Unverified Commit 80e0c7ed authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature] [Sql] Add Flink Jar sql (#2412)

* add-flink-jar-sql * add-flink-jar-sql * add-flink-jar-sql
parent e0017561
......@@ -125,7 +125,8 @@ public class TaskController {
@PostMapping("/getJobPlan")
@ApiOperation("Get Job Plan")
public Result<ObjectNode> getJobPlan(@RequestBody TaskDTO taskDTO) {
@ExecuteProcess(type = ProcessType.FLINK_JOB_PLAN)
public Result<ObjectNode> getJobPlan(@ProcessId @RequestBody TaskDTO taskDTO) {
return Result.succeed(taskService.getJobPlan(taskDTO), Status.EXECUTE_SUCCESS);
}
......
/*
*
* 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.annotation;
import org.dinky.config.Dialect;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义操作日志记录注解
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SupportDialect {
/**
* 模块
*/
public Dialect[] value();
}
......@@ -61,6 +61,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
......@@ -81,6 +82,7 @@ import lombok.RequiredArgsConstructor;
@Component
@Order(value = 1)
@RequiredArgsConstructor
@Profile("!test")
public class SystemInit implements ApplicationRunner {
private final SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
......
......@@ -24,7 +24,6 @@ import org.dinky.config.Dialect;
import org.dinky.context.TenantContextHolder;
import org.dinky.data.constant.CommonConstant;
import org.dinky.data.dto.AbstractStatementDTO;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.TaskRollbackVersionDTO;
import org.dinky.data.enums.JobLifeCycle;
......@@ -50,7 +49,6 @@ import org.dinky.data.model.TaskExtConfig;
import org.dinky.data.model.TaskVersion;
import org.dinky.data.model.UDFTemplate;
import org.dinky.data.result.Result;
import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.function.compiler.CustomStringJavaCompiler;
......@@ -67,7 +65,6 @@ import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
import org.dinky.job.JobResult;
import org.dinky.mapper.TaskMapper;
import org.dinky.metadata.result.JdbcSelectResult;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.parser.SqlType;
import org.dinky.process.annotations.ProcessStep;
......@@ -85,6 +82,7 @@ import org.dinky.service.TaskService;
import org.dinky.service.TaskVersionService;
import org.dinky.service.UDFTemplateService;
import org.dinky.service.UserService;
import org.dinky.service.task.BaseTask;
import org.dinky.trans.Operations;
import org.dinky.utils.FragmentVariableUtils;
import org.dinky.utils.JsonUtils;
......@@ -129,6 +127,7 @@ import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.StrFormatter;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
/**
......@@ -203,22 +202,11 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeJob(TaskDTO task) throws Exception {
JobResult jobResult;
if (Dialect.isCommonSql(task.getDialect())) {
log.info("Preparing to execute common sql...");
SqlDTO sqlDTO = SqlDTO.build(task.getStatement(), task.getDatabaseId(), null);
jobResult = dataBaseService.executeCommonSql(sqlDTO);
ResultPool.putCommonSqlCache(task.getId(), (JdbcSelectResult) jobResult.getResult());
} else {
log.info("Initializing Flink job config...");
JobManager jobManager = JobManager.build(
applicationContext.getBean(TaskServiceImpl.class).buildJobConfig(task));
jobResult = jobManager.executeSql(task.getStatement());
}
jobResult = BaseTask.getTask(task).execute();
log.info("execute job finished,status is {}", jobResult.getStatus());
return jobResult;
}
@ProcessStep(type = ProcessStepType.SUBMIT_BUILD_CONFIG)
public JobConfig buildJobConfig(TaskDTO task) {
task.setStatement(buildEnvSql(task) + task.getStatement());
JobConfig config = task.getJobConfig();
......@@ -344,26 +332,14 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override
public List<SqlExplainResult> explainTask(TaskDTO task) throws NotSupportExplainExcepition {
if (Dialect.isCommonSql(task.getDialect())) {
return dataBaseService.explainCommonSql(task);
} else if (task.getDialect().equals(Dialect.FLINK_SQL.getValue())) {
JobConfig config = buildJobConfig(task);
config.buildLocal();
JobManager jobManager = JobManager.buildPlanMode(config);
return jobManager.explainSql(task.getStatement()).getSqlExplainResults();
}
throw new NotSupportExplainExcepition(StrFormatter.format(
"task [{}] dialect [{}] is can not explain, skip sqlExplain verify",
task.getName(),
task.getDialect()));
return BaseTask.getTask(task).explain();
}
@SneakyThrows
@Override
public ObjectNode getJobPlan(TaskDTO task) {
JobManager jobManager = JobManager.buildPlanMode(buildJobConfig(task));
String planJson = jobManager.getJobPlanJson(task.getStatement());
return JsonUtils.parseObject(planJson);
BaseTask baseTask = BaseTask.getTask(task);
return baseTask.getJobPlan();
}
@Override
......
/*
*
* 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.service.task;
import org.dinky.config.Dialect;
import org.dinky.data.annotation.SupportDialect;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobResult;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public abstract class BaseTask {
private static final Cache<String, SelectResult> results = new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
final TaskDTO task;
public abstract JobResult execute() throws Exception;
public abstract boolean stop();
public List<SqlExplainResult> explain() throws NotSupportExplainExcepition {
throw new NotSupportExplainExcepition(StrFormatter.format(
"task [{}] dialect [{}] is can not explain, skip sqlExplain verify",
task.getName(),
task.getDialect()));
}
public ObjectNode getJobPlan() throws NotSupportExplainExcepition {
throw new NotSupportExplainExcepition(
StrFormatter.format("task [{}] dialect [{}] is can not getJobPlan", task.getName(), task.getDialect()));
}
public static BaseTask getTask(TaskDTO taskDTO) {
Set<Class<?>> classes =
ClassUtil.scanPackageBySuper(BaseTask.class.getPackage().getName(), BaseTask.class);
for (Class<?> clazz : classes) {
SupportDialect annotation = clazz.getAnnotation(SupportDialect.class);
if (annotation != null) {
for (Dialect dialect : annotation.value()) {
if (dialect.getValue().equalsIgnoreCase(taskDTO.getDialect())) {
return (BaseTask) ReflectUtil.newInstance(clazz, taskDTO);
}
}
}
}
throw new RuntimeException("Not support dialect: " + taskDTO.getDialect());
}
}
/*
*
* 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.service.task;
import org.dinky.config.Dialect;
import org.dinky.data.annotation.SupportDialect;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobResult;
import org.dinky.service.DataBaseService;
import java.util.List;
import java.util.concurrent.TimeUnit;
import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SupportDialect({
Dialect.SQL,
Dialect.MYSQL,
Dialect.ORACLE,
Dialect.POSTGRESQL,
Dialect.HIVE,
Dialect.SQLSERVER,
Dialect.CLICKHOUSE,
Dialect.DORIS,
Dialect.PHOENIX,
Dialect.STAR_ROCKS,
Dialect.PRESTO
})
public class CommonSqlTask extends BaseTask {
private static final Cache<Integer, JobResult> COMMON_SQL_SEARCH_CACHE =
new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
public CommonSqlTask(TaskDTO task) {
super(task);
}
@Override
public List<SqlExplainResult> explain() {
DataBaseService dataBaseService = SpringUtil.getBean(DataBaseService.class);
return dataBaseService.explainCommonSql(task);
}
@Override
public JobResult execute() {
log.info("Preparing to execute common sql...");
SqlDTO sqlDTO = SqlDTO.build(task.getStatement(), task.getDatabaseId(), null);
DataBaseService dataBaseService = SpringUtil.getBean(DataBaseService.class);
return COMMON_SQL_SEARCH_CACHE.get(task.getId(), () -> dataBaseService.executeCommonSql(sqlDTO));
}
@Override
public boolean stop() {
return false;
}
}
/*
*
* 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.service.task;
import org.dinky.config.Dialect;
import org.dinky.data.annotation.SupportDialect;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobResult;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.node.ObjectNode;
@SupportDialect(Dialect.FLINK_JAR)
public class FlinkJarSqlTask extends FlinkSqlTask {
public FlinkJarSqlTask(TaskDTO task) {
super(task);
}
@Override
public List<SqlExplainResult> explain() {
return new ArrayList<>();
}
@Override
public JobResult execute() throws Exception {
return jobManager.executeJarSql(task.getStatement());
}
@Override
public boolean stop() {
return false;
}
@Override
public ObjectNode getJobPlan() {
try {
return jobManager.getJarStreamGraphJson(task.getStatement());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/*
*
* 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.service.task;
import org.dinky.config.Dialect;
import org.dinky.data.annotation.SupportDialect;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobManager;
import org.dinky.job.JobResult;
import org.dinky.service.impl.TaskServiceImpl;
import org.dinky.utils.JsonUtils;
import java.util.List;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SupportDialect(Dialect.FLINK_SQL)
public class FlinkSqlTask extends BaseTask {
protected final JobManager jobManager;
public FlinkSqlTask(TaskDTO task) {
super(task);
this.jobManager = getJobManager();
}
@Override
public List<SqlExplainResult> explain() {
return jobManager.explainSql(task.getStatement()).getSqlExplainResults();
}
public ObjectNode getJobPlan() {
String planJson = jobManager.getJobPlanJson(task.getStatement());
return JsonUtils.parseObject(planJson);
}
@Override
public JobResult execute() throws Exception {
log.info("Initializing Flink job config...");
return jobManager.executeSql(task.getStatement());
}
protected JobManager getJobManager() {
TaskServiceImpl taskService = SpringUtil.getBean(TaskServiceImpl.class);
return JobManager.build(taskService.buildJobConfig(task));
}
@Override
public boolean stop() {
return false;
}
}
/*
*
* 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.service.task;
import org.dinky.config.Dialect;
import org.dinky.data.annotation.SupportDialect;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Task;
import org.dinky.job.JobResult;
import org.dinky.utils.UDFUtils;
import cn.hutool.core.bean.BeanUtil;
@SupportDialect({Dialect.JAVA, Dialect.PYTHON, Dialect.SCALA})
public class UdfTask extends BaseTask {
public UdfTask(TaskDTO task) {
super(task);
}
@Override
public JobResult execute() throws Exception {
UDFUtils.taskToUDF(BeanUtil.toBean(task, Task.class));
return null;
}
@Override
public boolean stop() {
return false;
}
}
......@@ -24,8 +24,11 @@ import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import org.springframework.context.annotation.Profile;
import cn.hutool.core.lang.Singleton;
@Profile("!test")
public class RsURLStreamHandlerFactory implements URLStreamHandlerFactory {
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
......
......@@ -19,6 +19,15 @@
package org.dinky.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
/**
* RunTimeUtil
*
......@@ -30,4 +39,80 @@ public class RunTimeUtil {
obj = null;
System.gc();
}
/**
* 处理命令,多行命令原样返回,单行命令拆分处理
*
* @param cmds 命令
* @return 处理后的命令
*/
public static String[] handleCmds(String... cmds) {
if (ArrayUtil.isEmpty(cmds)) {
throw new NullPointerException("Command is empty !");
}
// 单条命令的情况
if (1 == cmds.length) {
final String cmd = cmds[0];
if (StrUtil.isBlank(cmd)) {
throw new NullPointerException("Command is blank !");
}
cmds = cmdSplit(cmd);
}
return cmds;
}
/**
* 命令分割,使用空格分割,考虑双引号和单引号的情况
*
* @param cmd 命令,如 git commit -m 'test commit'
* @return 分割后的命令
*/
public static String[] cmdSplit(String cmd) {
final List<String> cmds = new ArrayList<>();
final int length = cmd.length();
final Stack<Character> stack = new Stack<>();
boolean inWrap = false;
final StrBuilder cache = StrUtil.strBuilder();
char c;
for (int i = 0; i < length; i++) {
c = cmd.charAt(i);
switch (c) {
case CharUtil.SINGLE_QUOTE:
case CharUtil.DOUBLE_QUOTES:
if (inWrap) {
if (c == stack.peek()) {
// 结束包装
stack.pop();
inWrap = false;
}
cache.append(c);
} else {
stack.push(c);
cache.append(c);
inWrap = true;
}
break;
case CharUtil.SPACE:
if (inWrap) {
// 处于包装内
cache.append(c);
} else {
cmds.add(cache.toString());
cache.reset();
}
break;
default:
cache.append(c);
break;
}
}
if (cache.hasContent()) {
cmds.add(cache.toString());
}
return cmds.toArray(new String[0]);
}
}
......@@ -57,10 +57,15 @@ import org.dinky.gateway.result.TestResult;
import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult;
import org.dinky.parser.SqlType;
import org.dinky.parser.check.AddJarSqlParser;
import org.dinky.process.annotations.ProcessStep;
import org.dinky.process.enums.ProcessStepType;
import org.dinky.process.exception.DinkyException;
import org.dinky.trans.ExecuteJarParseStrategy;
import org.dinky.trans.Operations;
import org.dinky.trans.dml.ExecuteJarOperation;
import org.dinky.utils.DinkyClassLoaderUtil;
import org.dinky.utils.JsonUtils;
import org.dinky.utils.LogUtil;
import org.dinky.utils.SqlUtil;
import org.dinky.utils.URLUtils;
......@@ -73,6 +78,7 @@ import org.apache.flink.core.execution.JobClient;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.runtime.jobgraph.jsonplan.JsonPlanGenerator;
import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
......@@ -95,6 +101,7 @@ 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.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
......@@ -300,9 +307,88 @@ public class JobManager {
JobContextHolder.clear();
CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear();
FlinkUdfPathContextHolder.clear();
return true;
}
public ObjectNode getJarStreamGraphJson(String statement) throws Exception {
StreamGraph streamGraph = getJarStreamGraph(statement);
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 sqlStatement = executor.pretreatStatement(statements[i]);
if (ExecuteJarParseStrategy.INSTANCE.match(sqlStatement)) {
currentSql = sqlStatement;
executeJarOperation = new ExecuteJarOperation(statement);
break;
}
SqlType operationType = Operations.getOperationType(statement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParser.getAllFilePath(statement).forEach(executor::addJar);
}
}
Assert.notNull(executeJarOperation, () -> new DinkyException("Not found execute jar operation."));
return executeJarOperation.explain(executor);
}
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeJarSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
if (!useGateway) {
job.setJobManagerAddress(executorConfig.getJobManagerAddress());
}
JobContextHolder.setJob(job);
StreamGraph streamGraph = getJarStreamGraph(statement);
try {
if (!useGateway) {
executor.getStreamExecutionEnvironment().executeAsync(streamGraph);
} else {
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
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());
}
}
job.setStatus(Job.JobStatus.SUCCESS);
success();
} catch (Exception e) {
String error = LogUtil.getError("Exception in executing FlinkJarSQL:\n" + addLineNumber(statement), e);
job.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED);
job.setError(error);
failed();
throw e;
} finally {
close();
}
return job.getJobResult();
}
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
......
......@@ -31,6 +31,7 @@ import org.dinky.utils.KerberosUtil;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.core.execution.JobClient;
......@@ -46,9 +47,14 @@ import org.apache.flink.table.api.StatementSet;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableResult;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -57,7 +63,9 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.URLUtil;
/**
* Executor
......@@ -195,6 +203,34 @@ public abstract class Executor {
configuration.setString(PythonOptions.PYTHON_CLIENT_EXECUTABLE, executable);
}
private void addJar(String... jarPath) {
Configuration configuration = tableEnvironment.getRootConfiguration();
List<String> jars = configuration.get(PipelineOptions.JARS);
if (jars == null) {
configuration.set(PipelineOptions.JARS, CollUtil.newArrayList(jarPath));
} else {
CollUtil.addAll(jars, jarPath);
}
}
public void addJar(File... jarPath) {
addJar(Arrays.stream(jarPath).map(URLUtil::getURL).map(URL::toString).toArray(String[]::new));
}
public void addJar(Collection<File> jarPath) {
addJar(jarPath.stream().map(URLUtil::getURL).map(URL::toString).toArray(String[]::new));
}
public <T> void updateConfiguration(ConfigOption<T> configOption, T value) {
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
configuration.set(configOption, value);
}
public <T> void updateConfiguration(Consumer<Configuration> configurationConsumer) {
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
configurationConsumer.accept(configuration);
}
public SqlExplainResult explainSqlRecord(String statement, ExplainDetail... extraDetails) {
statement = pretreatStatement(statement);
if (Asserts.isNotNullString(statement) && !pretreatExecute(statement).isNoExecute()) {
......
/*
*
* 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.trans;
import org.dinky.parser.SqlSegment;
import org.dinky.trans.dml.ExecuteJarOperation;
import org.apache.flink.table.operations.Operation;
import org.apache.flink.table.planner.parse.AbstractRegexParseStrategy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
public class ExecuteJarParseStrategy extends AbstractRegexParseStrategy {
private static final String PATTERN_STR = "^EXECUTE\\s+JAR\\s+WITH\\s+\\(\\s+(.*\\s+)+\\)";
private static final Pattern PATTERN = Pattern.compile(PATTERN_STR, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
public static final ExecuteJarParseStrategy INSTANCE = new ExecuteJarParseStrategy();
protected ExecuteJarParseStrategy() {
super(PATTERN);
}
public static ExecuteJarOperation.JarSubmitParam getInfo(String statement) {
statement = statement.replace("\r\n", " ").replace("\n", " ") + " ENDOFSQL";
SqlSegment sqlSegment = new SqlSegment("with", "(with\\s+\\()(.+)(\\))", "',");
sqlSegment.parse(statement);
List<String> bodyPieces = sqlSegment.getBodyPieces();
Map<String, String> keyValue = getKeyValue(bodyPieces);
return BeanUtil.toBean(
keyValue,
ExecuteJarOperation.JarSubmitParam.class,
CopyOptions.create().setFieldNameEditor(s -> StrUtil.toCamelCase(s, '-')));
}
private static Map<String, String> getKeyValue(List<String> list) {
Map<String, String> map = new HashMap<>();
Pattern p = Pattern.compile("'(.*?)'\\s*=\\s*'(.*?)'");
for (String s : list) {
Matcher m = p.matcher(s + "'");
if (m.find()) {
map.put(m.group(1), m.group(2));
}
}
return map;
}
@Override
public Operation convert(String statement) {
return new ExecuteJarOperation(statement);
}
@Override
public String[] getHints() {
return new String[0];
}
}
/*
*
* 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.trans.dml;
import org.dinky.executor.CustomTableResultImpl;
import org.dinky.executor.Executor;
import org.dinky.trans.AbstractOperation;
import org.dinky.trans.ExecuteJarParseStrategy;
import org.dinky.trans.ExtendOperation;
import org.dinky.utils.RunTimeUtil;
import org.apache.flink.api.dag.Pipeline;
import org.apache.flink.client.program.PackagedProgram;
import org.apache.flink.client.program.PackagedProgramUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult;
import java.io.File;
import java.util.Optional;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
public class ExecuteJarOperation extends AbstractOperation implements ExtendOperation {
public ExecuteJarOperation(String statement) {
super(statement);
}
@Override
public Optional<? extends TableResult> execute(Executor executor) {
try {
executor.getStreamExecutionEnvironment().execute(getStreamGraph(executor));
} catch (Exception e) {
throw new RuntimeException(e);
}
return Optional.of(CustomTableResultImpl.TABLE_RESULT_OK);
}
protected StreamGraph getStreamGraph(Executor executor) {
JarSubmitParam submitParam = JarSubmitParam.build(statement);
SavepointRestoreSettings savepointRestoreSettings = StrUtil.isBlank(submitParam.getSavepointPath())
? SavepointRestoreSettings.none()
: SavepointRestoreSettings.forPath(
submitParam.getSavepointPath(), submitParam.getAllowNonRestoredState());
PackagedProgram program;
try {
Configuration configuration = executor.getTableConfig().getConfiguration();
File file = FileUtil.file(submitParam.getUri());
program = PackagedProgram.newBuilder()
.setJarFile(file)
.setEntryPointClassName(submitParam.getMainClass())
.setConfiguration(configuration)
.setSavepointRestoreSettings(savepointRestoreSettings)
.setArguments(RunTimeUtil.handleCmds(submitParam.getArgs()))
.build();
executor.addJar(file);
Pipeline pipeline = PackagedProgramUtils.getPipelineFromProgram(program, configuration, 1, true);
Assert.isTrue(pipeline instanceof StreamGraph, "can not translate");
return (StreamGraph) pipeline;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public String asSummaryString() {
return statement;
}
public StreamGraph explain(Executor executor) {
return getStreamGraph(executor);
}
@Setter
@Getter
public static class JarSubmitParam {
protected JarSubmitParam() {}
private String uri;
private String mainClass;
private String args;
private String parallelism;
private String savepointPath;
private Boolean allowNonRestoredState = SavepointConfigOptions.SAVEPOINT_IGNORE_UNCLAIMED_STATE.defaultValue();
public static JarSubmitParam build(String statement) {
JarSubmitParam submitParam = ExecuteJarParseStrategy.getInfo(statement);
Assert.notBlank(submitParam.getUri());
Assert.notBlank(submitParam.getMainClass());
return submitParam;
}
}
}
......@@ -61,7 +61,7 @@ public class FlinkClusterConfig {
value = "Application Configuration",
dataType = "AppConfig",
notes = "Configuration settings for the application")
private AppConfig appConfig;
private AppConfig appConfig = new AppConfig();
@ApiModelProperty(
value = "Kubernetes Configuration",
......
......@@ -30,6 +30,7 @@ public enum ProcessType {
FLINK_EXPLAIN("FlinkExplain"),
FLINK_EXECUTE("FlinkExecute"),
FLINK_SUBMIT("FlinkSubmit"),
FLINK_JOB_PLAN("FLinkJobPlan"),
SQL_EXPLAIN("SQLExplain"),
SQL_EXECUTE("SQLExecute"),
SQL_SUBMIT("SQLSubmit"),
......
......@@ -124,7 +124,8 @@ export enum TabsPageType {
}
export enum TabsPageSubType {
flinkSql = 'FlinkSql'
flinkSql = 'FlinkSql',
flinkJar = 'FlinkJar',
}
export interface TabsItemType {
......
......@@ -90,7 +90,7 @@ export const RightSide: TabProp[] = [
icon: <SettingOutlined />,
label: l('menu.datastudio.jobConfig'),
children: <JobConfig />,
isShow: (type, subType) => type === TabsPageType.project && TabsPageSubType.flinkSql === subType
isShow: (type, subType) => type === TabsPageType.project && (TabsPageSubType.flinkSql === subType||TabsPageSubType.flinkJar === subType)
},
{
auth: '/datastudio/right/executeConfig',
......
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