Unverified Commit 0459e093 authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Optimization-2349][core] Optimize dinky executor (#2350)

* [Optimization-2349][core] Optimize dinky executor * Optimize code --------- Co-authored-by: 's avatarwenmo <32723967+wenmo@users.noreply.github.com>
parent 496e1182
...@@ -24,6 +24,7 @@ import org.dinky.assertion.Asserts; ...@@ -24,6 +24,7 @@ import org.dinky.assertion.Asserts;
import org.dinky.data.annotation.Log; import org.dinky.data.annotation.Log;
import org.dinky.data.enums.BusinessType; import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.model.ID;
import org.dinky.data.model.JobInfoDetail; import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobInstance; import org.dinky.data.model.JobInstance;
import org.dinky.data.model.JobManagerConfiguration; import org.dinky.data.model.JobManagerConfiguration;
...@@ -106,6 +107,18 @@ public class JobInstanceController { ...@@ -106,6 +107,18 @@ public class JobInstanceController {
return Result.succeed(jobInstanceService.getJobInfoDetail(id)); return Result.succeed(jobInstanceService.getJobInfoDetail(id));
} }
@PostMapping("/getOneById")
@ApiOperation("Get job instance info by job instance id")
@ApiImplicitParam(
name = "id",
value = "Job instance id",
dataType = "Integer",
paramType = "query",
required = true)
public Result getOneById(@RequestBody ID id) {
return Result.succeed(jobInstanceService.getById(id.getId()));
}
/** 刷新Job实例的所有信息 */ /** 刷新Job实例的所有信息 */
@GetMapping("/refreshJobInfoDetail") @GetMapping("/refreshJobInfoDetail")
@ApiOperation("Refresh job info detail") @ApiOperation("Refresh job info detail")
......
...@@ -24,7 +24,8 @@ import org.dinky.app.db.DBUtil; ...@@ -24,7 +24,8 @@ import org.dinky.app.db.DBUtil;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant; import org.dinky.constant.FlinkSQLConstant;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
import org.dinky.executor.ExecutorFactory;
import org.dinky.interceptor.FlinkInterceptor; import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.parser.SqlType; import org.dinky.parser.SqlType;
import org.dinky.trans.Operations; import org.dinky.trans.Operations;
...@@ -170,13 +171,13 @@ public class Submitter { ...@@ -170,13 +171,13 @@ public class Submitter {
// 添加自定义全局变量信息 // 添加自定义全局变量信息
sb.append(getFlinkSQLStatement(id, dbConfig)); sb.append(getFlinkSQLStatement(id, dbConfig));
List<String> statements = Submitter.getStatements(sb.toString()); List<String> statements = Submitter.getStatements(sb.toString());
ExecutorSetting executorSetting = ExecutorSetting.build(taskConfig); ExecutorConfig executorConfig = ExecutorConfig.buildFromMap(taskConfig);
// 加载第三方jar // 加载第三方jar
loadDep(taskConfig.get("type"), id, dinkyAddr, executorSetting); loadDep(taskConfig.get("type"), id, dinkyAddr, executorConfig);
logger.info("作业配置如下: {}", executorSetting); logger.info("The job configuration is as follows: {}", executorConfig);
Executor executor = Executor.buildAppStreamExecutor(executorSetting); Executor executor = ExecutorFactory.buildAppStreamExecutor(executorConfig);
List<StatementParam> ddl = new ArrayList<>(); List<StatementParam> ddl = new ArrayList<>();
List<StatementParam> trans = new ArrayList<>(); List<StatementParam> trans = new ArrayList<>();
List<StatementParam> execute = new ArrayList<>(); List<StatementParam> execute = new ArrayList<>();
...@@ -188,12 +189,12 @@ public class Submitter { ...@@ -188,12 +189,12 @@ public class Submitter {
SqlType operationType = Operations.getOperationType(statement); SqlType operationType = Operations.getOperationType(statement);
if (operationType.equals(SqlType.INSERT) || operationType.equals(SqlType.SELECT)) { if (operationType.equals(SqlType.INSERT) || operationType.equals(SqlType.SELECT)) {
trans.add(new StatementParam(statement, operationType)); trans.add(new StatementParam(statement, operationType));
if (!executorSetting.isUseStatementSet()) { if (!executorConfig.isUseStatementSet()) {
break; break;
} }
} else if (operationType.equals(SqlType.EXECUTE)) { } else if (operationType.equals(SqlType.EXECUTE)) {
execute.add(new StatementParam(statement, operationType)); execute.add(new StatementParam(statement, operationType));
if (!executorSetting.isUseStatementSet()) { if (!executorConfig.isUseStatementSet()) {
break; break;
} }
} else { } else {
...@@ -201,26 +202,26 @@ public class Submitter { ...@@ -201,26 +202,26 @@ public class Submitter {
} }
} }
for (StatementParam item : ddl) { for (StatementParam item : ddl) {
logger.info("正在执行 FlinkSQL: " + item.getValue()); logger.info("Executing FlinkSQL: " + item.getValue());
executor.submitSql(item.getValue()); executor.executeSql(item.getValue());
logger.info("执行成功"); logger.info("Execution succeeded.");
} }
if (trans.size() > 0) { if (trans.size() > 0) {
if (executorSetting.isUseStatementSet()) { if (executorConfig.isUseStatementSet()) {
List<String> inserts = new ArrayList<>(); List<String> inserts = new ArrayList<>();
for (StatementParam item : trans) { for (StatementParam item : trans) {
if (item.getType().equals(SqlType.INSERT)) { if (item.getType().equals(SqlType.INSERT)) {
inserts.add(item.getValue()); inserts.add(item.getValue());
} }
} }
logger.info("正在执行 FlinkSQL 语句集: " + String.join(FlinkSQLConstant.SEPARATOR, inserts)); logger.info("Executing FlinkSQL statement set: " + String.join(FlinkSQLConstant.SEPARATOR, inserts));
executor.submitStatementSet(inserts); executor.executeStatementSet(inserts);
logger.info("执行成功"); logger.info("Execution succeeded.");
} else { } else {
for (StatementParam item : trans) { for (StatementParam item : trans) {
logger.info("正在执行 FlinkSQL: " + item.getValue()); logger.info("Executing FlinkSQL: " + item.getValue());
executor.submitSql(item.getValue()); executor.executeSql(item.getValue());
logger.info("执行成功"); logger.info("Execution succeeded.");
break; break;
} }
} }
...@@ -230,13 +231,13 @@ public class Submitter { ...@@ -230,13 +231,13 @@ public class Submitter {
for (StatementParam item : execute) { for (StatementParam item : execute) {
executes.add(item.getValue()); executes.add(item.getValue());
executor.executeSql(item.getValue()); executor.executeSql(item.getValue());
if (!executorSetting.isUseStatementSet()) { if (!executorConfig.isUseStatementSet()) {
break; break;
} }
} }
logger.info("正在执行 FlinkSQL 语句集: " + String.join(FlinkSQLConstant.SEPARATOR, executes)); logger.info("正在执行 FlinkSQL 语句集: " + String.join(FlinkSQLConstant.SEPARATOR, executes));
try { try {
executor.execute(executorSetting.getJobName()); executor.execute(executorConfig.getJobName());
logger.info("执行成功"); logger.info("执行成功");
} catch (Exception e) { } catch (Exception e) {
logger.error("执行失败, {}", e.getMessage(), e); logger.error("执行失败, {}", e.getMessage(), e);
...@@ -245,7 +246,7 @@ public class Submitter { ...@@ -245,7 +246,7 @@ public class Submitter {
logger.info("{}任务提交成功", LocalDateTime.now()); logger.info("{}任务提交成功", LocalDateTime.now());
} }
private static void loadDep(String type, Integer taskId, String dinkyAddr, ExecutorSetting executorSetting) { private static void loadDep(String type, Integer taskId, String dinkyAddr, ExecutorConfig executorConfig) {
if (StringUtils.isBlank(dinkyAddr)) { if (StringUtils.isBlank(dinkyAddr)) {
return; return;
} }
...@@ -275,13 +276,13 @@ public class Submitter { ...@@ -275,13 +276,13 @@ public class Submitter {
.toArray(URL[]::new); .toArray(URL[]::new);
addURLs(jarUrls); addURLs(jarUrls);
executorSetting executorConfig
.getConfig() .getConfig()
.put( .put(
PipelineOptions.JARS.key(), PipelineOptions.JARS.key(),
Arrays.stream(jarUrls).map(URL::toString).collect(Collectors.joining(";"))); Arrays.stream(jarUrls).map(URL::toString).collect(Collectors.joining(";")));
if (ArrayUtil.isNotEmpty(pyUrls)) { if (ArrayUtil.isNotEmpty(pyUrls)) {
executorSetting executorConfig
.getConfig() .getConfig()
.put( .put(
PythonOptions.PYTHON_FILES.key(), PythonOptions.PYTHON_FILES.key(),
...@@ -295,7 +296,7 @@ public class Submitter { ...@@ -295,7 +296,7 @@ public class Submitter {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
} }
executorSetting.getConfig().put("python.files", "./python_udf.zip"); executorConfig.getConfig().put("python.files", "./python_udf.zip");
} }
private static void addURLs(URL[] jarUrls) { private static void addURLs(URL[] jarUrls) {
......
/*
*
* 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.data.model;
import io.swagger.annotations.ApiModel;
import lombok.Data;
@Data
@ApiModel(value = "ID", description = "The ID of a object")
public class ID {
private Integer id;
}
...@@ -19,8 +19,10 @@ ...@@ -19,8 +19,10 @@
package org.dinky.data.result; package org.dinky.data.result;
import java.util.Map; import java.util.concurrent.TimeUnit;
import java.util.concurrent.ConcurrentHashMap;
import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
/** /**
* ResultPool * ResultPool
...@@ -31,7 +33,7 @@ public final class ResultPool { ...@@ -31,7 +33,7 @@ public final class ResultPool {
private ResultPool() {} private ResultPool() {}
private static final Map<String, SelectResult> results = new ConcurrentHashMap<>(); private static final Cache<String, SelectResult> results = new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
public static boolean containsKey(String key) { public static boolean containsKey(String key) {
return results.containsKey(key); return results.containsKey(key);
...@@ -42,7 +44,10 @@ public final class ResultPool { ...@@ -42,7 +44,10 @@ public final class ResultPool {
} }
public static SelectResult get(String key) { public static SelectResult get(String key) {
return results.getOrDefault(key, SelectResult.buildDestruction(key)); if (containsKey(key)) {
return results.get(key);
}
return SelectResult.buildDestruction(key);
} }
public static boolean remove(String key) { public static boolean remove(String key) {
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
package org.dinky.data.result; package org.dinky.data.result;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -42,7 +42,7 @@ public class RunResult { ...@@ -42,7 +42,7 @@ public class RunResult {
private String msg; private String msg;
private String error; private String error;
private IResult result; private IResult result;
private ExecutorSetting setting; private ExecutorConfig setting;
public RunResult() {} public RunResult() {}
...@@ -51,7 +51,7 @@ public class RunResult { ...@@ -51,7 +51,7 @@ public class RunResult {
String statement, String statement,
String flinkHost, String flinkHost,
Integer flinkPort, Integer flinkPort,
ExecutorSetting setting, ExecutorConfig setting,
String jobName) { String jobName) {
this.sessionId = sessionId; this.sessionId = sessionId;
this.statement = statement; this.statement = statement;
...@@ -77,11 +77,11 @@ public class RunResult { ...@@ -77,11 +77,11 @@ public class RunResult {
this.jobId = jobId; this.jobId = jobId;
} }
public ExecutorSetting getSetting() { public ExecutorConfig getSetting() {
return setting; return setting;
} }
public void setSetting(ExecutorSetting setting) { public void setSetting(ExecutorConfig setting) {
this.setting = setting; this.setting = setting;
} }
......
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package org.dinky.data.result; package org.dinky.data.result;
import org.dinky.assertion.Asserts;
import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.TableResult;
/** /**
...@@ -34,7 +36,7 @@ public class SelectResultBuilder implements ResultBuilder { ...@@ -34,7 +36,7 @@ public class SelectResultBuilder implements ResultBuilder {
private final String timeZone; private final String timeZone;
public SelectResultBuilder(Integer maxRowNum, boolean isChangeLog, boolean isAutoCancel, String timeZone) { public SelectResultBuilder(Integer maxRowNum, boolean isChangeLog, boolean isAutoCancel, String timeZone) {
this.maxRowNum = maxRowNum; this.maxRowNum = Asserts.isNotNull(maxRowNum) ? maxRowNum : 100;
this.isChangeLog = isChangeLog; this.isChangeLog = isChangeLog;
this.isAutoCancel = isAutoCancel; this.isAutoCancel = isAutoCancel;
this.timeZone = timeZone; this.timeZone = timeZone;
......
...@@ -42,6 +42,7 @@ import org.dinky.parser.check.AddJarSqlParser; ...@@ -42,6 +42,7 @@ import org.dinky.parser.check.AddJarSqlParser;
import org.dinky.process.context.ProcessContextHolder; import org.dinky.process.context.ProcessContextHolder;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.trans.Operations; import org.dinky.trans.Operations;
import org.dinky.utils.DinkyClassLoaderUtil;
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;
...@@ -98,7 +99,7 @@ public class Explainer { ...@@ -98,7 +99,7 @@ public class Explainer {
} }
public Explainer initialize(JobManager jobManager, JobConfig config, String statement) { public Explainer initialize(JobManager jobManager, JobConfig config, String statement) {
jobManager.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)); jobManager.initUDF(parseUDFFromStatements(statements));
return this; return this;
......
...@@ -20,7 +20,7 @@ ...@@ -20,7 +20,7 @@
package org.dinky.explainer.lineage; package org.dinky.explainer.lineage;
import org.dinky.data.model.LineageRel; import org.dinky.data.model.LineageRel;
import org.dinky.executor.Executor; import org.dinky.executor.ExecutorFactory;
import org.dinky.explainer.Explainer; import org.dinky.explainer.Explainer;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -36,7 +36,7 @@ import java.util.Map; ...@@ -36,7 +36,7 @@ import java.util.Map;
public class LineageBuilder { public class LineageBuilder {
public static LineageResult getColumnLineageByLogicalPlan(String statement) { public static LineageResult getColumnLineageByLogicalPlan(String statement) {
Explainer explainer = new Explainer(Executor.build(), false); Explainer explainer = new Explainer(ExecutorFactory.getExecutor(), false);
List<LineageRel> lineageRelList = explainer.getLineage(statement); List<LineageRel> lineageRelList = explainer.getLineage(statement);
List<LineageRelation> relations = new ArrayList<>(); List<LineageRelation> relations = new ArrayList<>();
Map<String, LineageTable> tableMap = new HashMap<>(); Map<String, LineageTable> tableMap = new HashMap<>();
......
...@@ -21,7 +21,7 @@ package org.dinky.job; ...@@ -21,7 +21,7 @@ package org.dinky.job;
import org.dinky.data.result.IResult; import org.dinky.data.result.IResult;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import java.time.LocalDateTime; import java.time.LocalDateTime;
...@@ -48,7 +48,7 @@ public class Job { ...@@ -48,7 +48,7 @@ public class Job {
private String jobId; private String jobId;
private String error; private String error;
private IResult result; private IResult result;
private ExecutorSetting executorSetting; private ExecutorConfig executorConfig;
private LocalDateTime startTime; private LocalDateTime startTime;
private LocalDateTime endTime; private LocalDateTime endTime;
private Executor executor; private Executor executor;
...@@ -68,14 +68,14 @@ public class Job { ...@@ -68,14 +68,14 @@ public class Job {
GatewayType type, GatewayType type,
JobStatus status, JobStatus status,
String statement, String statement,
ExecutorSetting executorSetting, ExecutorConfig executorConfig,
Executor executor, Executor executor,
boolean useGateway) { boolean useGateway) {
this.jobConfig = jobConfig; this.jobConfig = jobConfig;
this.type = type; this.type = type;
this.status = status; this.status = status;
this.statement = statement; this.statement = statement;
this.executorSetting = executorSetting; this.executorConfig = executorConfig;
this.startTime = LocalDateTime.now(); this.startTime = LocalDateTime.now();
this.executor = executor; this.executor = executor;
this.useGateway = useGateway; this.useGateway = useGateway;
...@@ -84,11 +84,11 @@ public class Job { ...@@ -84,11 +84,11 @@ public class Job {
public static Job init( public static Job init(
GatewayType type, GatewayType type,
JobConfig jobConfig, JobConfig jobConfig,
ExecutorSetting executorSetting, ExecutorConfig executorConfig,
Executor executor, Executor executor,
String statement, String statement,
boolean useGateway) { boolean useGateway) {
return new Job(jobConfig, type, JobStatus.INITIALIZE, statement, executorSetting, executor, useGateway); return new Job(jobConfig, type, JobStatus.INITIALIZE, statement, executorConfig, executor, useGateway);
} }
public JobResult getJobResult() { public JobResult getJobResult() {
......
...@@ -21,7 +21,7 @@ package org.dinky.job; ...@@ -21,7 +21,7 @@ package org.dinky.job;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.constant.NetConstant; import org.dinky.data.constant.NetConstant;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.enums.SavePointStrategy; import org.dinky.gateway.enums.SavePointStrategy;
...@@ -387,8 +387,9 @@ public class JobConfig { ...@@ -387,8 +387,9 @@ public class JobConfig {
this.isJarTask = isJarTask; this.isJarTask = isJarTask;
} }
public ExecutorSetting getExecutorSetting() { public ExecutorConfig getExecutorSetting() {
return new ExecutorSetting( return ExecutorConfig.build(
address,
checkpoint, checkpoint,
parallelism, parallelism,
useSqlFragment, useSqlFragment,
...@@ -396,7 +397,8 @@ public class JobConfig { ...@@ -396,7 +397,8 @@ public class JobConfig {
useBatchModel, useBatchModel,
savePointPath, savePointPath,
jobName, jobName,
configJson); configJson,
variables);
} }
public void buildGatewayConfig(FlinkClusterConfig config) { public void buildGatewayConfig(FlinkClusterConfig config) {
......
...@@ -27,7 +27,6 @@ import org.dinky.api.FlinkAPI; ...@@ -27,7 +27,6 @@ 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;
import org.dinky.context.CustomTableEnvironmentContext; import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.context.RowLevelPermissionsContext; import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.data.model.FlinkUdfManifest; import org.dinky.data.model.FlinkUdfManifest;
...@@ -39,9 +38,9 @@ import org.dinky.data.result.InsertResult; ...@@ -39,9 +38,9 @@ import org.dinky.data.result.InsertResult;
import org.dinky.data.result.ResultBuilder; import org.dinky.data.result.ResultBuilder;
import org.dinky.data.result.ResultPool; import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
import org.dinky.executor.EnvironmentSetting;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
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.constant.PathConstant;
import org.dinky.function.data.model.UDF; import org.dinky.function.data.model.UDF;
...@@ -58,9 +57,9 @@ import org.dinky.interceptor.FlinkInterceptor; ...@@ -58,9 +57,9 @@ import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult; import org.dinky.interceptor.FlinkInterceptorResult;
import org.dinky.parser.SqlType; import org.dinky.parser.SqlType;
import org.dinky.process.context.ProcessContextHolder; import org.dinky.process.context.ProcessContextHolder;
import org.dinky.process.exception.DinkyException;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.trans.Operations; import org.dinky.trans.Operations;
import org.dinky.utils.DinkyClassLoaderUtil;
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;
...@@ -90,7 +89,6 @@ import java.util.List; ...@@ -90,7 +89,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -101,23 +99,16 @@ import cn.hutool.core.collection.CollUtil; ...@@ -101,23 +99,16 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil; import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
/**
* JobManager
*
* @since 2021/5/25 15:27
*/
public class JobManager { public class JobManager {
private static final Logger logger = LoggerFactory.getLogger(JobManager.class); private static final Logger logger = LoggerFactory.getLogger(JobManager.class);
private JobHandler handler; private JobHandler handler;
private EnvironmentSetting environmentSetting; private ExecutorConfig executorConfig;
private ExecutorSetting executorSetting;
private JobConfig config; private JobConfig config;
private Executor executor; private Executor executor;
private boolean useGateway = false; private boolean useGateway = false;
...@@ -165,12 +156,6 @@ public class JobManager { ...@@ -165,12 +156,6 @@ public class JobManager {
this.config = config; this.config = config;
} }
public static JobManager build() {
JobManager manager = new JobManager();
manager.init();
return manager;
}
public static JobManager build(JobConfig config) { public static JobManager build(JobConfig config) {
JobManager manager = new JobManager(config); JobManager manager = new JobManager(config);
manager.init(); manager.init();
...@@ -185,41 +170,6 @@ public class JobManager { ...@@ -185,41 +170,6 @@ public class JobManager {
return manager; return manager;
} }
private Executor createExecutor() {
initEnvironmentSetting();
if (!runMode.isLocalExecute()) {
executor = Executor.buildRemoteExecutor(environmentSetting, config.getExecutorSetting()); // 构建远端执行器
} else {
// 构建本地执行器
if (ArrayUtil.isNotEmpty(config.getJarFiles())) {
config.getExecutorSetting()
.getConfig()
.put(
PipelineOptions.JARS.key(),
Stream.of(config.getJarFiles())
.map(FileUtil::getAbsolutePath)
.collect(Collectors.joining(",")));
}
executor = Executor.buildLocalExecutor(config.getExecutorSetting());
}
StreamExecutionEnvironment env = this.getExecutor().getStreamExecutionEnvironment();
// Fix the Classloader in the env above Flink1.16 to appClassLoader, causing ckp to fail to compile
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
ReflectUtil.setFieldValue(env, "userClassloader", contextClassLoader);
executor.getSqlManager().registerSqlFragment(config.getVariables());
return executor;
}
private void initEnvironmentSetting() {
if (Asserts.isNotNullString(config.getAddress())) {
environmentSetting = EnvironmentSetting.build(config.getAddress(), config.getJarFiles());
}
}
private void initExecutorSetting() {
executorSetting = config.getExecutorSetting();
}
public boolean init() { public boolean init() {
if (!isPlanMode) { if (!isPlanMode) {
runMode = GatewayType.get(config.getType()); runMode = GatewayType.get(config.getType());
...@@ -229,9 +179,8 @@ public class JobManager { ...@@ -229,9 +179,8 @@ public class JobManager {
useStatementSet = config.isUseStatementSet(); useStatementSet = config.isUseStatementSet();
useRestAPI = SystemConfiguration.getInstances().isUseRestAPI(); useRestAPI = SystemConfiguration.getInstances().isUseRestAPI();
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator(); sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
executorConfig = config.getExecutorSetting();
initExecutorSetting(); executor = ExecutorFactory.buildExecutor(executorConfig);
createExecutor();
return false; return false;
} }
...@@ -354,52 +303,19 @@ public class JobManager { ...@@ -354,52 +303,19 @@ public class JobManager {
JobContextHolder.clear(); JobContextHolder.clear();
CustomTableEnvironmentContext.clear(); CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear(); RowLevelPermissionsContext.clear();
return false; return true;
}
public void initClassLoader(JobConfig config) {
if (CollUtil.isNotEmpty(config.getConfigJson())) {
String pipelineJars = config.getConfigJson().get(PipelineOptions.JARS.key());
String classpaths = config.getConfigJson().get(PipelineOptions.CLASSPATHS.key());
// add custom jar path
if (StrUtil.isNotBlank(pipelineJars)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
FlinkUdfPathContextHolder.addUdfPath(file);
}
}
// add custom classpath
if (StrUtil.isNotBlank(classpaths)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
FlinkUdfPathContextHolder.addOtherPlugins(file);
}
}
}
DinkyClassLoaderContextHolder.get()
.addURL(CollUtil.addAll(
FlinkUdfPathContextHolder.getUdfFile(), FlinkUdfPathContextHolder.getOtherPluginsFiles()));
} }
public JobResult executeSql(String statement) { public JobResult executeSql(String statement) {
initClassLoader(config);
ProcessEntity process = ProcessContextHolder.getProcess(); ProcessEntity process = ProcessContextHolder.getProcess();
Job job = Job.init(runMode, config, executorSetting, executor, statement, useGateway); Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
if (!useGateway) { if (!useGateway) {
job.setJobManagerAddress(environmentSetting.getAddress()); job.setJobManagerAddress(executorConfig.getJobManagerAddress());
} }
JobContextHolder.setJob(job); JobContextHolder.setJob(job);
ready(); ready();
String currentSql = ""; String currentSql = "";
DinkyClassLoaderUtil.initClassLoader(config);
JobParam jobParam = Explainer.build(executor, useStatementSet, sqlSeparator) JobParam jobParam = Explainer.build(executor, useStatementSet, sqlSeparator)
.pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator)); .pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator));
try { try {
...@@ -742,7 +658,7 @@ public class JobManager { ...@@ -742,7 +658,7 @@ public class JobManager {
public JobResult executeJar() { public JobResult executeJar() {
ProcessEntity process = ProcessContextHolder.getProcess(); ProcessEntity process = ProcessContextHolder.getProcess();
Job job = Job.init(runMode, config, executorSetting, executor, null, useGateway); Job job = Job.init(runMode, config, executorConfig, executor, null, useGateway);
JobContextHolder.setJob(job); JobContextHolder.setJob(job);
ready(); ready();
try { try {
......
/*
*
* 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.utils;
import org.dinky.assertion.Asserts;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.job.JobConfig;
import org.dinky.process.exception.DinkyException;
import org.apache.flink.configuration.PipelineOptions;
import java.io.File;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
public class DinkyClassLoaderUtil {
public static void initClassLoader(JobConfig config) {
if (CollUtil.isNotEmpty(config.getConfigJson())) {
String pipelineJars = config.getConfigJson().get(PipelineOptions.JARS.key());
String classpaths = config.getConfigJson().get(PipelineOptions.CLASSPATHS.key());
// add custom jar path
if (Asserts.isNotNullString(pipelineJars)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " not exists!");
}
FlinkUdfPathContextHolder.addUdfPath(file);
}
}
// add custom classpath
if (Asserts.isNotNullString(classpaths)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " not exists!");
}
FlinkUdfPathContextHolder.addOtherPlugins(file);
}
}
}
DinkyClassLoaderContextHolder.get()
.addURL(CollUtil.addAll(
FlinkUdfPathContextHolder.getUdfFile(), FlinkUdfPathContextHolder.getOtherPluginsFiles()));
}
}
...@@ -34,12 +34,13 @@ public interface FlinkSQLConstant { ...@@ -34,12 +34,13 @@ public interface FlinkSQLConstant {
String DML = "DML"; String DML = "DML";
/** DATASTREAM 类型 */ /** DATASTREAM 类型 */
String DATASTREAM = "DATASTREAM"; String DATASTREAM = "DATASTREAM";
/** 片段 Fragments 标识 */
String FRAGMENTS = ":=";
/** 内置日期变量前缀 */ /** The define identifier of FlinkSQL Variable */
String INNER_DATETIME_KEY = "_CURRENT_DATE_"; String VARIABLES = ":=";
/** The define identifier of FlinkSQL Date Variable */
String INNER_DATE_KEY = "_CURRENT_DATE_";
/** 内置日期变量格式 确定后不能修改 */ /** 内置日期变量格式 确定后不能修改 */
String INNER_DATETIME_FORMAT = "yyyyMMdd"; String INNER_DATE_FORMAT = "yyyy-MM-dd";
} }
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
...@@ -31,10 +29,10 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; ...@@ -31,10 +29,10 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/ */
public class AppBatchExecutor extends Executor { public class AppBatchExecutor extends Executor {
public AppBatchExecutor(ExecutorSetting executorSetting) { public AppBatchExecutor(ExecutorConfig executorConfig) {
this.executorSetting = executorSetting; this.executorConfig = executorConfig;
if (Asserts.isNotNull(executorSetting.getConfig())) { if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig()); Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
this.environment = StreamExecutionEnvironment.getExecutionEnvironment(configuration); this.environment = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
} else { } else {
this.environment = StreamExecutionEnvironment.createLocalEnvironment(); this.environment = StreamExecutionEnvironment.createLocalEnvironment();
......
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
...@@ -31,10 +29,10 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; ...@@ -31,10 +29,10 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/ */
public class AppStreamExecutor extends Executor { public class AppStreamExecutor extends Executor {
public AppStreamExecutor(ExecutorSetting executorSetting) { public AppStreamExecutor(ExecutorConfig executorConfig) {
this.executorSetting = executorSetting; this.executorConfig = executorConfig;
if (Asserts.isNotNull(executorSetting.getConfig())) { if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig()); Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
this.environment = StreamExecutionEnvironment.getExecutionEnvironment(configuration); this.environment = StreamExecutionEnvironment.getExecutionEnvironment(configuration);
} else { } else {
this.environment = StreamExecutionEnvironment.getExecutionEnvironment(); this.environment = StreamExecutionEnvironment.getExecutionEnvironment();
......
/*
*
* 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;
import org.dinky.assertion.Asserts;
import org.dinky.data.constant.NetConstant;
import lombok.Getter;
import lombok.Setter;
/**
* EnvironmentSetting
*
* @since 2021/5/25 13:45
*/
@Getter
@Setter
public class EnvironmentSetting {
private String host;
private Integer port;
private String[] jarFiles;
private boolean useRemote;
public static final EnvironmentSetting LOCAL = new EnvironmentSetting(false);
public EnvironmentSetting(boolean useRemote) {
this.useRemote = useRemote;
}
public EnvironmentSetting(String... jarFiles) {
this.useRemote = false;
this.jarFiles = jarFiles;
}
public EnvironmentSetting(String host, Integer port, String... jarFiles) {
this.host = host;
this.port = port;
this.useRemote = true;
this.jarFiles = jarFiles;
}
public static EnvironmentSetting build(String address, String... jarFiles) {
Asserts.checkNull(address, "Flink 地址不能为空");
String[] strs = getHostAndPort(address);
if (strs.length >= 2) {
return new EnvironmentSetting(strs[0], Integer.parseInt(strs[1]), jarFiles);
} else {
return new EnvironmentSetting(jarFiles);
}
}
/**
* 修复地址,解决无只有域名无端口的情况,具体情况,请看测试用例
*
* @param address flink地址(前端配置)
* @return String[]{域名,端口}
*/
static String[] getHostAndPort(String address) {
address = address.toLowerCase().replace("://", "//");
String[] strs = address.split(NetConstant.COLON);
// 兼容直接填写域名情况(走k8s ingress时没有端口号)
if (address.startsWith("http//")) {
String port = strs.length == 1 ? "80" : strs[1];
strs = new String[] {strs[0].replace("http//", ""), port};
}
if (address.startsWith("https//")) {
String port = strs.length == 1 ? "443" : strs[1];
strs = new String[] {strs[0].replace("https//", ""), port};
}
// 如果没有填端口,则默认80
if (strs.length == 1) {
strs = new String[] {address, "80"};
}
return strs;
}
public String getAddress() {
if (Asserts.isAllNotNull(host, port)) {
return host + NetConstant.COLON + port;
} else {
return "";
}
}
}
...@@ -46,11 +46,11 @@ import lombok.Setter; ...@@ -46,11 +46,11 @@ import lombok.Setter;
*/ */
@Setter @Setter
@Getter @Getter
@ApiModel(value = "ExecutorSetting", description = "Executor settings for a job") @ApiModel(value = "ExecutorConfig", description = "Executor config for a job")
public class ExecutorSetting { public class ExecutorConfig {
private static final Logger log = LoggerFactory.getLogger(ExecutorSetting.class); private static final Logger log = LoggerFactory.getLogger(ExecutorConfig.class);
public static final ExecutorSetting DEFAULT = new ExecutorSetting(0, 1, true); public static final ExecutorConfig DEFAULT = new ExecutorConfig(0, 1, true);
public static final String CHECKPOINT_CONST = "checkpoint"; public static final String CHECKPOINT_CONST = "checkpoint";
public static final String PARALLELISM_CONST = "parallelism"; public static final String PARALLELISM_CONST = "parallelism";
...@@ -63,6 +63,20 @@ public class ExecutorSetting { ...@@ -63,6 +63,20 @@ public class ExecutorSetting {
private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectMapper mapper = new ObjectMapper();
@ApiModelProperty(
value = "Job manager rest host",
dataType = "String",
example = "127.0.0.1",
notes = "Remote environment need a job manager rest host")
private String host;
@ApiModelProperty(
value = "Job manager rest port",
dataType = "Integer",
example = "8081",
notes = "Remote environment need a job manager rest port")
private Integer port;
@ApiModelProperty( @ApiModelProperty(
value = "Flag indicating whether to use batch model", value = "Flag indicating whether to use batch model",
dataType = "boolean", dataType = "boolean",
...@@ -111,42 +125,58 @@ public class ExecutorSetting { ...@@ -111,42 +125,58 @@ public class ExecutorSetting {
notes = "Map of configuration properties") notes = "Map of configuration properties")
private Map<String, String> config; private Map<String, String> config;
public ExecutorSetting(boolean useSqlFragment) { @ApiModelProperty(
value = "Map of variables",
dataType = "Map<String, String>",
example = "{\"var1\": \"value1\", \"var2\": \"value2\"}",
notes = "Map of variables")
private Map<String, String> variables;
@ApiModelProperty(
value = "List of JAR files",
dataType = "String[]",
example = "[\"file1.jar\", \"file2.jar\"]",
notes = "List of JAR files")
private String[] jarFiles;
public ExecutorConfig(boolean useSqlFragment) {
this(null, useSqlFragment); this(null, useSqlFragment);
} }
public ExecutorSetting(Integer checkpoint) { public ExecutorConfig(Integer checkpoint) {
this(checkpoint, false); this(checkpoint, false);
} }
public ExecutorSetting(Integer checkpoint, boolean useSqlFragment) { public ExecutorConfig(Integer checkpoint, boolean useSqlFragment) {
this(checkpoint, null, useSqlFragment, null, null); this(checkpoint, null, useSqlFragment, null, null);
} }
public ExecutorSetting(Integer checkpoint, Integer parallelism, boolean useSqlFragment) { public ExecutorConfig(Integer checkpoint, Integer parallelism, boolean useSqlFragment) {
this(checkpoint, parallelism, useSqlFragment, null, null); this(checkpoint, parallelism, useSqlFragment, null, null);
} }
public ExecutorSetting( public ExecutorConfig(
Integer checkpoint, Integer parallelism, boolean useSqlFragment, String savePointPath, String jobName) { Integer checkpoint, Integer parallelism, boolean useSqlFragment, String savePointPath, String jobName) {
this(checkpoint, parallelism, useSqlFragment, savePointPath, jobName, null); this(checkpoint, parallelism, useSqlFragment, savePointPath, jobName, null);
} }
public ExecutorSetting(Integer checkpoint, Integer parallelism, boolean useSqlFragment, String savePointPath) { public ExecutorConfig(Integer checkpoint, Integer parallelism, boolean useSqlFragment, String savePointPath) {
this(checkpoint, parallelism, useSqlFragment, savePointPath, null, null); this(checkpoint, parallelism, useSqlFragment, savePointPath, null, null);
} }
public ExecutorSetting( public ExecutorConfig(
Integer checkpoint, Integer checkpoint,
Integer parallelism, Integer parallelism,
boolean useSqlFragment, boolean useSqlFragment,
String savePointPath, String savePointPath,
String jobName, String jobName,
Map<String, String> config) { Map<String, String> config) {
this(checkpoint, parallelism, useSqlFragment, false, false, savePointPath, jobName, config); this(null, null, checkpoint, parallelism, useSqlFragment, false, false, savePointPath, jobName, config, null);
} }
public ExecutorSetting( private ExecutorConfig(
String host,
Integer port,
Integer checkpoint, Integer checkpoint,
Integer parallelism, Integer parallelism,
boolean useSqlFragment, boolean useSqlFragment,
...@@ -154,7 +184,10 @@ public class ExecutorSetting { ...@@ -154,7 +184,10 @@ public class ExecutorSetting {
boolean useBatchModel, boolean useBatchModel,
String savePointPath, String savePointPath,
String jobName, String jobName,
Map<String, String> config) { Map<String, String> config,
Map<String, String> variables) {
this.host = host;
this.port = port;
this.checkpoint = checkpoint; this.checkpoint = checkpoint;
this.parallelism = parallelism; this.parallelism = parallelism;
this.useSqlFragment = useSqlFragment; this.useSqlFragment = useSqlFragment;
...@@ -163,9 +196,49 @@ public class ExecutorSetting { ...@@ -163,9 +196,49 @@ public class ExecutorSetting {
this.savePointPath = savePointPath; this.savePointPath = savePointPath;
this.jobName = jobName; this.jobName = jobName;
this.config = config; this.config = config;
this.variables = variables;
} }
public static ExecutorSetting build( public static ExecutorConfig build(
String address,
Integer checkpoint,
Integer parallelism,
boolean useSqlFragment,
boolean useStatementSet,
boolean useBatchModel,
String savePointPath,
String jobName,
Map<String, String> config,
Map<String, String> variables) {
String host = null;
Integer port = null;
if (Asserts.isNotNullString(address)) {
String[] strings = address.split(":");
if (strings.length > 1) {
host = strings[0];
port = Integer.parseInt(strings[1]);
} else {
host = strings[0];
port = 8081;
}
}
return new ExecutorConfig(
host,
port,
checkpoint,
parallelism,
useSqlFragment,
useStatementSet,
useBatchModel,
savePointPath,
jobName,
config,
variables);
}
public static ExecutorConfig build(
Integer checkpoint, Integer checkpoint,
Integer parallelism, Integer parallelism,
boolean useSqlFragment, boolean useSqlFragment,
...@@ -189,7 +262,9 @@ public class ExecutorSetting { ...@@ -189,7 +262,9 @@ public class ExecutorSetting {
config.put(item.get("key"), item.get("value")); config.put(item.get("key"), item.get("value"));
} }
} }
return new ExecutorSetting( return new ExecutorConfig(
null,
null,
checkpoint, checkpoint,
parallelism, parallelism,
useSqlFragment, useSqlFragment,
...@@ -197,10 +272,11 @@ public class ExecutorSetting { ...@@ -197,10 +272,11 @@ public class ExecutorSetting {
useBatchModel, useBatchModel,
savePointPath, savePointPath,
jobName, jobName,
config); config,
null);
} }
public static ExecutorSetting build(Map<String, String> settingMap) { public static ExecutorConfig buildFromMap(Map<String, String> settingMap) {
Integer checkpoint = NumberUtils.createInteger(settingMap.get(CHECKPOINT_CONST)); Integer checkpoint = NumberUtils.createInteger(settingMap.get(CHECKPOINT_CONST));
Integer parallelism = NumberUtils.createInteger(settingMap.get(PARALLELISM_CONST)); Integer parallelism = NumberUtils.createInteger(settingMap.get(PARALLELISM_CONST));
return build( return build(
...@@ -214,6 +290,14 @@ public class ExecutorSetting { ...@@ -214,6 +290,14 @@ public class ExecutorSetting {
settingMap.get(CONFIG_CONST)); settingMap.get(CONFIG_CONST));
} }
public String getJobManagerAddress() {
return host + ":" + port;
}
public boolean isRemote() {
return Asserts.isNotNullString(this.getHost());
}
public boolean isValidParallelism() { public boolean isValidParallelism() {
return Asserts.isNotNull(this.getParallelism()) && this.getParallelism() > 0; return Asserts.isNotNull(this.getParallelism()) && this.getParallelism() > 0;
} }
...@@ -222,10 +306,26 @@ public class ExecutorSetting { ...@@ -222,10 +306,26 @@ public class ExecutorSetting {
return Asserts.isNotNullString(this.getJobName()); return Asserts.isNotNullString(this.getJobName());
} }
public boolean isValidHost() {
return Asserts.isNotNullString(this.getHost());
}
public boolean isValidPort() {
return Asserts.isNotNull(this.getPort());
}
public boolean isValidConfig() { public boolean isValidConfig() {
return Asserts.isNotNullMap(this.getConfig()); return Asserts.isNotNullMap(this.getConfig());
} }
public boolean isValidVariables() {
return Asserts.isNotNullMap(this.getVariables());
}
public boolean isValidJarFiles() {
return Asserts.isNotNull(this.getJarFiles());
}
@Override @Override
public String toString() { public String toString() {
return String.format( return String.format(
......
/*
*
* 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;
/**
* ExecutorFactory
*
* @author qiwenkai
* @since 2023/9/21 9:45
**/
public final class ExecutorFactory {
public static Executor getExecutor() {
return new LocalStreamExecutor(ExecutorConfig.DEFAULT);
}
public static Executor buildExecutor(ExecutorConfig executorConfig) {
if (executorConfig.isRemote()) {
return buildRemoteExecutor(executorConfig);
} else {
return buildLocalExecutor(executorConfig);
}
}
public static Executor buildLocalExecutor(ExecutorConfig executorConfig) {
if (executorConfig.isUseBatchModel()) {
return new LocalBatchExecutor(executorConfig);
} else {
return new LocalStreamExecutor(executorConfig);
}
}
public static Executor buildAppStreamExecutor(ExecutorConfig executorConfig) {
if (executorConfig.isUseBatchModel()) {
return new AppBatchExecutor(executorConfig);
} else {
return new AppStreamExecutor(executorConfig);
}
}
public static Executor buildRemoteExecutor(ExecutorConfig executorConfig) {
if (executorConfig.isUseBatchModel()) {
return new RemoteBatchExecutor(executorConfig);
} else {
return new RemoteStreamExecutor(executorConfig);
}
}
}
...@@ -19,12 +19,16 @@ ...@@ -19,12 +19,16 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cn.hutool.core.io.FileUtil;
/** /**
* LocalBatchExecutor * LocalBatchExecutor
* *
...@@ -32,10 +36,19 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; ...@@ -32,10 +36,19 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/ */
public class LocalBatchExecutor extends Executor { public class LocalBatchExecutor extends Executor {
public LocalBatchExecutor(ExecutorSetting executorSetting) { public LocalBatchExecutor(ExecutorConfig executorConfig) {
this.executorSetting = executorSetting; this.executorConfig = executorConfig;
if (Asserts.isNotNull(executorSetting.getConfig())) { if (executorConfig.isValidJarFiles()) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig()); executorConfig
.getConfig()
.put(
PipelineOptions.JARS.key(),
Stream.of(executorConfig.getJarFiles())
.map(FileUtil::getAbsolutePath)
.collect(Collectors.joining(",")));
}
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
if (configuration.contains(RestOptions.PORT)) { if (configuration.contains(RestOptions.PORT)) {
this.environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration); this.environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
} else { } else {
......
...@@ -19,12 +19,16 @@ ...@@ -19,12 +19,16 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cn.hutool.core.io.FileUtil;
/** /**
* LocalStreamExecuter * LocalStreamExecuter
* *
...@@ -32,10 +36,19 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; ...@@ -32,10 +36,19 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/ */
public class LocalStreamExecutor extends Executor { public class LocalStreamExecutor extends Executor {
public LocalStreamExecutor(ExecutorSetting executorSetting) { public LocalStreamExecutor(ExecutorConfig executorConfig) {
this.executorSetting = executorSetting; this.executorConfig = executorConfig;
if (Asserts.isNotNull(executorSetting.getConfig())) { if (executorConfig.isValidJarFiles()) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig()); executorConfig
.getConfig()
.put(
PipelineOptions.JARS.key(),
Stream.of(executorConfig.getJarFiles())
.map(FileUtil::getAbsolutePath)
.collect(Collectors.joining(",")));
}
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
if (configuration.contains(RestOptions.PORT)) { if (configuration.contains(RestOptions.PORT)) {
this.environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration); this.environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
} else { } else {
......
...@@ -19,8 +19,6 @@ ...@@ -19,8 +19,6 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
...@@ -31,19 +29,15 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; ...@@ -31,19 +29,15 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/ */
public class RemoteBatchExecutor extends Executor { public class RemoteBatchExecutor extends Executor {
public RemoteBatchExecutor(EnvironmentSetting environmentSetting, ExecutorSetting executorSetting) { public RemoteBatchExecutor(ExecutorConfig executorConfig) {
this.environmentSetting = environmentSetting; this.executorConfig = executorConfig;
this.executorSetting = executorSetting; if (executorConfig.isValidConfig()) {
if (Asserts.isNotNull(executorSetting.getConfig())) { Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
Configuration configuration = Configuration.fromMap(executorSetting.getConfig());
this.environment = StreamExecutionEnvironment.createRemoteEnvironment( this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
environmentSetting.getHost(), executorConfig.getHost(), executorConfig.getPort(), configuration, executorConfig.getJarFiles());
environmentSetting.getPort(),
configuration,
environmentSetting.getJarFiles());
} else { } else {
this.environment = StreamExecutionEnvironment.createRemoteEnvironment( this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
environmentSetting.getHost(), environmentSetting.getPort(), environmentSetting.getJarFiles()); executorConfig.getHost(), executorConfig.getPort(), executorConfig.getJarFiles());
} }
init(); init();
} }
......
...@@ -19,10 +19,8 @@ ...@@ -19,10 +19,8 @@
package org.dinky.executor; package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.RemoteStreamEnvironment; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
/** /**
* RemoteStreamExecutor * RemoteStreamExecutor
...@@ -31,15 +29,16 @@ import org.apache.flink.streaming.api.environment.RemoteStreamEnvironment; ...@@ -31,15 +29,16 @@ import org.apache.flink.streaming.api.environment.RemoteStreamEnvironment;
*/ */
public class RemoteStreamExecutor extends Executor { public class RemoteStreamExecutor extends Executor {
public RemoteStreamExecutor(EnvironmentSetting environmentSetting, ExecutorSetting executorSetting) { public RemoteStreamExecutor(ExecutorConfig executorConfig) {
this.environmentSetting = environmentSetting; this.executorConfig = executorConfig;
this.executorSetting = executorSetting; if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
Configuration configuration = Asserts.isNotNull(executorSetting.getConfig()) this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
? Configuration.fromMap(executorSetting.getConfig()) executorConfig.getHost(), executorConfig.getPort(), configuration, executorConfig.getJarFiles());
: null; } else {
this.environment = this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
new RemoteStreamEnvironment(environmentSetting.getHost(), environmentSetting.getPort(), configuration); executorConfig.getHost(), executorConfig.getPort(), executorConfig.getJarFiles());
}
init(); init();
} }
......
...@@ -39,7 +39,7 @@ public class FlinkInterceptor { ...@@ -39,7 +39,7 @@ public class FlinkInterceptor {
public static String pretreatStatement(Executor executor, String statement) { public static String pretreatStatement(Executor executor, String statement) {
statement = SqlUtil.removeNote(statement); statement = SqlUtil.removeNote(statement);
if (executor.isUseSqlFragment()) { if (executor.isUseSqlFragment()) {
statement = executor.getSqlManager().parseVariable(statement); statement = executor.getVariableManager().parseVariable(statement);
} }
return statement.trim(); return statement.trim();
} }
......
...@@ -61,9 +61,9 @@ public class ShowFragmentOperation extends AbstractOperation implements Operatio ...@@ -61,9 +61,9 @@ public class ShowFragmentOperation extends AbstractOperation implements Operatio
Map<String, List<String>> map = SingleSqlParserFactory.generateParser(statement); Map<String, List<String>> map = SingleSqlParserFactory.generateParser(statement);
if (Asserts.isNotNullMap(map)) { if (Asserts.isNotNullMap(map)) {
if (map.containsKey("FRAGMENT")) { if (map.containsKey("FRAGMENT")) {
return executor.getSqlManager().getSqlFragmentResult(StringUtils.join(map.get("FRAGMENT"), "")); return executor.getVariableManager().getVariableResult(StringUtils.join(map.get("FRAGMENT"), ""));
} }
} }
return executor.getSqlManager().getSqlFragmentResult(null); return executor.getVariableManager().getVariableResult(null);
} }
} }
...@@ -52,6 +52,6 @@ public class ShowFragmentsOperation extends AbstractOperation implements Operati ...@@ -52,6 +52,6 @@ public class ShowFragmentsOperation extends AbstractOperation implements Operati
@Override @Override
public TableResult build(Executor executor) { public TableResult build(Executor executor) {
return executor.getSqlManager().getSqlFragments(); return executor.getVariableManager().getVariables();
} }
} }
/*
*
* 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.utils;
import org.dinky.assertion.Asserts;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KerberosUtil {
private static final Logger logger = LoggerFactory.getLogger(KerberosUtil.class);
private static void reset() {
try {
if (UserGroupInformation.isLoginKeytabBased()) {
Method reset = UserGroupInformation.class.getDeclaredMethod("reset");
reset.invoke(UserGroupInformation.class);
logger.info("Reset kerberos authentication...");
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException e) {
logger.error("Reset kerberos authentication error.", e);
throw new RuntimeException(e);
}
}
public static void authenticate(Map<String, Object> configuration) {
configuration.forEach((k, v) -> logger.debug("Flink configuration key: [{}], value: [{}]", k, v));
String krb5ConfPath = (String) configuration.getOrDefault("java.security.krb5.conf", "");
String keytabPath = (String) configuration.getOrDefault("security.kerberos.login.keytab", "");
String principal = (String) configuration.getOrDefault("security.kerberos.login.principal", "");
if (Asserts.isAllNullString(krb5ConfPath, keytabPath, principal)) {
logger.info("Simple authentication mode");
return;
}
logger.info("Kerberos authentication mode");
if (Asserts.isNullString(krb5ConfPath)) {
logger.error("Parameter [java.security.krb5.conf] is null or empty.");
return;
}
if (Asserts.isNullString(keytabPath)) {
logger.error("Parameter [security.kerberos.login.keytab] is null or empty.");
return;
}
if (Asserts.isNullString(principal)) {
logger.error("Parameter [security.kerberos.login.principal] is null or empty.");
return;
}
reset();
System.setProperty("java.security.krb5.conf", krb5ConfPath);
org.apache.hadoop.conf.Configuration config = new org.apache.hadoop.conf.Configuration();
config.set("hadoop.security.authentication", "Kerberos");
config.setBoolean("hadoop.security.authorization", true);
UserGroupInformation.setConfiguration(config);
try {
UserGroupInformation.loginUserFromKeytab(principal, keytabPath);
logger.error(
"Kerberos [{}] authentication success.",
UserGroupInformation.getLoginUser().getUserName());
} catch (IOException e) {
logger.error("Kerberos authentication failed. ", e);
}
}
}
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
package org.dinky.executor; package org.dinky.executor;
import static org.dinky.executor.ExecutorSetting.CHECKPOINT_CONST; import static org.dinky.executor.ExecutorConfig.CHECKPOINT_CONST;
import static org.dinky.executor.ExecutorSetting.PARALLELISM_CONST; import static org.dinky.executor.ExecutorConfig.PARALLELISM_CONST;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import java.util.Collections; import java.util.Collections;
...@@ -30,7 +30,7 @@ import java.util.Map; ...@@ -30,7 +30,7 @@ import java.util.Map;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** */ /** */
class ExecutorSettingTest { class ExecutorConfigTest {
@Test @Test
void build() { void build() {
...@@ -38,11 +38,11 @@ class ExecutorSettingTest { ...@@ -38,11 +38,11 @@ class ExecutorSettingTest {
maps.put(CHECKPOINT_CONST, "123"); maps.put(CHECKPOINT_CONST, "123");
maps.put(PARALLELISM_CONST, "456"); maps.put(PARALLELISM_CONST, "456");
ExecutorSetting es = ExecutorSetting.build(maps); ExecutorConfig es = ExecutorConfig.buildFromMap(maps);
assertEquals(123, es.getCheckpoint()); assertEquals(123, es.getCheckpoint());
assertEquals(456, es.getParallelism()); assertEquals(456, es.getParallelism());
ExecutorSetting esNull = ExecutorSetting.build(Collections.emptyMap()); ExecutorConfig esNull = ExecutorConfig.buildFromMap(Collections.emptyMap());
assertNull(esNull.getCheckpoint()); assertNull(esNull.getCheckpoint());
assertNull(esNull.getParallelism()); assertNull(esNull.getParallelism());
} }
......
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
package org.dinky.interceptor; package org.dinky.interceptor;
import org.dinky.executor.Executor; import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorSetting; import org.dinky.executor.ExecutorConfig;
import org.dinky.executor.LocalStreamExecutor; import org.dinky.executor.ExecutorFactory;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
...@@ -48,8 +48,8 @@ public class CdcSourceTests { ...@@ -48,8 +48,8 @@ public class CdcSourceTests {
.append(")") .append(")")
.toString(); .toString();
ExecutorSetting executorSetting = ExecutorSetting.DEFAULT; ExecutorConfig executorConfig = ExecutorConfig.DEFAULT;
Executor executor = LocalStreamExecutor.buildLocalExecutor(executorSetting); Executor executor = ExecutorFactory.buildLocalExecutor(executorConfig);
executor.executeSql(statement); executor.executeSql(statement);
executor.execute(""); executor.execute("");
} }
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
package org.dinky.interceptor; package org.dinky.interceptor;
import org.dinky.executor.Executor; import org.dinky.executor.ExecutorFactory;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Ignore; import org.junit.Ignore;
...@@ -38,7 +38,7 @@ public class FlinkInterceptorTest { ...@@ -38,7 +38,7 @@ public class FlinkInterceptorTest {
String statement = "nullif1:=NULLIF(1, 0) as val;\n" String statement = "nullif1:=NULLIF(1, 0) as val;\n"
+ "nullif2:=NULLIF(0, 0) as val$null;\n" + "nullif2:=NULLIF(0, 0) as val$null;\n"
+ "select ${nullif1},${nullif2}"; + "select ${nullif1},${nullif2}";
String pretreatStatement = FlinkInterceptor.pretreatStatement(Executor.build(), statement); String pretreatStatement = FlinkInterceptor.pretreatStatement(ExecutorFactory.getExecutor(), statement);
Assert.assertEquals("select NULLIF(1, 0) as val,NULLIF(0, 0) as val$null", pretreatStatement); Assert.assertEquals("select NULLIF(1, 0) as val,NULLIF(0, 0) as val$null", pretreatStatement);
} }
} }
...@@ -94,11 +94,11 @@ public enum GatewayType { ...@@ -94,11 +94,11 @@ public enum GatewayType {
} }
public boolean isDeployCluster() { public boolean isDeployCluster() {
switch (value) { switch (this) {
case "ya": case YARN_APPLICATION:
case "ypj": case YARN_PER_JOB:
case "ka": case KUBERNETES_APPLICATION:
case "kao": case KUBERNETES_APPLICATION_OPERATOR:
return true; return true;
default: default:
return false; return false;
...@@ -106,10 +106,10 @@ public enum GatewayType { ...@@ -106,10 +106,10 @@ public enum GatewayType {
} }
public boolean isApplicationMode() { public boolean isApplicationMode() {
switch (value) { switch (this) {
case "ya": case YARN_APPLICATION:
case "ka": case KUBERNETES_APPLICATION:
case "kao": case KUBERNETES_APPLICATION_OPERATOR:
return true; return true;
default: default:
return false; return false;
......
...@@ -109,7 +109,6 @@ const Result = (props: any) => { ...@@ -109,7 +109,6 @@ const Result = (props: any) => {
} }
const params = currentTabs.params; const params = currentTabs.params;
if (params.resultData && !isRefresh) { if (params.resultData && !isRefresh) {
setData(params.resultData); setData(params.resultData);
} else { } else {
...@@ -120,7 +119,6 @@ const Result = (props: any) => { ...@@ -120,7 +119,6 @@ const Result = (props: any) => {
}); });
if (res.datas) { if (res.datas) {
params.resultData = res.datas; params.resultData = res.datas;
saveTabs({ ...props.tabs });
setData(res.datas); setData(res.datas);
} }
} else { } else {
...@@ -139,7 +137,10 @@ const Result = (props: any) => { ...@@ -139,7 +137,10 @@ const Result = (props: any) => {
datas.jid = jid; datas.jid = jid;
if (datas.success) { if (datas.success) {
params.resultData = datas; params.resultData = datas;
saveTabs({ ...props.tabs }); setData(datas);
}else {
params.resultData = {};
setData({});
} }
} }
} }
...@@ -218,7 +219,7 @@ const Result = (props: any) => { ...@@ -218,7 +219,7 @@ const Result = (props: any) => {
{data.columns ? ( {data.columns ? (
<Table <Table
columns={getColumns(data.columns)} columns={getColumns(data.columns)}
dataSource={data.rowData!.map((item: any, index: number) => { dataSource={data.rowData?.map((item: any, index: number) => {
return { ...item, key: index }; return { ...item, key: index };
})} })}
loading={loading} loading={loading}
......
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