Unverified Commit e38c814c authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Optimization-2579][core] Optimizate JobManager (#2580)

* [Optimization-2579][core] Optimizate JobManager * optimize return --------- Co-authored-by: 's avatarwenmo <32723967+wenmo@users.noreply.github.com>
parent e32555e0
...@@ -86,4 +86,16 @@ public class SqlUtil { ...@@ -86,4 +86,16 @@ public class SqlUtil {
} }
return sql; return sql;
} }
public static String addLineNumber(String input) {
String[] lines = input.split("\n");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
sb.append(String.format("%-4d", i + 1));
sb.append(" ");
sb.append(lines[i]);
sb.append("\n");
}
return sb.toString();
}
} }
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package org.dinky.utils; package org.dinky.utils;
import org.dinky.assertion.Asserts;
import java.io.File; import java.io.File;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
...@@ -93,4 +95,12 @@ public class URLUtils { ...@@ -93,4 +95,12 @@ public class URLUtils {
public static String toString(URL[] urls) { public static String toString(URL[] urls) {
return Arrays.stream(urls).map(URL::toString).collect(Collectors.joining(",")); return Arrays.stream(urls).map(URL::toString).collect(Collectors.joining(","));
} }
public static String formatAddress(String webURL) {
if (Asserts.isNotNullString(webURL)) {
return webURL.replaceAll("http://", "");
} else {
return "";
}
}
} }
/*
*
* 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.executor;
public class ExecutorContext {
private static final ThreadLocal<Executor> EXECUTOR = new ThreadLocal<>();
public static void setExecutor(Executor executor) {
EXECUTOR.set(executor);
}
public static Executor getExecutor() {
return EXECUTOR.get();
}
public static void clear() {
EXECUTOR.remove();
}
}
...@@ -38,6 +38,7 @@ import org.dinky.job.JobConfig; ...@@ -38,6 +38,7 @@ import org.dinky.job.JobConfig;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.job.JobParam; import org.dinky.job.JobParam;
import org.dinky.job.StatementParam; import org.dinky.job.StatementParam;
import org.dinky.job.builder.JobUDFBuilder;
import org.dinky.parser.SqlType; import org.dinky.parser.SqlType;
import org.dinky.trans.Operations; import org.dinky.trans.Operations;
import org.dinky.trans.parse.AddJarSqlParseStrategy; import org.dinky.trans.parse.AddJarSqlParseStrategy;
...@@ -99,7 +100,13 @@ public class Explainer { ...@@ -99,7 +100,13 @@ public class Explainer {
public Explainer initialize(JobManager jobManager, JobConfig config, String statement) { public Explainer initialize(JobManager jobManager, JobConfig config, String statement) {
DinkyClassLoaderUtil.initClassLoader(config); DinkyClassLoaderUtil.initClassLoader(config);
String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement), sqlSeparator); String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement), sqlSeparator);
jobManager.initUDF(parseUDFFromStatements(statements)); List<UDF> udfs = parseUDFFromStatements(statements);
jobManager.setJobParam(new JobParam(udfs));
try {
JobUDFBuilder.build(jobManager).run();
} catch (Exception e) {
e.printStackTrace();
}
return this; return this;
} }
......
/*
*
* 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.job;
import org.dinky.executor.Executor;
import org.dinky.gateway.enums.GatewayType;
public abstract class JobBuilder {
protected JobManager jobManager;
protected JobConfig config;
protected JobParam jobParam;
protected GatewayType runMode;
protected Executor executor;
protected boolean useStatementSet;
protected boolean useGateway;
protected String sqlSeparator;
protected Job job;
public JobBuilder(JobManager jobManager) {
this.jobManager = jobManager;
this.config = jobManager.getConfig();
this.jobParam = jobManager.getJobParam();
this.runMode = jobManager.getRunMode();
this.executor = jobManager.getExecutor();
this.useStatementSet = jobManager.isUseStatementSet();
this.useGateway = jobManager.isUseGateway();
this.sqlSeparator = jobManager.getSqlSeparator();
this.job = JobContextHolder.getJob();
}
public abstract void run() throws Exception;
}
...@@ -19,10 +19,6 @@ ...@@ -19,10 +19,6 @@
package org.dinky.job; package org.dinky.job;
import static org.dinky.function.util.UDFUtil.GATEWAY_TYPE_MAP;
import static org.dinky.function.util.UDFUtil.SESSION;
import static org.dinky.function.util.UDFUtil.YARN;
import org.dinky.api.FlinkAPI; import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant; import org.dinky.constant.FlinkSQLConstant;
...@@ -31,8 +27,6 @@ import org.dinky.context.FlinkUdfPathContextHolder; ...@@ -31,8 +27,6 @@ import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.context.RowLevelPermissionsContext; import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.data.annotations.ProcessStep; import org.dinky.data.annotations.ProcessStep;
import org.dinky.data.enums.ProcessStepType; import org.dinky.data.enums.ProcessStepType;
import org.dinky.data.exception.DinkyException;
import org.dinky.data.model.FlinkUdfManifest;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.result.ErrorResult; import org.dinky.data.result.ErrorResult;
import org.dinky.data.result.ExplainResult; import org.dinky.data.result.ExplainResult;
...@@ -43,11 +37,9 @@ import org.dinky.data.result.ResultPool; ...@@ -43,11 +37,9 @@ import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorConfig; import org.dinky.executor.ExecutorConfig;
import org.dinky.executor.ExecutorContext;
import org.dinky.executor.ExecutorFactory; import org.dinky.executor.ExecutorFactory;
import org.dinky.explainer.Explainer; import org.dinky.explainer.Explainer;
import org.dinky.function.constant.PathConstant;
import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil;
import org.dinky.gateway.Gateway; import org.dinky.gateway.Gateway;
import org.dinky.gateway.config.FlinkConfig; import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
...@@ -57,57 +49,38 @@ import org.dinky.gateway.enums.SavePointType; ...@@ -57,57 +49,38 @@ import org.dinky.gateway.enums.SavePointType;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
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.interceptor.FlinkInterceptor; import org.dinky.job.builder.JobDDLBuilder;
import org.dinky.interceptor.FlinkInterceptorResult; import org.dinky.job.builder.JobExecuteBuilder;
import org.dinky.job.builder.JobJarStreamGraphBuilder;
import org.dinky.job.builder.JobTransBuilder;
import org.dinky.job.builder.JobUDFBuilder;
import org.dinky.parser.SqlType; import org.dinky.parser.SqlType;
import org.dinky.trans.Operations; import org.dinky.trans.Operations;
import org.dinky.trans.dml.ExecuteJarOperation;
import org.dinky.trans.parse.AddJarSqlParseStrategy;
import org.dinky.trans.parse.ExecuteJarParseStrategy;
import org.dinky.utils.DinkyClassLoaderUtil; import org.dinky.utils.DinkyClassLoaderUtil;
import org.dinky.utils.JsonUtils; import org.dinky.utils.JsonUtils;
import org.dinky.utils.LogUtil; import org.dinky.utils.LogUtil;
import org.dinky.utils.SqlUtil; import org.dinky.utils.SqlUtil;
import org.dinky.utils.URLUtils; import org.dinky.utils.URLUtils;
import org.apache.flink.configuration.Configuration;
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.PipelineOptions; import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions; import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings; import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator; import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator;
import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions; import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph; import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.TableResult;
import org.apache.flink.yarn.configuration.YarnConfigOptions; import org.apache.flink.yarn.configuration.YarnConfigOptions;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List;
import java.util.Map; import java.util.Map;
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.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.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
...@@ -123,8 +96,35 @@ public class JobManager { ...@@ -123,8 +96,35 @@ public class JobManager {
private String sqlSeparator = FlinkSQLConstant.SEPARATOR; private String sqlSeparator = FlinkSQLConstant.SEPARATOR;
private GatewayType runMode = GatewayType.LOCAL; private GatewayType runMode = GatewayType.LOCAL;
private JobParam jobParam = null;
private String currentSql = "";
public JobManager() {} public JobManager() {}
public JobParam getJobParam() {
return jobParam;
}
public void setJobParam(JobParam jobParam) {
this.jobParam = jobParam;
}
public JobConfig getConfig() {
return config;
}
public GatewayType getRunMode() {
return runMode;
}
public void setCurrentSql(String currentSql) {
this.currentSql = currentSql;
}
public Executor getExecutor() {
return executor;
}
public void setPlanMode(boolean planMode) { public void setPlanMode(boolean planMode) {
isPlanMode = planMode; isPlanMode = planMode;
} }
...@@ -137,27 +137,19 @@ public class JobManager { ...@@ -137,27 +137,19 @@ public class JobManager {
return useStatementSet; return useStatementSet;
} }
public void setUseStatementSet(boolean useStatementSet) {
this.useStatementSet = useStatementSet;
}
public boolean isUseRestAPI() { public boolean isUseRestAPI() {
return useRestAPI; return useRestAPI;
} }
public void setUseRestAPI(boolean useRestAPI) {
this.useRestAPI = useRestAPI;
}
public String getSqlSeparator() { public String getSqlSeparator() {
return sqlSeparator; return sqlSeparator;
} }
public void setSqlSeparator(String sqlSeparator) { public boolean isUseGateway() {
this.sqlSeparator = sqlSeparator; return useGateway;
} }
public JobManager(JobConfig config) { private JobManager(JobConfig config) {
this.config = config; this.config = config;
} }
...@@ -175,7 +167,7 @@ public class JobManager { ...@@ -175,7 +167,7 @@ public class JobManager {
return manager; return manager;
} }
public boolean init() { public void init() {
if (!isPlanMode) { if (!isPlanMode) {
runMode = GatewayType.get(config.getType()); runMode = GatewayType.get(config.getType());
useGateway = GatewayType.isDeployCluster(config.getType()); useGateway = GatewayType.isDeployCluster(config.getType());
...@@ -186,110 +178,7 @@ public class JobManager { ...@@ -186,110 +178,7 @@ public class JobManager {
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator(); sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
executorConfig = config.getExecutorSetting(); executorConfig = config.getExecutorSetting();
executor = ExecutorFactory.buildExecutor(executorConfig); executor = ExecutorFactory.buildExecutor(executorConfig);
return false; ExecutorContext.setExecutor(executor);
}
private void addConfigurationClsAndJars(List<URL> jarList, List<URL> classpaths) throws Exception {
Map<String, Object> temp = getFlinkConfigurationMap();
temp.put(
PipelineOptions.CLASSPATHS.key(),
classpaths.stream().map(URL::toString).collect(Collectors.toList()));
temp.put(PipelineOptions.JARS.key(), jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
private Map<String, Object> getFlinkConfigurationMap() {
Field configuration = null;
try {
configuration = StreamExecutionEnvironment.class.getDeclaredField("configuration");
configuration.setAccessible(true);
Configuration o = (Configuration) configuration.get(executor.getStreamExecutionEnvironment());
Field confData = Configuration.class.getDeclaredField("confData");
confData.setAccessible(true);
Map<String, Object> temp = (Map<String, Object>) confData.get(o);
return temp;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void initUDF(List<UDF> udfList) {
if (Asserts.isNotNullCollection(udfList)) {
initUDF(udfList, runMode, config.getTaskId());
}
}
public void initUDF(List<UDF> udfList, GatewayType runMode, Integer taskId) {
if (taskId == null) {
taskId = -RandomUtil.randomInt(0, 1000);
}
// TODO 改为ProcessStep注释
// 这里要分开
// 1. 得到jar包路径,注入remote环境
Set<File> jarFiles = FlinkUdfPathContextHolder.getUdfFile();
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
List<File> udfJars = Arrays.stream(UDFUtil.initJavaUDF(udfList, runMode, taskId))
.map(File::new)
.collect(Collectors.toList());
jarFiles.addAll(udfJars);
String[] jarPaths = CollUtil.removeNull(jarFiles).stream()
.map(File::getAbsolutePath)
.toArray(String[]::new);
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths);
}
// 2.编译python
String[] pyPaths = UDFUtil.initPythonUDF(
udfList, runMode, config.getTaskId(), executor.getTableConfig().getConfiguration());
executor.initUDF(jarPaths);
if (ArrayUtil.isNotEmpty(pyPaths)) {
for (String pyPath : pyPaths) {
if (StrUtil.isNotBlank(pyPath)) {
FlinkUdfPathContextHolder.addPyUdfPath(new File(pyPath));
}
}
}
Set<File> pyUdfFile = FlinkUdfPathContextHolder.getPyUdfFile();
executor.initPyUDF(
SystemConfiguration.getInstances().getPythonHome(),
pyUdfFile.stream().map(File::getAbsolutePath).toArray(String[]::new));
if (GATEWAY_TYPE_MAP.get(YARN).contains(runMode)) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(jarPaths, pyPaths));
}
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
// 3.写入udf所需文件
writeManifest(taskId, jarList);
addConfigurationClsAndJars(jarList, CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
log.error("add configuration failed;reason:{}", LogUtil.getError(e));
throw new RuntimeException(e);
}
log.info(StrUtil.format("A total of {} UDF have been Init.", udfList.size() + pyUdfFile.size()));
log.info("Initializing Flink UDF...Finish");
}
private void writeManifest(Integer taskId, List<URL> jarPaths) {
FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest();
flinkUdfManifest.setJars(jarPaths);
flinkUdfManifest.setPythonFiles(FlinkUdfPathContextHolder.getPyUdfFile().stream()
.map(URLUtil::getURL)
.collect(Collectors.toList()));
FileUtil.writeUtf8String(
JSONUtil.toJsonStr(flinkUdfManifest),
PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST);
} }
private boolean ready() { private boolean ready() {
...@@ -309,46 +198,19 @@ public class JobManager { ...@@ -309,46 +198,19 @@ public class JobManager {
CustomTableEnvironmentContext.clear(); CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear(); RowLevelPermissionsContext.clear();
FlinkUdfPathContextHolder.clear(); FlinkUdfPathContextHolder.clear();
ExecutorContext.clear();
return true; return true;
} }
public ObjectNode getJarStreamGraphJson(String statement) throws Exception { public ObjectNode getJarStreamGraphJson(String statement) {
StreamGraph streamGraph = getJarStreamGraph(statement); StreamGraph streamGraph = JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement);
return JsonUtils.parseObject(JsonPlanGenerator.generatePlan(streamGraph.getJobGraph())); return JsonUtils.parseObject(JsonPlanGenerator.generatePlan(streamGraph.getJobGraph()));
} }
public StreamGraph getJarStreamGraph(String statement) throws Exception {
String currentSql = "";
DinkyClassLoaderUtil.initClassLoader(config);
String[] statements = SqlUtil.getStatements(statement, sqlSeparator);
ExecuteJarOperation executeJarOperation = null;
for (int i = 0; i < statements.length; i++) {
String sql = statements[i];
String sqlStatement = executor.pretreatStatement(sql);
if (ExecuteJarParseStrategy.INSTANCE.match(sqlStatement)) {
currentSql = sqlStatement;
executeJarOperation = new ExecuteJarOperation(sqlStatement);
break;
}
SqlType operationType = Operations.getOperationType(sqlStatement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
if (runMode.isApplicationMode()) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement)
.forEach(FlinkUdfPathContextHolder::addOtherPlugins);
} else {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
}
}
}
Assert.notNull(executeJarOperation, () -> new DinkyException("Not found execute jar operation."));
return executeJarOperation.explain(executor.getCustomTableEnvironment());
}
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE) @ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeJarSql(String statement) throws Exception { public JobResult executeJarSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway); Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
StreamGraph streamGraph = getJarStreamGraph(statement); StreamGraph streamGraph = JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement);
try { try {
if (!useGateway) { if (!useGateway) {
executor.getStreamExecutionEnvironment().executeAsync(streamGraph); executor.getStreamExecutionEnvironment().executeAsync(streamGraph);
...@@ -369,7 +231,7 @@ public class JobManager { ...@@ -369,7 +231,7 @@ public class JobManager {
job.setResult(InsertResult.success(gatewayResult.getId())); job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId()); job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids()); job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(formatAddress(gatewayResult.getWebURL())); job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) { if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS); job.setStatus(Job.JobStatus.SUCCESS);
...@@ -382,7 +244,8 @@ public class JobManager { ...@@ -382,7 +244,8 @@ public class JobManager {
} }
} }
} catch (Exception e) { } catch (Exception e) {
String error = LogUtil.getError("Exception in executing FlinkJarSQL:\n" + addLineNumber(statement), e); String error =
LogUtil.getError("Exception in executing FlinkJarSQL:\n" + SqlUtil.addLineNumber(statement), e);
job.setEndTime(LocalDateTime.now()); job.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED); job.setStatus(Job.JobStatus.FAILED);
job.setError(error); job.setError(error);
...@@ -398,213 +261,20 @@ public class JobManager { ...@@ -398,213 +261,20 @@ public class JobManager {
public JobResult executeSql(String statement) throws Exception { public JobResult executeSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway); Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
ready(); ready();
String currentSql = "";
DinkyClassLoaderUtil.initClassLoader(config); DinkyClassLoaderUtil.initClassLoader(config);
JobParam jobParam = Explainer.build(executor, useStatementSet, sqlSeparator) jobParam = Explainer.build(executor, useStatementSet, sqlSeparator)
.pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator)); .pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator));
try { try {
initUDF(jobParam.getUdfList(), runMode, config.getTaskId()); // step 1: init udf
JobUDFBuilder.build(this).run();
for (StatementParam item : jobParam.getDdl()) { // step 2: execute ddl
currentSql = item.getValue(); JobDDLBuilder.build(this).run();
executor.executeSql(item.getValue()); // step 3: execute insert/select/show/desc/CTAS...
} JobTransBuilder.build(this).run();
if (!jobParam.getTrans().isEmpty()) { // step 4: execute custom data stream task
// Use statement set or gateway only submit inserts. JobExecuteBuilder.build(this).run();
if (useStatementSet && useGateway) { // finished
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
inserts.add(item.getValue());
}
// Use statement set need to merge all insert sql into a sql.
currentSql = String.join(sqlSeparator, inserts);
GatewayResult gatewayResult = submitByGateway(inserts);
// Use statement set only has one jid.
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else if (useStatementSet && !useGateway) {
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
if (item.getType().equals(SqlType.INSERT)) {
inserts.add(item.getValue());
} else if (item.getType().equals(SqlType.CTAS)) {
executor.getCustomTableEnvironment()
.getParser()
.parse(item.getValue())
.forEach(x -> {
executor.getCustomTableEnvironment().executeCTAS(x);
});
}
}
if (!inserts.isEmpty()) {
currentSql = String.join(sqlSeparator, inserts);
// Remote mode can get the table result.
TableResult tableResult = executor.executeStatementSet(inserts);
if (tableResult.getJobClient().isPresent()) {
job.setJobId(
tableResult.getJobClient().get().getJobID().toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
// Build insert result.
IResult result = ResultBuilder.build(
SqlType.INSERT,
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(tableResult);
job.setResult(result);
}
}
} else if (!useStatementSet && useGateway) {
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
inserts.add(item.getValue());
// Only can submit the first of insert sql, when not use statement set.
break;
}
currentSql = String.join(sqlSeparator, inserts);
GatewayResult gatewayResult = submitByGateway(inserts);
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else {
for (StatementParam item : jobParam.getTrans()) {
currentSql = item.getValue();
FlinkInterceptorResult flinkInterceptorResult =
FlinkInterceptor.build(executor, item.getValue());
if (Asserts.isNotNull(flinkInterceptorResult.getTableResult())) {
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
item.getType(),
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(flinkInterceptorResult.getTableResult());
job.setResult(result);
}
} else {
if (!flinkInterceptorResult.isNoExecute()) {
TableResult tableResult = executor.executeSql(item.getValue());
if (tableResult.getJobClient().isPresent()) {
job.setJobId(tableResult
.getJobClient()
.get()
.getJobID()
.toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
item.getType(),
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(tableResult);
job.setResult(result);
}
}
}
// Only can submit the first of insert sql, when not use statement set.
break;
}
}
}
if (!jobParam.getExecute().isEmpty()) {
if (useGateway) {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
StreamGraph streamGraph = executor.getStreamGraph();
streamGraph.setJobName(config.getJobName());
JobGraph jobGraph = streamGraph.getJobGraph();
if (Asserts.isNotNullString(config.getSavePointPath())) {
jobGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(config.getSavePointPath(), true));
}
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJobGraph(jobGraph);
}
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
JobClient jobClient = executor.executeAsync(config.getJobName());
if (Asserts.isNotNull(jobClient)) {
job.setJobId(jobClient.getJobID().toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
SqlType.EXECUTE,
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(null);
job.setResult(result);
}
}
}
job.setEndTime(LocalDateTime.now()); job.setEndTime(LocalDateTime.now());
if (job.isFailed()) { if (job.isFailed()) {
failed(); failed();
...@@ -614,7 +284,7 @@ public class JobManager { ...@@ -614,7 +284,7 @@ public class JobManager {
} }
} catch (Exception e) { } catch (Exception e) {
String error = StrFormatter.format( String error = StrFormatter.format(
"Exception in executing FlinkSQL:\n{}\n{}", addLineNumber(currentSql), e.getMessage()); "Exception in executing FlinkSQL:\n{}\n{}", SqlUtil.addLineNumber(currentSql), e.getMessage());
job.setEndTime(LocalDateTime.now()); job.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED); job.setStatus(Job.JobStatus.FAILED);
job.setError(error); job.setError(error);
...@@ -622,48 +292,7 @@ public class JobManager { ...@@ -622,48 +292,7 @@ public class JobManager {
throw new Exception(error, e); throw new Exception(error, e);
} finally { } finally {
close(); close();
} return job.getJobResult();
return job.getJobResult();
}
public String addLineNumber(String input) {
String[] lines = input.split("\n");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
sb.append(String.format("%-4d", i + 1));
sb.append(" ");
sb.append(lines[i]);
sb.append("\n");
}
return sb.toString();
}
private GatewayResult submitByGateway(List<String> inserts) {
GatewayResult gatewayResult = null;
// Use gateway need to build gateway config, include flink configeration.
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
// Application mode need to submit dinky-app.jar that in the hdfs or image.
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
JobGraph jobGraph = executor.getJobGraphFromInserts(inserts);
// Perjob mode need to set savepoint restore path, when recovery from savepoint.
if (Asserts.isNotNullString(config.getSavePointPath())) {
jobGraph.setSavepointRestoreSettings(SavepointRestoreSettings.forPath(config.getSavePointPath(), true));
}
// Perjob mode need to submit job graph.
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJobGraph(jobGraph);
}
return gatewayResult;
}
private String formatAddress(String webURL) {
if (Asserts.isNotNullString(webURL)) {
return webURL.replaceAll("http://", "");
} else {
return "";
} }
} }
...@@ -761,6 +390,7 @@ public class JobManager { ...@@ -761,6 +390,7 @@ public class JobManager {
return Gateway.build(gatewayConfig).deployCluster(); return Gateway.build(gatewayConfig).deployCluster();
} }
@Deprecated
public JobResult executeJar() { public JobResult executeJar() {
// TODO 改为ProcessStep注释 // TODO 改为ProcessStep注释
Job job = Job.init(runMode, config, executorConfig, executor, null, useGateway); Job job = Job.init(runMode, config, executorConfig, executor, null, useGateway);
...@@ -771,7 +401,7 @@ public class JobManager { ...@@ -771,7 +401,7 @@ public class JobManager {
job.setResult(InsertResult.success(gatewayResult.getId())); job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId()); job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids()); job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(formatAddress(gatewayResult.getWebURL())); job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
job.setEndTime(LocalDateTime.now()); job.setEndTime(LocalDateTime.now());
if (gatewayResult.isSuccess()) { if (gatewayResult.isSuccess()) {
...@@ -862,8 +492,4 @@ public class JobManager { ...@@ -862,8 +492,4 @@ public class JobManager {
sb.append(statement); sb.append(statement);
return sb.toString(); return sb.toString();
} }
public Executor getExecutor() {
return executor;
}
} }
...@@ -37,6 +37,10 @@ public class JobParam { ...@@ -37,6 +37,10 @@ public class JobParam {
private List<StatementParam> execute; private List<StatementParam> execute;
private List<UDF> udfList; private List<UDF> udfList;
public JobParam(List<UDF> udfList) {
this.udfList = udfList;
}
public JobParam(List<StatementParam> ddl, List<StatementParam> trans) { public JobParam(List<StatementParam> ddl, List<StatementParam> trans) {
this.ddl = ddl; this.ddl = ddl;
this.trans = trans; this.trans = trans;
......
/*
*
* 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.job.builder;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.job.StatementParam;
import lombok.extern.slf4j.Slf4j;
/**
* JobDDLBuilder
*
*/
@Slf4j
public class JobDDLBuilder extends JobBuilder {
public JobDDLBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobDDLBuilder build(JobManager jobManager) {
return new JobDDLBuilder(jobManager);
}
@Override
public void run() throws Exception {
for (StatementParam item : jobParam.getDdl()) {
jobManager.setCurrentSql(item.getValue());
executor.executeSql(item.getValue());
}
}
}
/*
*
* 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.job.builder;
import org.dinky.assertion.Asserts;
import org.dinky.data.result.IResult;
import org.dinky.data.result.InsertResult;
import org.dinky.data.result.ResultBuilder;
import org.dinky.gateway.Gateway;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.job.Job;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.job.StatementParam;
import org.dinky.parser.SqlType;
import org.dinky.utils.URLUtils;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.streaming.api.graph.StreamGraph;
import java.util.ArrayList;
/**
* JobExecuteBuilder
*
*/
public class JobExecuteBuilder extends JobBuilder {
public JobExecuteBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobExecuteBuilder build(JobManager jobManager) {
return new JobExecuteBuilder(jobManager);
}
@Override
public void run() throws Exception {
if (!jobParam.getExecute().isEmpty()) {
if (useGateway) {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
StreamGraph streamGraph = executor.getStreamGraph();
streamGraph.setJobName(config.getJobName());
JobGraph jobGraph = streamGraph.getJobGraph();
if (Asserts.isNotNullString(config.getSavePointPath())) {
jobGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(config.getSavePointPath(), true));
}
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJobGraph(jobGraph);
}
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
JobClient jobClient = executor.executeAsync(config.getJobName());
if (Asserts.isNotNull(jobClient)) {
job.setJobId(jobClient.getJobID().toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
SqlType.EXECUTE,
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(null);
job.setResult(result);
}
}
}
}
}
/*
*
* 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.job.builder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.exception.DinkyException;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.parser.SqlType;
import org.dinky.trans.Operations;
import org.dinky.trans.dml.ExecuteJarOperation;
import org.dinky.trans.parse.AddJarSqlParseStrategy;
import org.dinky.trans.parse.ExecuteJarParseStrategy;
import org.dinky.utils.DinkyClassLoaderUtil;
import org.dinky.utils.SqlUtil;
import org.apache.flink.streaming.api.graph.StreamGraph;
import cn.hutool.core.lang.Assert;
/**
* JobJarStreamGraphBuilder
*
*/
public class JobJarStreamGraphBuilder extends JobBuilder {
public JobJarStreamGraphBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobJarStreamGraphBuilder build(JobManager jobManager) {
return new JobJarStreamGraphBuilder(jobManager);
}
@Override
public void run() throws Exception {}
public StreamGraph getJarStreamGraph(String statement) {
DinkyClassLoaderUtil.initClassLoader(config);
String[] statements = SqlUtil.getStatements(statement, sqlSeparator);
ExecuteJarOperation executeJarOperation = null;
for (int i = 0; i < statements.length; i++) {
String sql = statements[i];
String sqlStatement = executor.pretreatStatement(sql);
if (ExecuteJarParseStrategy.INSTANCE.match(sqlStatement)) {
executeJarOperation = new ExecuteJarOperation(sqlStatement);
break;
}
SqlType operationType = Operations.getOperationType(sqlStatement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
if (runMode.isApplicationMode()) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement)
.forEach(FlinkUdfPathContextHolder::addOtherPlugins);
} else {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
}
}
}
Assert.notNull(executeJarOperation, () -> new DinkyException("Not found execute jar operation."));
return executeJarOperation.explain(executor.getCustomTableEnvironment());
}
}
/*
*
* 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.job.builder;
import org.dinky.assertion.Asserts;
import org.dinky.data.result.IResult;
import org.dinky.data.result.InsertResult;
import org.dinky.data.result.ResultBuilder;
import org.dinky.executor.Executor;
import org.dinky.gateway.Gateway;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult;
import org.dinky.job.Job;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
import org.dinky.job.StatementParam;
import org.dinky.parser.SqlType;
import org.dinky.utils.URLUtils;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.table.api.TableResult;
import java.util.ArrayList;
import java.util.List;
/**
* JobTransBuilder
*
*/
public class JobTransBuilder extends JobBuilder {
public JobTransBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobTransBuilder build(JobManager jobManager) {
return new JobTransBuilder(jobManager);
}
@Override
public void run() throws Exception {
if (!jobParam.getTrans().isEmpty()) {
// Use statement set or gateway only submit inserts.
if (useStatementSet && useGateway) {
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
inserts.add(item.getValue());
}
// Use statement set need to merge all insert sql into a sql.
jobManager.setCurrentSql(String.join(sqlSeparator, inserts));
GatewayResult gatewayResult = submitByGateway(inserts);
// Use statement set only has one jid.
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else if (useStatementSet && !useGateway) {
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
if (item.getType().equals(SqlType.INSERT)) {
inserts.add(item.getValue());
} else if (item.getType().equals(SqlType.CTAS)) {
executor.getCustomTableEnvironment()
.getParser()
.parse(item.getValue())
.forEach(x -> {
executor.getCustomTableEnvironment().executeCTAS(x);
});
}
}
if (!inserts.isEmpty()) {
jobManager.setCurrentSql(String.join(sqlSeparator, inserts));
// Remote mode can get the table result.
TableResult tableResult = executor.executeStatementSet(inserts);
if (tableResult.getJobClient().isPresent()) {
job.setJobId(tableResult.getJobClient().get().getJobID().toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
// Build insert result.
IResult result = ResultBuilder.build(
SqlType.INSERT,
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(tableResult);
job.setResult(result);
}
}
} else if (!useStatementSet && useGateway) {
List<String> inserts = new ArrayList<>();
for (StatementParam item : jobParam.getTrans()) {
inserts.add(item.getValue());
// Only can submit the first of insert sql, when not use statement set.
break;
}
jobManager.setCurrentSql(String.join(sqlSeparator, inserts));
GatewayResult gatewayResult = submitByGateway(inserts);
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else {
for (StatementParam item : jobParam.getTrans()) {
jobManager.setCurrentSql(item.getValue());
FlinkInterceptorResult flinkInterceptorResult = FlinkInterceptor.build(executor, item.getValue());
if (Asserts.isNotNull(flinkInterceptorResult.getTableResult())) {
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
item.getType(),
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(flinkInterceptorResult.getTableResult());
job.setResult(result);
}
} else {
if (!flinkInterceptorResult.isNoExecute()) {
TableResult tableResult = executor.executeSql(item.getValue());
if (tableResult.getJobClient().isPresent()) {
job.setJobId(tableResult
.getJobClient()
.get()
.getJobID()
.toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
item.getType(),
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(tableResult);
job.setResult(result);
}
}
}
// Only can submit the first of insert sql, when not use statement set.
break;
}
}
}
}
private GatewayResult submitByGateway(List<String> inserts) {
JobConfig config = jobManager.getConfig();
GatewayType runMode = jobManager.getRunMode();
Executor executor = jobManager.getExecutor();
GatewayResult gatewayResult = null;
// Use gateway need to build gateway config, include flink configeration.
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
// Application mode need to submit dinky-app.jar that in the hdfs or image.
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
JobGraph jobGraph = executor.getJobGraphFromInserts(inserts);
// Perjob mode need to set savepoint restore path, when recovery from savepoint.
if (Asserts.isNotNullString(config.getSavePointPath())) {
jobGraph.setSavepointRestoreSettings(SavepointRestoreSettings.forPath(config.getSavePointPath(), true));
}
// Perjob mode need to submit job graph.
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJobGraph(jobGraph);
}
return gatewayResult;
}
}
/*
*
* 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.job.builder;
import static org.dinky.function.util.UDFUtil.GATEWAY_TYPE_MAP;
import static org.dinky.function.util.UDFUtil.SESSION;
import static org.dinky.function.util.UDFUtil.YARN;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.utils.LogUtil;
import org.dinky.utils.URLUtils;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* JobUDFBuilder
*
*/
@Slf4j
public class JobUDFBuilder extends JobBuilder {
public JobUDFBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobUDFBuilder build(JobManager jobManager) {
return new JobUDFBuilder(jobManager);
}
@Override
public void run() throws Exception {
Asserts.checkNotNull(jobParam, "No executable statement.");
List<UDF> udfList = jobManager.getJobParam().getUdfList();
Integer taskId = config.getTaskId();
if (taskId == null) {
taskId = -RandomUtil.randomInt(0, 1000);
}
// 1. Obtain the path of the jar package and inject it into the remote environment
Set<File> jarFiles = FlinkUdfPathContextHolder.getUdfFile();
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
List<File> udfJars = Arrays.stream(UDFUtil.initJavaUDF(udfList, runMode, taskId))
.map(File::new)
.collect(Collectors.toList());
jarFiles.addAll(udfJars);
String[] jarPaths = CollUtil.removeNull(jarFiles).stream()
.map(File::getAbsolutePath)
.toArray(String[]::new);
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths);
}
// 2.Compile Python
String[] pyPaths = UDFUtil.initPythonUDF(
udfList, runMode, config.getTaskId(), executor.getTableConfig().getConfiguration());
executor.initUDF(jarPaths);
if (ArrayUtil.isNotEmpty(pyPaths)) {
for (String pyPath : pyPaths) {
if (StrUtil.isNotBlank(pyPath)) {
FlinkUdfPathContextHolder.addPyUdfPath(new File(pyPath));
}
}
}
Set<File> pyUdfFile = FlinkUdfPathContextHolder.getPyUdfFile();
executor.initPyUDF(
SystemConfiguration.getInstances().getPythonHome(),
pyUdfFile.stream().map(File::getAbsolutePath).toArray(String[]::new));
if (GATEWAY_TYPE_MAP.get(YARN).contains(runMode)) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(jarPaths, pyPaths));
}
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
// 3.Write the required files for UDF
UDFUtil.writeManifest(taskId, jarList);
UDFUtil.addConfigurationClsAndJars(jarList, CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
log.error("add configuration failed;reason:{}", LogUtil.getError(e));
throw new RuntimeException(e);
}
log.info(StrUtil.format("A total of {} UDF have been Init.", udfList.size() + pyUdfFile.size()));
log.info("Initializing Flink UDF...Finish");
}
}
...@@ -21,9 +21,11 @@ package org.dinky.function.util; ...@@ -21,9 +21,11 @@ package org.dinky.function.util;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect; import org.dinky.config.Dialect;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder; import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.exception.DinkyException; import org.dinky.data.exception.DinkyException;
import org.dinky.data.model.FlinkUdfManifest;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.function.FunctionFactory; import org.dinky.function.FunctionFactory;
import org.dinky.function.compiler.CustomStringJavaCompiler; import org.dinky.function.compiler.CustomStringJavaCompiler;
...@@ -37,6 +39,7 @@ import org.dinky.pool.ClassPool; ...@@ -37,6 +39,7 @@ import org.dinky.pool.ClassPool;
import org.apache.flink.client.python.PythonFunctionFactory; import org.apache.flink.client.python.PythonFunctionFactory;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.python.PythonOptions; import org.apache.flink.python.PythonOptions;
import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
...@@ -45,6 +48,7 @@ import org.apache.flink.table.functions.UserDefinedFunctionHelper; ...@@ -45,6 +48,7 @@ import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
...@@ -55,6 +59,7 @@ import java.util.Map; ...@@ -55,6 +59,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -75,10 +80,12 @@ import cn.hutool.core.util.ReUtil; ...@@ -75,10 +80,12 @@ import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.MD5; import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine; import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine;
import cn.hutool.json.JSONUtil;
/** /**
* UDFUtil * UDFUtil
...@@ -421,4 +428,27 @@ public class UDFUtil { ...@@ -421,4 +428,27 @@ public class UDFUtil {
throw new DinkyException(e); throw new DinkyException(e);
} }
} }
public static void addConfigurationClsAndJars(List<URL> jarList, List<URL> classpaths) {
Configuration configuration = (Configuration) CustomTableEnvironmentContext.get()
.getStreamExecutionEnvironment()
.getConfiguration();
configuration.set(
PipelineOptions.CLASSPATHS,
classpaths.stream().map(URL::toString).collect(Collectors.toList()));
configuration.set(
PipelineOptions.JARS, jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
public static void writeManifest(Integer taskId, List<URL> jarPaths) {
FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest();
flinkUdfManifest.setJars(jarPaths);
flinkUdfManifest.setPythonFiles(FlinkUdfPathContextHolder.getPyUdfFile().stream()
.map(URLUtil::getURL)
.collect(Collectors.toList()));
FileUtil.writeUtf8String(
JSONUtil.toJsonStr(flinkUdfManifest),
PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST);
}
} }
...@@ -506,7 +506,6 @@ const Model: ModelType = { ...@@ -506,7 +506,6 @@ const Model: ModelType = {
if (payload === '') { if (payload === '') {
centerContentHeight = state.centerContentHeight + (state.bottomContainer.height as number); centerContentHeight = state.centerContentHeight + (state.bottomContainer.height as number);
toolContentHeight = state.toolContentHeight + (state.bottomContainer.height as number); toolContentHeight = state.toolContentHeight + (state.bottomContainer.height as number);
console.log(2);
} else if ( } else if (
state.bottomContainer.selectKey !== '' && state.bottomContainer.selectKey !== '' &&
payload !== state.bottomContainer.selectKey payload !== state.bottomContainer.selectKey
...@@ -516,7 +515,6 @@ const Model: ModelType = { ...@@ -516,7 +515,6 @@ const Model: ModelType = {
} else { } else {
centerContentHeight = state.centerContentHeight - (state.bottomContainer.height as number); centerContentHeight = state.centerContentHeight - (state.bottomContainer.height as number);
toolContentHeight = state.toolContentHeight - (state.bottomContainer.height as number); toolContentHeight = state.toolContentHeight - (state.bottomContainer.height as number);
console.log(3);
} }
return { return {
......
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