Unverified Commit ef3fa840 authored by gaoyan's avatar gaoyan Committed by GitHub

Refactor app submit with sql file (#3315)

parent 39324f50
...@@ -26,6 +26,7 @@ import org.dinky.app.util.FlinkAppUtil; ...@@ -26,6 +26,7 @@ import org.dinky.app.util.FlinkAppUtil;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader; import org.dinky.classloader.DinkyClassLoader;
import org.dinky.config.Dialect; import org.dinky.config.Dialect;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.constant.FlinkSQLConstant; import org.dinky.constant.FlinkSQLConstant;
import org.dinky.data.app.AppParamConfig; import org.dinky.data.app.AppParamConfig;
import org.dinky.data.app.AppTask; import org.dinky.data.app.AppTask;
...@@ -48,6 +49,7 @@ import org.dinky.utils.ZipUtils; ...@@ -48,6 +49,7 @@ import org.dinky.utils.ZipUtils;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig; import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.core.execution.JobClient; import org.apache.flink.core.execution.JobClient;
import org.apache.flink.python.PythonOptions; import org.apache.flink.python.PythonOptions;
...@@ -63,6 +65,7 @@ import java.lang.reflect.InvocationTargetException; ...@@ -63,6 +65,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -73,23 +76,21 @@ import java.util.Map; ...@@ -73,23 +76,21 @@ import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.URLUtil; import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
/** /**
* FlinkSQLFactory * FlinkSQLFactory
* *
* @since 2021/10/27 * @since 2021/10/27
*/ */
@Slf4j
public class Submitter { public class Submitter {
private static final Logger log = LoggerFactory.getLogger(Submitter.class);
public static Executor executor = null; public static Executor executor = null;
private static void initSystemConfiguration() throws SQLException { private static void initSystemConfiguration() throws SQLException {
...@@ -108,7 +109,6 @@ public class Submitter { ...@@ -108,7 +109,6 @@ public class Submitter {
log.info("{} Start Submit Job:{}", LocalDateTime.now(), config.getTaskId()); log.info("{} Start Submit Job:{}", LocalDateTime.now(), config.getTaskId());
AppTask appTask = DBUtil.getTask(config.getTaskId()); AppTask appTask = DBUtil.getTask(config.getTaskId());
String sql = buildSql(appTask);
ExecutorConfig executorConfig = ExecutorConfig.builder() ExecutorConfig executorConfig = ExecutorConfig.builder()
.type(appTask.getType()) .type(appTask.getType())
...@@ -130,6 +130,7 @@ public class Submitter { ...@@ -130,6 +130,7 @@ public class Submitter {
loadDep(appTask.getType(), config.getTaskId(), executorConfig); loadDep(appTask.getType(), config.getTaskId(), executorConfig);
log.info("The job configuration is as follows: {}", executorConfig); log.info("The job configuration is as follows: {}", executorConfig);
String sql = readSql(executor);
String[] statements = SqlUtil.getStatements(sql); String[] statements = SqlUtil.getStatements(sql);
Optional<JobClient> jobClient = Optional.empty(); Optional<JobClient> jobClient = Optional.empty();
try { try {
...@@ -149,31 +150,21 @@ public class Submitter { ...@@ -149,31 +150,21 @@ public class Submitter {
} }
} }
public static String buildSql(AppTask appTask) throws SQLException { private static String readSql(Executor executor) {
StringBuilder sb = new StringBuilder(); Configuration configuration =
(Configuration) executor.getStreamExecutionEnvironment().getConfiguration();
// 1. build Database golbal varibals String sqlFileName = configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE);
// Note: It is necessary to first build the global variables defined in the database and registry, otherwise it String confDir = configuration.get(CustomerConfigureOptions.DINKY_CONF_DIR);
// may cause some variables to be unable to be resolved and referenced properly due to order issues File sqlFile = new File(sqlFileName);
if (appTask.getFragment()) { if (!sqlFile.exists()) {
log.info("Global env is enable, load database flink config env and global variables."); sqlFile = new File(confDir, sqlFileName);
// append database flink config env if (!sqlFile.exists()) {
sb.append(DBUtil.getDbSourceSQLStatement()).append("\n"); log.error("sql file not found,current dir:{},conf dir:{}", System.getProperty("user.dir"), confDir);
// append global variables throw new RuntimeException("sql file not found");
sb.append(DBUtil.getGlobalVariablesStatement()).append("\n");
}
// 2. build env task
if (Asserts.isNotNull(appTask.getEnvId()) && appTask.getEnvId() > 0) {
AppTask envTask = DBUtil.getTask(appTask.getEnvId());
if (Asserts.isNotNullString(envTask.getStatement())) {
log.info("use statement is enable, load env:{}", envTask.getName());
sb.append(envTask.getStatement()).append("\n");
} }
} }
log.info("start read sql file path:{}", sqlFile.getAbsolutePath());
sb.append(appTask.getStatement()); return FileUtil.readString(sqlFile, Charset.defaultCharset());
return sb.toString();
} }
private static void loadDep(String type, Integer taskId, ExecutorConfig executorConfig) { private static void loadDep(String type, Integer taskId, ExecutorConfig executorConfig) {
......
...@@ -45,4 +45,15 @@ public class CustomerConfigureOptions { ...@@ -45,4 +45,15 @@ public class CustomerConfigureOptions {
public static final ConfigOption<Integer> DINKY_PORT = public static final ConfigOption<Integer> DINKY_PORT =
key("dinky.dinkyPort").intType().defaultValue(7125).withDescription("dinky local port"); key("dinky.dinkyPort").intType().defaultValue(7125).withDescription("dinky local port");
public static final ConfigOption<String> EXEC_SQL_FILE = key("dinky.sql.file")
.stringType()
.defaultValue("job.sql")
.withDescription("dinky exec sql file name at application model");
public static final ConfigOption<String> DINKY_CONF_DIR = key("kubernetes.dinky.conf.dir")
.stringType()
.defaultValue("/opt/dinky/sql-exec/")
.withDescription(
"The dinky configuration directory. It is used to mount the ConfigMap to the Flink container.");
} }
...@@ -65,6 +65,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; ...@@ -65,6 +65,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -111,8 +112,10 @@ public class Explainer { ...@@ -111,8 +112,10 @@ public class Explainer {
List<StatementParam> execute = new ArrayList<>(); List<StatementParam> execute = new ArrayList<>();
List<String> statementList = new ArrayList<>(); List<String> statementList = new ArrayList<>();
List<UDF> udfList = new ArrayList<>(); List<UDF> udfList = new ArrayList<>();
StrBuilder parsedSql = new StrBuilder();
for (String item : statements) { for (String item : statements) {
String statement = executor.pretreatStatement(item); String statement = executor.pretreatStatement(item);
parsedSql.append(statement).append(";\n");
if (statement.isEmpty()) { if (statement.isEmpty()) {
continue; continue;
} }
...@@ -169,7 +172,7 @@ public class Explainer { ...@@ -169,7 +172,7 @@ public class Explainer {
statementList.add(statement); statementList.add(statement);
} }
} }
return new JobParam(statementList, ddl, trans, execute, CollUtil.removeNull(udfList)); return new JobParam(statementList, ddl, trans, execute, CollUtil.removeNull(udfList), parsedSql.toString());
} }
private Configuration getCombinationConfig() { private Configuration getCombinationConfig() {
......
...@@ -91,14 +91,17 @@ import java.util.Collections; ...@@ -91,14 +91,17 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@Data
public class JobManager { public class JobManager {
private JobHandler handler; private JobHandler handler;
private ExecutorConfig executorConfig; private ExecutorConfig executorConfig;
...@@ -250,6 +253,10 @@ public class JobManager { ...@@ -250,6 +253,10 @@ public class JobManager {
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE) @ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeJarSql(String statement) throws Exception { public JobResult executeJarSql(String statement) throws Exception {
List<String> statements = Arrays.stream(SqlUtil.getStatements(statement))
.map(t -> executor.pretreatStatement(t))
.collect(Collectors.toList());
statement = String.join(";\n", statements);
job = Job.build(runMode, config, executorConfig, executor, statement, useGateway); job = Job.build(runMode, config, executorConfig, executor, statement, useGateway);
ready(); ready();
JobJarStreamGraphBuilder jobJarStreamGraphBuilder = JobJarStreamGraphBuilder.build(this); JobJarStreamGraphBuilder jobJarStreamGraphBuilder = JobJarStreamGraphBuilder.build(this);
...@@ -282,6 +289,7 @@ public class JobManager { ...@@ -282,6 +289,7 @@ public class JobManager {
GatewayResult gatewayResult; GatewayResult gatewayResult;
config.addGatewayConfig(configuration); config.addGatewayConfig(configuration);
if (runMode.isApplicationMode()) { if (runMode.isApplicationMode()) {
config.getGatewayConfig().setSql(statement);
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar(getUdfPathContextHolder()); gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar(getUdfPathContextHolder());
} else { } else {
streamGraph.setJobName(config.getJobName()); streamGraph.setJobName(config.getJobName());
...@@ -351,7 +359,7 @@ public class JobManager { ...@@ -351,7 +359,7 @@ public class JobManager {
} }
} catch (Exception e) { } catch (Exception e) {
String errorMessage = e.getMessage(); String errorMessage = e.getMessage();
if (errorMessage.contains("Only insert statement is supported now")) { if (errorMessage != null && errorMessage.contains("Only insert statement is supported now")) {
throw new BusException(Status.OPERATE_NOT_SUPPORT_QUERY.getMessage()); throw new BusException(Status.OPERATE_NOT_SUPPORT_QUERY.getMessage());
} }
String error = StrFormatter.format( String error = StrFormatter.format(
......
...@@ -24,11 +24,14 @@ import org.dinky.function.data.model.UDF; ...@@ -24,11 +24,14 @@ import org.dinky.function.data.model.UDF;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import lombok.Data;
/** /**
* JobParam * JobParam
* *
* @since 2021/11/16 * @since 2021/11/16
*/ */
@Data
public class JobParam { public class JobParam {
private List<String> statements; private List<String> statements;
...@@ -36,6 +39,7 @@ public class JobParam { ...@@ -36,6 +39,7 @@ public class JobParam {
private List<StatementParam> trans; private List<StatementParam> trans;
private List<StatementParam> execute; private List<StatementParam> execute;
private List<UDF> udfList; private List<UDF> udfList;
private String parsedSql;
public JobParam(List<UDF> udfList) { public JobParam(List<UDF> udfList) {
this.udfList = udfList; this.udfList = udfList;
...@@ -62,12 +66,14 @@ public class JobParam { ...@@ -62,12 +66,14 @@ public class JobParam {
List<StatementParam> ddl, List<StatementParam> ddl,
List<StatementParam> trans, List<StatementParam> trans,
List<StatementParam> execute, List<StatementParam> execute,
List<UDF> udfList) { List<UDF> udfList,
String parsedSql) {
this.statements = statements; this.statements = statements;
this.ddl = ddl; this.ddl = ddl;
this.trans = trans; this.trans = trans;
this.execute = execute; this.execute = execute;
this.udfList = udfList; this.udfList = udfList;
this.parsedSql = parsedSql;
} }
public List<String> getStatements() { public List<String> getStatements() {
......
...@@ -186,7 +186,7 @@ public class JobTransBuilder extends JobBuilder { ...@@ -186,7 +186,7 @@ public class JobTransBuilder extends JobBuilder {
// Use gateway need to build gateway config, include flink configuration. // Use gateway need to build gateway config, include flink configuration.
config.addGatewayConfig(executor.getCustomTableEnvironment().getConfig().getConfiguration()); config.addGatewayConfig(executor.getCustomTableEnvironment().getConfig().getConfiguration());
config.getGatewayConfig().setSql(jobParam.getParsedSql());
if (runMode.isApplicationMode()) { if (runMode.isApplicationMode()) {
// Application mode need to submit dinky-app.jar that in the hdfs or image. // Application mode need to submit dinky-app.jar that in the hdfs or image.
gatewayResult = Gateway.build(config.getGatewayConfig()) gatewayResult = Gateway.build(config.getGatewayConfig())
......
...@@ -47,6 +47,13 @@ public class GatewayConfig { ...@@ -47,6 +47,13 @@ public class GatewayConfig {
notes = "ID of the task") notes = "ID of the task")
private Integer taskId; private Integer taskId;
@ApiModelProperty(
value = "SQL statement to be executed",
dataType = "String",
example = "SELECT * FROM table",
notes = "SQL statement")
private String sql;
@ApiModelProperty( @ApiModelProperty(
value = "Paths to the JAR files", value = "Paths to the JAR files",
dataType = "String[]", dataType = "String[]",
......
...@@ -25,8 +25,10 @@ import org.dinky.data.enums.GatewayType; ...@@ -25,8 +25,10 @@ import org.dinky.data.enums.GatewayType;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.gateway.config.AppConfig; import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.exception.GatewayException; import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.IgnoreNullRepresenter;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult; import org.dinky.gateway.result.KubernetesResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.api.common.JobStatus; import org.apache.flink.api.common.JobStatus;
import org.apache.flink.client.deployment.ClusterDeploymentException; import org.apache.flink.client.deployment.ClusterDeploymentException;
...@@ -34,8 +36,10 @@ import org.apache.flink.client.deployment.ClusterSpecification; ...@@ -34,8 +36,10 @@ import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.application.ApplicationConfiguration; import org.apache.flink.client.deployment.application.ApplicationConfiguration;
import org.apache.flink.client.program.ClusterClient; import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ClusterClientProvider; import org.apache.flink.client.program.ClusterClientProvider;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor; import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions; import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.utils.Constants; import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.runtime.client.JobStatusMessage; import org.apache.flink.runtime.client.JobStatusMessage;
...@@ -43,24 +47,32 @@ import java.util.Collection; ...@@ -43,24 +47,32 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.representer.Representer;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import io.fabric8.kubernetes.api.model.ContainerStatus; import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
/** /**
* KubernetesApplicationGateway * KubernetesApplicationGateway
*/ */
@Slf4j
public class KubernetesApplicationGateway extends KubernetesGateway { public class KubernetesApplicationGateway extends KubernetesGateway {
private final String tmpConfDir =
String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
/** /**
* @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION. * @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION.
*/ */
...@@ -69,6 +81,24 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -69,6 +81,24 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
return GatewayType.KUBERNETES_APPLICATION; return GatewayType.KUBERNETES_APPLICATION;
} }
@Override
public void init() {
super.init();
Pod decoratedPodTemplate = getK8sClientHelper().decoratePodTemplate(config.getSql());
// use snakyaml to serialize the pod
Representer representer = new IgnoreNullRepresenter();
// set the label of the Map type, only the map type will not print the class name when dumping
representer.addClassTag(Pod.class, Tag.MAP);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(representer, options);
preparPodTemplate(yaml.dump(decoratedPodTemplate), KubernetesConfigOptions.KUBERNETES_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getJmPodTemplate(), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getTmPodTemplate(), KubernetesConfigOptions.TASK_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getKubeConfig(), KubernetesConfigOptions.KUBE_CONFIG_FILE);
}
/** /**
* Submits a jar file to the Kubernetes gateway. * Submits a jar file to the Kubernetes gateway.
* *
...@@ -76,16 +106,16 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -76,16 +106,16 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
*/ */
@Override @Override
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) { public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
try { init();
try (KubernetesClient kubernetesClient = getK8sClientHelper().getKubernetesClient()) {
logger.info("Start submit k8s application."); logger.info("Start submit k8s application.");
ClusterClientProvider<String> clusterClient = deployApplication();
Deployment deployment = kubernetesClient ClusterClientProvider<String> clusterClient =
.apps() deployApplication(getK8sClientHelper().getClient());
.deployments()
.inNamespace(configuration.getString(KubernetesConfigOptions.NAMESPACE)) Deployment deployment = getK8sClientHelper().createDinkyResource();
.withName(configuration.getString(KubernetesConfigOptions.CLUSTER_ID))
.get(); KubernetesResult kubernetesResult = waitForJmAndJobStart(kubernetesClient, deployment, clusterClient);
KubernetesResult kubernetesResult = waitForJmAndJobStart(deployment, clusterClient);
kubernetesResult.success(); kubernetesResult.success();
return kubernetesResult; return kubernetesResult;
} catch (Exception ex) { } catch (Exception ex) {
...@@ -110,7 +140,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -110,7 +140,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
ContainerStatus containerStatus = ContainerStatus containerStatus =
flinContainer.orElseThrow(() -> new GatewayException("Deploy k8s failed, can't find flink container")); flinContainer.orElseThrow(() -> new GatewayException("Deploy k8s failed, can't find flink container"));
Yaml yaml = new Yaml(new LogRepresenter()); Yaml yaml = new Yaml(new IgnoreNullRepresenter());
String logStr = StrFormatter.format( String logStr = StrFormatter.format(
"Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n" "Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n"
+ "------CurrentState------\n{}\n------LastState------\n{}", + "------CurrentState------\n{}\n------LastState------\n{}",
...@@ -134,10 +164,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -134,10 +164,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
* @return A ClusterClientProvider<String> object for accessing the Kubernetes cluster. * @return A ClusterClientProvider<String> object for accessing the Kubernetes cluster.
* @throws ClusterDeploymentException if deployment to Kubernetes fails. * @throws ClusterDeploymentException if deployment to Kubernetes fails.
*/ */
public ClusterClientProvider<String> deployApplication() throws ClusterDeploymentException { public ClusterClientProvider<String> deployApplication(FlinkKubeClient client) throws ClusterDeploymentException {
if (Asserts.isNull(client)) {
init();
}
// Build the commit information // Build the commit information
AppConfig appConfig = config.getAppConfig(); AppConfig appConfig = config.getAppConfig();
String[] userJarParas = String[] userJarParas =
...@@ -161,7 +188,8 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -161,7 +188,8 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
* @return A KubernetesResult object containing the Kubernetes gateway's Web URL, the Job ID, and the cluster ID. * @return A KubernetesResult object containing the Kubernetes gateway's Web URL, the Job ID, and the cluster ID.
* @throws InterruptedException if waiting is interrupted. * @throws InterruptedException if waiting is interrupted.
*/ */
public KubernetesResult waitForJmAndJobStart(Deployment deployment, ClusterClientProvider<String> clusterClient) public KubernetesResult waitForJmAndJobStart(
KubernetesClient kubernetesClient, Deployment deployment, ClusterClientProvider<String> clusterClient)
throws InterruptedException { throws InterruptedException {
KubernetesResult result = KubernetesResult.build(getType()); KubernetesResult result = KubernetesResult.build(getType());
long waitSends = SystemConfiguration.getInstances().getJobIdWait() * 1000L; long waitSends = SystemConfiguration.getInstances().getJobIdWait() * 1000L;
...@@ -208,27 +236,19 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -208,27 +236,19 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
"The number of retries exceeds the limit, check the K8S cluster for more information"); "The number of retries exceeds the limit, check the K8S cluster for more information");
} }
/** private void preparPodTemplate(String podTemplate, ConfigOption<String> option) {
* Represents Java Bean properties for YAML serialization with LogRepresenter. if (!TextUtil.isEmpty(podTemplate)) {
* If the property value is null, it is ignored. String filePath = String.format("%s/%s.yaml", tmpConfDir, option.key());
*/ if (FileUtil.exist(filePath)) {
static class LogRepresenter extends Representer { Assert.isTrue(FileUtil.del(filePath));
/**
* Represents the Java Bean property, ignoring null and empty values.
*
* @param javaBean The Java Bean object.
* @param property The property to represent.
* @param propertyValue The value of the property.
* @param tag The custom tag.
* @return The represented node tuple, or null if the property value is null.
*/
@Override
protected NodeTuple representJavaBeanProperty(
Object javaBean, Property property, Object propertyValue, Tag tag) {
if (propertyValue == null) {
return null;
} }
return super.representJavaBeanProperty(javaBean, property, propertyValue, tag); FileUtil.writeUtf8String(podTemplate, filePath);
addConfigParas(option, filePath);
} }
} }
public boolean close() {
super.close();
return FileUtil.del(tmpConfDir);
}
} }
...@@ -25,11 +25,10 @@ import org.dinky.gateway.AbstractGateway; ...@@ -25,11 +25,10 @@ import org.dinky.gateway.AbstractGateway;
import org.dinky.gateway.config.FlinkConfig; import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.K8sConfig; import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.exception.GatewayException; import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.K8sClientHelper;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.DeploymentOptions; import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.GlobalConfiguration;
...@@ -39,43 +38,39 @@ import org.apache.flink.kubernetes.KubernetesClusterDescriptor; ...@@ -39,43 +38,39 @@ import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions; import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient; import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient; import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.python.PythonOptions; import org.apache.flink.python.PythonOptions;
import org.apache.http.util.TextUtils;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import java.util.UUID; import java.util.UUID;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import io.fabric8.kubernetes.client.Config; import lombok.Data;
import io.fabric8.kubernetes.client.DefaultKubernetesClient; import lombok.EqualsAndHashCode;
import io.fabric8.kubernetes.client.KubernetesClient; import lombok.extern.slf4j.Slf4j;
/** /**
* KubernetesGateway * KubernetesGateway
*/ */
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class KubernetesGateway extends AbstractGateway { public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkKubeClient client;
protected KubernetesClient kubernetesClient;
protected String flinkConfigPath; protected String flinkConfigPath;
protected FlinkConfig flinkConfig; protected FlinkConfig flinkConfig;
protected K8sConfig k8sConfig; protected K8sConfig k8sConfig;
protected String tmpConfDir;
private K8sClientHelper k8sClientHelper;
public KubernetesGateway() {} public KubernetesGateway() {}
public void init() { public void init() {
initConfig(); initConfig();
initKubeClient();
} }
private void initConfig() { protected void initConfig() {
tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
flinkConfigPath = config.getClusterConfig().getFlinkConfigPath(); flinkConfigPath = config.getClusterConfig().getFlinkConfigPath();
flinkConfig = config.getFlinkConfig(); flinkConfig = config.getFlinkConfig();
k8sConfig = config.getKubernetesConfig(); k8sConfig = config.getKubernetesConfig();
...@@ -96,41 +91,18 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -96,41 +91,18 @@ public abstract class KubernetesGateway extends AbstractGateway {
PipelineOptions.JARS, PipelineOptions.JARS,
Collections.singletonList(config.getAppConfig().getUserJarPath())); Collections.singletonList(config.getAppConfig().getUserJarPath()));
preparPodTemplate(k8sConfig.getPodTemplate(), KubernetesConfigOptions.KUBERNETES_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getJmPodTemplate(), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getTmPodTemplate(), KubernetesConfigOptions.TASK_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getKubeConfig(), KubernetesConfigOptions.KUBE_CONFIG_FILE);
if (getType().isApplicationMode()) { if (getType().isApplicationMode()) {
// remove python file // remove python file
configuration.removeConfig(PythonOptions.PYTHON_FILES); configuration.removeConfig(PythonOptions.PYTHON_FILES);
resetCheckpointInApplicationMode(flinkConfig.getJobName()); resetCheckpointInApplicationMode(flinkConfig.getJobName());
} }
}
private void preparPodTemplate(String podTemplate, ConfigOption<String> option) {
if (!TextUtil.isEmpty(podTemplate)) {
String filePath = String.format("%s/%s.yaml", tmpConfDir, option.key());
if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath));
}
FileUtil.writeUtf8String(podTemplate, filePath);
addConfigParas(option, filePath);
}
}
private void initKubeClient() { k8sClientHelper = new K8sClientHelper(configuration, k8sConfig);
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) {
kubernetesClient = new DefaultKubernetesClient();
} else {
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(k8sConfig.getKubeConfig()));
}
} }
public SavePointResult savepointCluster(String savePoint) { public SavePointResult savepointCluster(String savePoint) {
if (Asserts.isNull(client)) { if (Asserts.isNull(k8sClientHelper.getClient())) {
init(); initConfig();
} }
KubernetesClusterClientFactory clusterClientFactory = new KubernetesClusterClientFactory(); KubernetesClusterClientFactory clusterClientFactory = new KubernetesClusterClientFactory();
...@@ -148,8 +120,8 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -148,8 +120,8 @@ public abstract class KubernetesGateway extends AbstractGateway {
} }
public SavePointResult savepointJob(String savePoint) { public SavePointResult savepointJob(String savePoint) {
if (Asserts.isNull(client)) { if (Asserts.isNull(k8sClientHelper.getClient())) {
init(); initConfig();
} }
if (Asserts.isNull(config.getFlinkConfig().getJobId())) { if (Asserts.isNull(config.getFlinkConfig().getJobId())) {
throw new GatewayException( throw new GatewayException(
...@@ -171,10 +143,10 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -171,10 +143,10 @@ public abstract class KubernetesGateway extends AbstractGateway {
public TestResult test() { public TestResult test() {
try { try {
initConfig();
// Test mode no jobName, use uuid . // Test mode no jobName, use uuid .
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, UUID.randomUUID().toString()); addConfigParas(KubernetesConfigOptions.CLUSTER_ID, UUID.randomUUID().toString());
initKubeClient(); initConfig();
FlinkKubeClient client = k8sClientHelper.getClient();
if (client instanceof Fabric8FlinkKubeClient) { if (client instanceof Fabric8FlinkKubeClient) {
Object internalClient = ReflectUtil.getFieldValue(client, "internalClient"); Object internalClient = ReflectUtil.getFieldValue(client, "internalClient");
Method method = ReflectUtil.getMethod(internalClient.getClass(), "getVersion"); Method method = ReflectUtil.getMethod(internalClient.getClass(), "getVersion");
...@@ -196,8 +168,8 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -196,8 +168,8 @@ public abstract class KubernetesGateway extends AbstractGateway {
@Override @Override
public void killCluster() { public void killCluster() {
if (Asserts.isNull(client)) { if (Asserts.isNull(k8sClientHelper.getClient())) {
init(); initConfig();
} }
addConfigParas( addConfigParas(
KubernetesConfigOptions.CLUSTER_ID, config.getClusterConfig().getAppId()); KubernetesConfigOptions.CLUSTER_ID, config.getClusterConfig().getAppId());
...@@ -207,22 +179,19 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -207,22 +179,19 @@ public abstract class KubernetesGateway extends AbstractGateway {
throw new GatewayException( throw new GatewayException(
"No cluster id was specified. Please specify a cluster to which you would like" + " to connect."); "No cluster id was specified. Please specify a cluster to which you would like" + " to connect.");
} }
KubernetesClusterDescriptor clusterDescriptor = clusterClientFactory.createClusterDescriptor(configuration);
try { try (KubernetesClusterDescriptor clusterDescriptor =
clusterClientFactory.createClusterDescriptor(configuration)) {
clusterDescriptor.killCluster(clusterId); clusterDescriptor.killCluster(clusterId);
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); logger.error(e.getMessage(), e);
} }
} }
public void close() { public boolean close() {
if (client != null) { if (k8sClientHelper != null) {
client.close(); return k8sClientHelper.close();
}
if (kubernetesClient != null) {
kubernetesClient.close();
} }
FileUtil.del(tmpConfDir); return true;
} }
} }
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
package org.dinky.gateway.kubernetes; package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.GatewayType; import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
...@@ -47,18 +46,16 @@ public class KubernetesSessionGateway extends KubernetesGateway { ...@@ -47,18 +46,16 @@ public class KubernetesSessionGateway extends KubernetesGateway {
@Override @Override
public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) { public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) {
if (Asserts.isNull(client)) { String clusterId = StrFormatter.format("dinky-flink-session-{}", System.currentTimeMillis());
String clusterId = StrFormatter.format("dinky-flink-session-{}", System.currentTimeMillis()); addConfigParas(KubernetesConfigOptions.CLUSTER_ID, clusterId);
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, clusterId); init();
init();
}
ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder = ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder =
createClusterSpecificationBuilder(); createClusterSpecificationBuilder();
KubernetesResult result = KubernetesResult.build(getType()); KubernetesResult result = KubernetesResult.build(getType());
try (KubernetesClusterDescriptor kubernetesClusterDescriptor = try (KubernetesClusterDescriptor kubernetesClusterDescriptor = new KubernetesClusterDescriptor(
new KubernetesClusterDescriptor(configuration, client)) { configuration, getK8sClientHelper().getClient())) {
ClusterClientProvider<String> clusterClientProvider = kubernetesClusterDescriptor.deploySessionCluster( ClusterClientProvider<String> clusterClientProvider = kubernetesClusterDescriptor.deploySessionCluster(
clusterSpecificationBuilder.createClusterSpecification()); clusterSpecificationBuilder.createClusterSpecification());
ClusterClient<String> clusterClient = clusterClientProvider.getClusterClient(); ClusterClient<String> clusterClient = clusterClientProvider.getClusterClient();
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.gateway.kubernetes.decorate;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.gateway.kubernetes.utils.DinkyKubernetsConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.utils.Constants;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.fabric8.kubernetes.api.model.ConfigMap;
import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.ContainerBuilder;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KeyToPath;
import io.fabric8.kubernetes.api.model.KeyToPathBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.PodSpecBuilder;
import io.fabric8.kubernetes.api.model.Volume;
import io.fabric8.kubernetes.api.model.VolumeBuilder;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class DinkySqlConfigMapDecorate {
private Pod podWithoutMainContainer;
private Container mainContainer;
private final Configuration configuration;
private final String sqlStatement;
public DinkySqlConfigMapDecorate(Configuration configuration, Pod pod, String sqlStatement) {
if (!configuration.contains(KubernetesConfigOptions.CLUSTER_ID)) {
throw new IllegalArgumentException(KubernetesConfigOptions.CLUSTER_ID.key() + " must not be blank.");
}
this.configuration = configuration;
this.sqlStatement = sqlStatement;
decorateFlinkPod(pod);
}
public Pod decoratePodMount() {
final Pod mountedPod = decoratePodVolume();
final Container mountedMainContainer = new ContainerBuilder(mainContainer)
.addNewVolumeMount()
.withName(DinkyKubernetsConstants.DINKY_CONF_VOLUME)
.withMountPath(configuration.get(CustomerConfigureOptions.DINKY_CONF_DIR))
.endVolumeMount()
.build();
return new PodBuilder(mountedPod)
.editOrNewSpec()
.addToContainers(mountedMainContainer)
.endSpec()
.build();
}
private void decorateFlinkPod(Pod pod) {
final List<Container> otherContainers = new ArrayList<>();
podWithoutMainContainer = new PodBuilder(pod).build();
if (null != podWithoutMainContainer.getSpec()) {
for (Container container : podWithoutMainContainer.getSpec().getContainers()) {
if (Constants.MAIN_CONTAINER_NAME.equals(container.getName())) {
mainContainer = container;
} else {
otherContainers.add(container);
}
}
podWithoutMainContainer.getSpec().setContainers(otherContainers);
} else {
podWithoutMainContainer.setSpec(new PodSpecBuilder().build());
}
if (mainContainer == null) {
log.info(
"Could not find main container {} in pod template, using empty one to initialize.",
Constants.MAIN_CONTAINER_NAME);
mainContainer = new ContainerBuilder()
.withName(Constants.MAIN_CONTAINER_NAME)
.build();
}
}
private Pod decoratePodVolume() {
final List<KeyToPath> keyToPaths = Collections.singletonList(new KeyToPathBuilder()
.withKey(configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE))
.withPath(configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE))
.build());
final Volume sqlConfigVolume = new VolumeBuilder()
.withName(DinkyKubernetsConstants.DINKY_CONF_VOLUME)
.withNewConfigMap()
.withName(dinkyConfMapName())
.withItems(keyToPaths)
.endConfigMap()
.build();
return new PodBuilder(podWithoutMainContainer)
.editSpec()
.addNewVolumeLike(sqlConfigVolume)
.endVolume()
.endSpec()
.build();
}
public List<HasMetadata> buildResources() {
final String clusterId = configuration.get(KubernetesConfigOptions.CLUSTER_ID);
final Map<String, String> data = new HashMap<>();
data.put(configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE), sqlStatement);
final Map<String, String> commonLabels = new HashMap<>();
commonLabels.put(Constants.LABEL_TYPE_KEY, Constants.LABEL_TYPE_NATIVE_TYPE);
commonLabels.put(Constants.LABEL_APP_KEY, clusterId);
final ConfigMap flinkConfConfigMap = new ConfigMapBuilder()
.withApiVersion(Constants.API_VERSION)
.withNewMetadata()
.withName(dinkyConfMapName())
.withLabels(Collections.unmodifiableMap(commonLabels))
.withNamespace(configuration.get(KubernetesConfigOptions.NAMESPACE))
.endMetadata()
.addToData(data)
.build();
return Collections.singletonList(flinkConfConfigMap);
}
private String dinkyConfMapName() {
return DinkyKubernetsConstants.DINKY_CONF_VOLUME_PERFIX + configuration.get(KubernetesConfigOptions.CLUSTER_ID);
}
}
...@@ -21,10 +21,8 @@ package org.dinky.gateway.kubernetes.operator; ...@@ -21,10 +21,8 @@ package org.dinky.gateway.kubernetes.operator;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.enums.JobStatus; import org.dinky.data.enums.JobStatus;
import org.dinky.gateway.AbstractGateway;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.enums.UpgradeMode; import org.dinky.gateway.enums.UpgradeMode;
import org.dinky.gateway.kubernetes.KubernetesGateway;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec; import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec.Resource; import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec.Resource;
import org.dinky.gateway.kubernetes.operator.api.FlinkDeployment; import org.dinky.gateway.kubernetes.operator.api.FlinkDeployment;
...@@ -35,77 +33,60 @@ import org.dinky.gateway.result.TestResult; ...@@ -35,77 +33,60 @@ import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil; import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.http.util.TextUtils; import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true) @EqualsAndHashCode(callSuper = true)
@Data @Data
public abstract class KubernetsOperatorGateway extends AbstractGateway { public abstract class KubernetsOperatorGateway extends KubernetesGateway {
private Map<String, String> kubernetsConfiguration; private Map<String, String> kubernetsConfiguration;
private K8sConfig k8sConfig;
private FlinkConfig flinkConfig;
private FlinkDeployment flinkDeployment = new FlinkDeployment(); private FlinkDeployment flinkDeployment = new FlinkDeployment();
private FlinkDeploymentSpec flinkDeploymentSpec = new FlinkDeploymentSpec(); private FlinkDeploymentSpec flinkDeploymentSpec = new FlinkDeploymentSpec();
private KubernetesClient kubernetesClient;
private static final Logger logger = LoggerFactory.getLogger(KubernetsOperatorGateway.class); private static final Logger logger = LoggerFactory.getLogger(KubernetsOperatorGateway.class);
@Override @Override
protected void init() { public void init() {
initKubeClient(); kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
initConfig();
initBase(); initBase();
initMetadata(); initMetadata();
initSpec(); initSpec();
initResource(kubernetesClient); initResource(getK8sClientHelper().getKubernetesClient());
initJob(); initJob();
} }
private void initKubeClient() {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
flinkConfig = config.getFlinkConfig();
k8sConfig = config.getKubernetesConfig();
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) {
kubernetesClient = new DefaultKubernetesClient();
} else {
kubernetesClient = DefaultKubernetesClient.fromConfig(k8sConfig.getKubeConfig());
}
}
@Override @Override
public TestResult test() { public TestResult test() {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration(); kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
flinkConfig = config.getFlinkConfig(); addConfigParas(KubernetesConfigOptions.CLUSTER_ID, UUID.randomUUID().toString());
config.getFlinkConfig().setJobName("test");
initKubeClient(); initConfig();
initBase(); initBase();
initMetadata(); initMetadata();
initSpec(); initSpec();
kubernetesClient.resource(flinkDeployment).fromServer(); getK8sClientHelper().getKubernetesClient().nodes().list();
logger.info("配置连接测试成功"); logger.info("配置连接测试成功");
return TestResult.success(); return TestResult.success();
} }
@Override @Override
public boolean onJobFinishCallback(String status) { public boolean onJobFinishCallback(String status) {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
initKubeClient();
String jobName = config.getFlinkConfig().getJobName(); String jobName = config.getFlinkConfig().getJobName();
if (status.equals(JobStatus.FINISHED.getValue())) { if (status.equals(JobStatus.FINISHED.getValue())) {
logger.info( logger.info(
...@@ -119,8 +100,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -119,8 +100,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
} }
public boolean deleteCluster() { public boolean deleteCluster() {
initConfig();
initMetadata(); initMetadata();
kubernetesClient.resource(flinkDeployment).delete(); getK8sClientHelper().getKubernetesClient().resource(flinkDeployment).delete();
return true; return true;
} }
...@@ -175,12 +157,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -175,12 +157,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem); logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem);
taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem)); taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem));
if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) { defaultPod = getK8sClientHelper().decoratePodTemplate(config.getSql());
InputStream inputStream = flinkDeploymentSpec.setPodTemplate(defaultPod);
new ByteArrayInputStream(k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8));
defaultPod = kubernetesClient.pods().load(inputStream).get();
flinkDeploymentSpec.setPodTemplate(defaultPod);
}
if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) { if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) {
InputStream inputStream = InputStream inputStream =
new ByteArrayInputStream(k8sConfig.getJmPodTemplate().getBytes(StandardCharsets.UTF_8)); new ByteArrayInputStream(k8sConfig.getJmPodTemplate().getBytes(StandardCharsets.UTF_8));
......
...@@ -60,12 +60,13 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa ...@@ -60,12 +60,13 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
try { try {
init(); init();
KubernetesClient kubernetesClient = getKubernetesClient(); KubernetesClient kubernetesClient = getK8sClientHelper().getKubernetesClient();
FlinkDeployment flinkDeployment = getFlinkDeployment(); FlinkDeployment flinkDeployment = getFlinkDeployment();
kubernetesClient.resource(flinkDeployment).delete(); kubernetesClient.resource(flinkDeployment).delete();
kubernetesClient.resource(flinkDeployment).waitUntilCondition(Objects::isNull, 1, TimeUnit.MINUTES); kubernetesClient.resource(flinkDeployment).waitUntilCondition(Objects::isNull, 1, TimeUnit.MINUTES);
kubernetesClient.resource(flinkDeployment).createOrReplace(); kubernetesClient.resource(flinkDeployment).createOrReplace();
logger.info("create flink deployment finish,wait for flink jobmanager ready");
FlinkDeployment flinkDeploymentResult = kubernetesClient FlinkDeployment flinkDeploymentResult = kubernetesClient
.resource(flinkDeployment) .resource(flinkDeployment)
...@@ -92,6 +93,9 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa ...@@ -92,6 +93,9 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
result.setJids(Collections.singletonList(jobId)); result.setJids(Collections.singletonList(jobId));
return true; return true;
} }
if (status.equals("DEPLOYING")) {
getK8sClientHelper().createDinkyResource();
}
return false; return false;
}, },
2, 2,
...@@ -125,7 +129,7 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa ...@@ -125,7 +129,7 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
} catch (KubernetesClientException e) { } catch (KubernetesClientException e) {
// some error while connecting to kube cluster // some error while connecting to kube cluster
result.fail(LogUtil.getError(e)); result.fail(LogUtil.getError(e));
e.printStackTrace(); throw e;
} }
logger.info( logger.info(
"submit {} job finish, web url is {}, jobid is {}", getType(), result.getWebURL(), result.getJids()); "submit {} job finish, web url is {}, jobid is {}", getType(), result.getWebURL(), result.getJids());
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.gateway.kubernetes.utils;
/** Constants for kubernetes. */
public class DinkyKubernetsConstants {
public static final String DINKY_CONF_VOLUME = "dinky-config-volume";
public static final String DINKY_CONF_VOLUME_PERFIX = "dinky-config-";
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.gateway.kubernetes.utils;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
/**
* Represents Java Bean properties for YAML serialization with LogRepresenter.
* If the property value is null, it is ignored.
*/
public class IgnoreNullRepresenter extends Representer {
/**
* Represents the Java Bean property, ignoring null and empty values.
*
* @param javaBean The Java Bean object.
* @param property The property to represent.
* @param propertyValue The value of the property.
* @param tag The custom tag.
* @return The represented node tuple, or null if the property value is null.
*/
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag tag) {
// Ignore null value
if (propertyValue == null) {
return null;
}
// Ignore empty map and list
if (propertyValue instanceof Map) {
if (((Map<?, ?>) propertyValue).isEmpty()) {
return null;
}
}
if (propertyValue instanceof List) {
if (((List<?>) propertyValue).isEmpty()) {
return null;
}
}
return super.representJavaBeanProperty(javaBean, property, propertyValue, tag);
}
}
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.gateway.kubernetes.utils;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.kubernetes.decorate.DinkySqlConfigMapDecorate;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.http.util.TextUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import cn.hutool.core.io.FileUtil;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.OwnerReference;
import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* K8sClientHelper
* manage k8s client
*/
@Data
@Slf4j
public class K8sClientHelper {
private FlinkKubeClient client;
private KubernetesClient kubernetesClient;
protected Configuration configuration;
private K8sConfig k8sConfig;
private String tmpConfDir;
private DinkySqlConfigMapDecorate sqlFileDecorate;
public K8sClientHelper(Configuration configuration, K8sConfig k8sConfig) {
this.configuration = configuration;
this.k8sConfig = k8sConfig;
tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
initKubeClient();
}
/**
* initKubeClient
*/
private void initKubeClient() {
// k8s flink native client
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
// k8s fabric client
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) {
kubernetesClient = new DefaultKubernetesClient();
} else {
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(k8sConfig.getKubeConfig()));
}
}
/**
* createDinkyResource
* Create the resources required by Dinky,
* and append the owner attribute of the deployment
* to automatically clear the related resources
* when the deployment is deleted
*/
public Deployment createDinkyResource() {
log.info("createDinkyResource");
Deployment deployment = kubernetesClient
.apps()
.deployments()
.inNamespace(configuration.getString(KubernetesConfigOptions.NAMESPACE))
.withName(configuration.getString(KubernetesConfigOptions.CLUSTER_ID))
.get();
List<HasMetadata> resources = getSqlFileDecorate().buildResources();
// set owner reference
OwnerReference deploymentOwnerReference = new OwnerReferenceBuilder()
.withName(deployment.getMetadata().getName())
.withApiVersion(deployment.getApiVersion())
.withUid(deployment.getMetadata().getUid())
.withKind(deployment.getKind())
.withController(true)
.withBlockOwnerDeletion(true)
.build();
resources.forEach(resource ->
resource.getMetadata().setOwnerReferences(Collections.singletonList(deploymentOwnerReference)));
// create resources
kubernetesClient.resourceList(resources).createOrReplace();
return deployment;
}
/**
* initPodTemplate
* Preprocess the pod template
* @param sqlStatement
* @return
*/
public Pod decoratePodTemplate(String sqlStatement) {
Pod pod;
// if the user has configured the pod template, combine user's configuration
if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) {
InputStream is = new ByteArrayInputStream(k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8));
pod = kubernetesClient.pods().load(is).get();
} else {
// if the user has not configured the pod template, use the default configuration
pod = new Pod();
}
// decorate the pod template
sqlFileDecorate = new DinkySqlConfigMapDecorate(configuration, pod, sqlStatement);
return sqlFileDecorate.decoratePodMount();
}
/**
* close
* delete the temporary directory and close the client
* @return
*/
public boolean close() {
if (client != null) {
client.close();
}
if (kubernetesClient != null) {
kubernetesClient.close();
}
try {
return FileUtil.del(tmpConfDir);
} catch (Exception e) {
log.warn("failed delete kubernetes temp dir: " + tmpConfDir);
}
return false;
}
}
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn; package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.GatewayType; import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.config.AppConfig; import org.dinky.gateway.config.AppConfig;
...@@ -39,6 +40,8 @@ import java.io.File; ...@@ -39,6 +40,8 @@ import java.io.File;
import java.util.Collections; import java.util.Collections;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
/** /**
* YarnApplicationGateway * YarnApplicationGateway
* *
...@@ -74,6 +77,11 @@ public class YarnApplicationGateway extends YarnGateway { ...@@ -74,6 +77,11 @@ public class YarnApplicationGateway extends YarnGateway {
YarnResult result = YarnResult.build(getType()); YarnResult result = YarnResult.build(getType());
String webUrl; String webUrl;
try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar(udfPathContextHolder)) { try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar(udfPathContextHolder)) {
yarnClusterDescriptor.addShipFiles(CollUtil.newArrayList(preparSqlFile()));
addConfigParas(
CustomerConfigureOptions.EXEC_SQL_FILE, configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE));
ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployApplicationCluster( ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployApplicationCluster(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration); clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration);
ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient(); ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient();
...@@ -86,6 +94,8 @@ public class YarnApplicationGateway extends YarnGateway { ...@@ -86,6 +94,8 @@ public class YarnApplicationGateway extends YarnGateway {
result.success(); result.success();
} catch (Exception e) { } catch (Exception e) {
result.fail(LogUtil.getError(e)); result.fail(LogUtil.getError(e));
} finally {
close();
} }
return result; return result;
} }
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn; package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.JobStatus; import org.dinky.data.enums.JobStatus;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
...@@ -73,7 +74,9 @@ import java.util.ArrayList; ...@@ -73,7 +74,9 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -86,6 +89,7 @@ import cn.hutool.http.HttpUtil; ...@@ -86,6 +89,7 @@ import cn.hutool.http.HttpUtil;
public abstract class YarnGateway extends AbstractGateway { public abstract class YarnGateway extends AbstractGateway {
private static final String HTML_TAG_REGEX = "<pre>(.*)</pre>"; private static final String HTML_TAG_REGEX = "<pre>(.*)</pre>";
private final String tmpConfDir = String.format("%s/tmp/%s", System.getProperty("user.dir"), UUID.randomUUID());
protected YarnConfiguration yarnConfiguration; protected YarnConfiguration yarnConfiguration;
...@@ -402,4 +406,16 @@ public abstract class YarnGateway extends AbstractGateway { ...@@ -402,4 +406,16 @@ public abstract class YarnGateway extends AbstractGateway {
} }
return "No history log found yet. so can't get log url, please check yarn cluster status or check if the flink job is running in yarn cluster or please go to yarn interface to view the log."; return "No history log found yet. so can't get log url, please check yarn cluster status or check if the flink job is running in yarn cluster or please go to yarn interface to view the log.";
} }
protected File preparSqlFile() {
File tempSqlFile =
new File(String.format("%s/%s", tmpConfDir, configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE)));
String sql = config == null ? "" : config.getSql();
FileUtil.writeString(Optional.ofNullable(sql).orElse(""), tempSqlFile.getAbsolutePath(), "UTF-8");
return tempSqlFile;
}
public boolean close() {
return FileUtil.del(tmpConfDir);
}
} }
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn; package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.data.enums.GatewayType; import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.YarnResult; import org.dinky.gateway.result.YarnResult;
...@@ -34,6 +35,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationId; ...@@ -34,6 +35,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationId;
import java.util.Arrays; import java.util.Arrays;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil; import cn.hutool.core.util.URLUtil;
...@@ -66,6 +68,9 @@ public class YarnPerJobGateway extends YarnGateway { ...@@ -66,6 +68,9 @@ public class YarnPerJobGateway extends YarnGateway {
YarnResult result = YarnResult.build(getType()); YarnResult result = YarnResult.build(getType());
try (YarnClusterDescriptor yarnClusterDescriptor = createInitYarnClusterDescriptor()) { try (YarnClusterDescriptor yarnClusterDescriptor = createInitYarnClusterDescriptor()) {
yarnClusterDescriptor.addShipFiles(CollUtil.newArrayList(preparSqlFile()));
addConfigParas(
CustomerConfigureOptions.EXEC_SQL_FILE, configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE));
ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployJobCluster( ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployJobCluster(
clusterSpecificationBuilder.createClusterSpecification(), jobGraph, true); clusterSpecificationBuilder.createClusterSpecification(), jobGraph, true);
ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient(); ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment