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;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.config.Dialect;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.data.app.AppParamConfig;
import org.dinky.data.app.AppTask;
......@@ -48,6 +49,7 @@ import org.dinky.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.python.PythonOptions;
......@@ -63,6 +65,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
......@@ -73,23 +76,21 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
/**
* FlinkSQLFactory
*
* @since 2021/10/27
*/
@Slf4j
public class Submitter {
private static final Logger log = LoggerFactory.getLogger(Submitter.class);
public static Executor executor = null;
private static void initSystemConfiguration() throws SQLException {
......@@ -108,7 +109,6 @@ public class Submitter {
log.info("{} Start Submit Job:{}", LocalDateTime.now(), config.getTaskId());
AppTask appTask = DBUtil.getTask(config.getTaskId());
String sql = buildSql(appTask);
ExecutorConfig executorConfig = ExecutorConfig.builder()
.type(appTask.getType())
......@@ -130,6 +130,7 @@ public class Submitter {
loadDep(appTask.getType(), config.getTaskId(), executorConfig);
log.info("The job configuration is as follows: {}", executorConfig);
String sql = readSql(executor);
String[] statements = SqlUtil.getStatements(sql);
Optional<JobClient> jobClient = Optional.empty();
try {
......@@ -149,31 +150,21 @@ public class Submitter {
}
}
public static String buildSql(AppTask appTask) throws SQLException {
StringBuilder sb = new StringBuilder();
// 1. build Database golbal varibals
// Note: It is necessary to first build the global variables defined in the database and registry, otherwise it
// may cause some variables to be unable to be resolved and referenced properly due to order issues
if (appTask.getFragment()) {
log.info("Global env is enable, load database flink config env and global variables.");
// append database flink config env
sb.append(DBUtil.getDbSourceSQLStatement()).append("\n");
// append global variables
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");
private static String readSql(Executor executor) {
Configuration configuration =
(Configuration) executor.getStreamExecutionEnvironment().getConfiguration();
String sqlFileName = configuration.get(CustomerConfigureOptions.EXEC_SQL_FILE);
String confDir = configuration.get(CustomerConfigureOptions.DINKY_CONF_DIR);
File sqlFile = new File(sqlFileName);
if (!sqlFile.exists()) {
sqlFile = new File(confDir, sqlFileName);
if (!sqlFile.exists()) {
log.error("sql file not found,current dir:{},conf dir:{}", System.getProperty("user.dir"), confDir);
throw new RuntimeException("sql file not found");
}
}
sb.append(appTask.getStatement());
return sb.toString();
log.info("start read sql file path:{}", sqlFile.getAbsolutePath());
return FileUtil.readString(sqlFile, Charset.defaultCharset());
}
private static void loadDep(String type, Integer taskId, ExecutorConfig executorConfig) {
......
......@@ -45,4 +45,15 @@ public class CustomerConfigureOptions {
public static final ConfigOption<Integer> DINKY_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;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
......@@ -111,8 +112,10 @@ public class Explainer {
List<StatementParam> execute = new ArrayList<>();
List<String> statementList = new ArrayList<>();
List<UDF> udfList = new ArrayList<>();
StrBuilder parsedSql = new StrBuilder();
for (String item : statements) {
String statement = executor.pretreatStatement(item);
parsedSql.append(statement).append(";\n");
if (statement.isEmpty()) {
continue;
}
......@@ -169,7 +172,7 @@ public class Explainer {
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() {
......
......@@ -91,14 +91,17 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrFormatter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class JobManager {
private JobHandler handler;
private ExecutorConfig executorConfig;
......@@ -250,6 +253,10 @@ public class JobManager {
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
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);
ready();
JobJarStreamGraphBuilder jobJarStreamGraphBuilder = JobJarStreamGraphBuilder.build(this);
......@@ -282,6 +289,7 @@ public class JobManager {
GatewayResult gatewayResult;
config.addGatewayConfig(configuration);
if (runMode.isApplicationMode()) {
config.getGatewayConfig().setSql(statement);
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar(getUdfPathContextHolder());
} else {
streamGraph.setJobName(config.getJobName());
......@@ -351,7 +359,7 @@ public class JobManager {
}
} catch (Exception e) {
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());
}
String error = StrFormatter.format(
......
......@@ -24,11 +24,14 @@ import org.dinky.function.data.model.UDF;
import java.util.List;
import java.util.stream.Collectors;
import lombok.Data;
/**
* JobParam
*
* @since 2021/11/16
*/
@Data
public class JobParam {
private List<String> statements;
......@@ -36,6 +39,7 @@ public class JobParam {
private List<StatementParam> trans;
private List<StatementParam> execute;
private List<UDF> udfList;
private String parsedSql;
public JobParam(List<UDF> udfList) {
this.udfList = udfList;
......@@ -62,12 +66,14 @@ public class JobParam {
List<StatementParam> ddl,
List<StatementParam> trans,
List<StatementParam> execute,
List<UDF> udfList) {
List<UDF> udfList,
String parsedSql) {
this.statements = statements;
this.ddl = ddl;
this.trans = trans;
this.execute = execute;
this.udfList = udfList;
this.parsedSql = parsedSql;
}
public List<String> getStatements() {
......
......@@ -186,7 +186,7 @@ public class JobTransBuilder extends JobBuilder {
// Use gateway need to build gateway config, include flink configuration.
config.addGatewayConfig(executor.getCustomTableEnvironment().getConfig().getConfiguration());
config.getGatewayConfig().setSql(jobParam.getParsedSql());
if (runMode.isApplicationMode()) {
// Application mode need to submit dinky-app.jar that in the hdfs or image.
gatewayResult = Gateway.build(config.getGatewayConfig())
......
......@@ -47,6 +47,13 @@ public class GatewayConfig {
notes = "ID of the task")
private Integer taskId;
@ApiModelProperty(
value = "SQL statement to be executed",
dataType = "String",
example = "SELECT * FROM table",
notes = "SQL statement")
private String sql;
@ApiModelProperty(
value = "Paths to the JAR files",
dataType = "String[]",
......
......@@ -25,8 +25,10 @@ import org.dinky.data.enums.GatewayType;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.IgnoreNullRepresenter;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.client.deployment.ClusterDeploymentException;
......@@ -34,8 +36,10 @@ import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.application.ApplicationConfiguration;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ClusterClientProvider;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
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.runtime.client.JobStatusMessage;
......@@ -43,24 +47,32 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.yaml.snakeyaml.DumperOptions;
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.representer.Representer;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
/**
* KubernetesApplicationGateway
*/
@Slf4j
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.
*/
......@@ -69,6 +81,24 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
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.
*
......@@ -76,16 +106,16 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
*/
@Override
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
try {
init();
try (KubernetesClient kubernetesClient = getK8sClientHelper().getKubernetesClient()) {
logger.info("Start submit k8s application.");
ClusterClientProvider<String> clusterClient = deployApplication();
Deployment deployment = kubernetesClient
.apps()
.deployments()
.inNamespace(configuration.getString(KubernetesConfigOptions.NAMESPACE))
.withName(configuration.getString(KubernetesConfigOptions.CLUSTER_ID))
.get();
KubernetesResult kubernetesResult = waitForJmAndJobStart(deployment, clusterClient);
ClusterClientProvider<String> clusterClient =
deployApplication(getK8sClientHelper().getClient());
Deployment deployment = getK8sClientHelper().createDinkyResource();
KubernetesResult kubernetesResult = waitForJmAndJobStart(kubernetesClient, deployment, clusterClient);
kubernetesResult.success();
return kubernetesResult;
} catch (Exception ex) {
......@@ -110,7 +140,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
ContainerStatus containerStatus =
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(
"Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n"
+ "------CurrentState------\n{}\n------LastState------\n{}",
......@@ -134,10 +164,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
* @return A ClusterClientProvider<String> object for accessing the Kubernetes cluster.
* @throws ClusterDeploymentException if deployment to Kubernetes fails.
*/
public ClusterClientProvider<String> deployApplication() throws ClusterDeploymentException {
if (Asserts.isNull(client)) {
init();
}
public ClusterClientProvider<String> deployApplication(FlinkKubeClient client) throws ClusterDeploymentException {
// Build the commit information
AppConfig appConfig = config.getAppConfig();
String[] userJarParas =
......@@ -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.
* @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 {
KubernetesResult result = KubernetesResult.build(getType());
long waitSends = SystemConfiguration.getInstances().getJobIdWait() * 1000L;
......@@ -208,27 +236,19 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
"The number of retries exceeds the limit, check the K8S cluster for more information");
}
/**
* Represents Java Bean properties for YAML serialization with LogRepresenter.
* If the property value is null, it is ignored.
*/
static class LogRepresenter 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) {
if (propertyValue == null) {
return null;
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));
}
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;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.K8sClientHelper;
import org.dinky.gateway.result.SavePointResult;
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.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration;
......@@ -39,43 +38,39 @@ import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.python.PythonOptions;
import org.apache.http.util.TextUtils;
import java.lang.reflect.Method;
import java.util.Collections;
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.util.ReflectUtil;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
/**
* KubernetesGateway
*/
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkKubeClient client;
protected KubernetesClient kubernetesClient;
protected String flinkConfigPath;
protected FlinkConfig flinkConfig;
protected K8sConfig k8sConfig;
protected String tmpConfDir;
private K8sClientHelper k8sClientHelper;
public KubernetesGateway() {}
public void init() {
initConfig();
initKubeClient();
}
private void initConfig() {
tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
protected void initConfig() {
flinkConfigPath = config.getClusterConfig().getFlinkConfigPath();
flinkConfig = config.getFlinkConfig();
k8sConfig = config.getKubernetesConfig();
......@@ -96,41 +91,18 @@ public abstract class KubernetesGateway extends AbstractGateway {
PipelineOptions.JARS,
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()) {
// remove python file
configuration.removeConfig(PythonOptions.PYTHON_FILES);
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() {
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) {
kubernetesClient = new DefaultKubernetesClient();
} else {
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(k8sConfig.getKubeConfig()));
}
k8sClientHelper = new K8sClientHelper(configuration, k8sConfig);
}
public SavePointResult savepointCluster(String savePoint) {
if (Asserts.isNull(client)) {
init();
if (Asserts.isNull(k8sClientHelper.getClient())) {
initConfig();
}
KubernetesClusterClientFactory clusterClientFactory = new KubernetesClusterClientFactory();
......@@ -148,8 +120,8 @@ public abstract class KubernetesGateway extends AbstractGateway {
}
public SavePointResult savepointJob(String savePoint) {
if (Asserts.isNull(client)) {
init();
if (Asserts.isNull(k8sClientHelper.getClient())) {
initConfig();
}
if (Asserts.isNull(config.getFlinkConfig().getJobId())) {
throw new GatewayException(
......@@ -171,10 +143,10 @@ public abstract class KubernetesGateway extends AbstractGateway {
public TestResult test() {
try {
initConfig();
// Test mode no jobName, use uuid .
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, UUID.randomUUID().toString());
initKubeClient();
initConfig();
FlinkKubeClient client = k8sClientHelper.getClient();
if (client instanceof Fabric8FlinkKubeClient) {
Object internalClient = ReflectUtil.getFieldValue(client, "internalClient");
Method method = ReflectUtil.getMethod(internalClient.getClass(), "getVersion");
......@@ -196,8 +168,8 @@ public abstract class KubernetesGateway extends AbstractGateway {
@Override
public void killCluster() {
if (Asserts.isNull(client)) {
init();
if (Asserts.isNull(k8sClientHelper.getClient())) {
initConfig();
}
addConfigParas(
KubernetesConfigOptions.CLUSTER_ID, config.getClusterConfig().getAppId());
......@@ -207,22 +179,19 @@ public abstract class KubernetesGateway extends AbstractGateway {
throw new GatewayException(
"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);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
public void close() {
if (client != null) {
client.close();
}
if (kubernetesClient != null) {
kubernetesClient.close();
public boolean close() {
if (k8sClientHelper != null) {
return k8sClientHelper.close();
}
FileUtil.del(tmpConfDir);
return true;
}
}
......@@ -19,7 +19,6 @@
package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult;
......@@ -47,18 +46,16 @@ public class KubernetesSessionGateway extends KubernetesGateway {
@Override
public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) {
if (Asserts.isNull(client)) {
String clusterId = StrFormatter.format("dinky-flink-session-{}", System.currentTimeMillis());
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, clusterId);
init();
}
String clusterId = StrFormatter.format("dinky-flink-session-{}", System.currentTimeMillis());
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, clusterId);
init();
ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder =
createClusterSpecificationBuilder();
KubernetesResult result = KubernetesResult.build(getType());
try (KubernetesClusterDescriptor kubernetesClusterDescriptor =
new KubernetesClusterDescriptor(configuration, client)) {
try (KubernetesClusterDescriptor kubernetesClusterDescriptor = new KubernetesClusterDescriptor(
configuration, getK8sClientHelper().getClient())) {
ClusterClientProvider<String> clusterClientProvider = kubernetesClusterDescriptor.deploySessionCluster(
clusterSpecificationBuilder.createClusterSpecification());
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;
import org.dinky.assertion.Asserts;
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.kubernetes.KubernetesGateway;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec.Resource;
import org.dinky.gateway.kubernetes.operator.api.FlinkDeployment;
......@@ -35,77 +33,60 @@ import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil;
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.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.Data;
import lombok.EqualsAndHashCode;
@EqualsAndHashCode(callSuper = true)
@Data
public abstract class KubernetsOperatorGateway extends AbstractGateway {
public abstract class KubernetsOperatorGateway extends KubernetesGateway {
private Map<String, String> kubernetsConfiguration;
private K8sConfig k8sConfig;
private FlinkConfig flinkConfig;
private FlinkDeployment flinkDeployment = new FlinkDeployment();
private FlinkDeploymentSpec flinkDeploymentSpec = new FlinkDeploymentSpec();
private KubernetesClient kubernetesClient;
private static final Logger logger = LoggerFactory.getLogger(KubernetsOperatorGateway.class);
@Override
protected void init() {
initKubeClient();
public void init() {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
initConfig();
initBase();
initMetadata();
initSpec();
initResource(kubernetesClient);
initResource(getK8sClientHelper().getKubernetesClient());
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
public TestResult test() {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
flinkConfig = config.getFlinkConfig();
config.getFlinkConfig().setJobName("test");
initKubeClient();
addConfigParas(KubernetesConfigOptions.CLUSTER_ID, UUID.randomUUID().toString());
initConfig();
initBase();
initMetadata();
initSpec();
kubernetesClient.resource(flinkDeployment).fromServer();
getK8sClientHelper().getKubernetesClient().nodes().list();
logger.info("配置连接测试成功");
return TestResult.success();
}
@Override
public boolean onJobFinishCallback(String status) {
kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
initKubeClient();
String jobName = config.getFlinkConfig().getJobName();
if (status.equals(JobStatus.FINISHED.getValue())) {
logger.info(
......@@ -119,8 +100,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
}
public boolean deleteCluster() {
initConfig();
initMetadata();
kubernetesClient.resource(flinkDeployment).delete();
getK8sClientHelper().getKubernetesClient().resource(flinkDeployment).delete();
return true;
}
......@@ -175,12 +157,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem);
taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem));
if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) {
InputStream inputStream =
new ByteArrayInputStream(k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8));
defaultPod = kubernetesClient.pods().load(inputStream).get();
flinkDeploymentSpec.setPodTemplate(defaultPod);
}
defaultPod = getK8sClientHelper().decoratePodTemplate(config.getSql());
flinkDeploymentSpec.setPodTemplate(defaultPod);
if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) {
InputStream inputStream =
new ByteArrayInputStream(k8sConfig.getJmPodTemplate().getBytes(StandardCharsets.UTF_8));
......
......@@ -60,12 +60,13 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
try {
init();
KubernetesClient kubernetesClient = getKubernetesClient();
KubernetesClient kubernetesClient = getK8sClientHelper().getKubernetesClient();
FlinkDeployment flinkDeployment = getFlinkDeployment();
kubernetesClient.resource(flinkDeployment).delete();
kubernetesClient.resource(flinkDeployment).waitUntilCondition(Objects::isNull, 1, TimeUnit.MINUTES);
kubernetesClient.resource(flinkDeployment).createOrReplace();
logger.info("create flink deployment finish,wait for flink jobmanager ready");
FlinkDeployment flinkDeploymentResult = kubernetesClient
.resource(flinkDeployment)
......@@ -92,6 +93,9 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
result.setJids(Collections.singletonList(jobId));
return true;
}
if (status.equals("DEPLOYING")) {
getK8sClientHelper().createDinkyResource();
}
return false;
},
2,
......@@ -125,7 +129,7 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
} catch (KubernetesClientException e) {
// some error while connecting to kube cluster
result.fail(LogUtil.getError(e));
e.printStackTrace();
throw e;
}
logger.info(
"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 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.config.AppConfig;
......@@ -39,6 +40,8 @@ import java.io.File;
import java.util.Collections;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
/**
* YarnApplicationGateway
*
......@@ -74,6 +77,11 @@ public class YarnApplicationGateway extends YarnGateway {
YarnResult result = YarnResult.build(getType());
String webUrl;
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(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration);
ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient();
......@@ -86,6 +94,8 @@ public class YarnApplicationGateway extends YarnGateway {
result.success();
} catch (Exception e) {
result.fail(LogUtil.getError(e));
} finally {
close();
}
return result;
}
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.JobStatus;
import org.dinky.data.model.SystemConfiguration;
......@@ -73,7 +74,9 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
......@@ -86,6 +89,7 @@ import cn.hutool.http.HttpUtil;
public abstract class YarnGateway extends AbstractGateway {
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;
......@@ -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.";
}
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 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.constant.CustomerConfigureOptions;
import org.dinky.data.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.YarnResult;
......@@ -34,6 +35,7 @@ import org.apache.hadoop.yarn.api.records.ApplicationId;
import java.util.Arrays;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
......@@ -66,6 +68,9 @@ public class YarnPerJobGateway extends YarnGateway {
YarnResult result = YarnResult.build(getType());
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(
clusterSpecificationBuilder.createClusterSpecification(), jobGraph, true);
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