Unverified Commit 6fab188d authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Optimize][udf]重构udf,使udf单独迁移到 dlink-function 模块 (#1184)

* 重构udf,使udf单独迁移到 dlink-function 模块 * 删除多于代码 * 添加udf 使用文档 * 添加类缺失 * 添加注释 * 添加注释 * 修改dlink-admin pom * 修改dlink-admin pom * 修改dlink-function pom * 添加github workflow 查看最终打包的大小 * 修订com.dlink.ud更换为com.dlink.function
parent 928ff281
...@@ -60,6 +60,10 @@ jobs: ...@@ -60,6 +60,10 @@ jobs:
-Dmaven.test.skip=true \ -Dmaven.test.skip=true \
-Dcheckstyle.skip=true \ -Dcheckstyle.skip=true \
--no-snapshot-updates --no-snapshot-updates
# 查看打包的大小
- name: View package size
run: |
cd build && ls -lh
# - name: Run Unit tests # - name: Run Unit tests
# run: | # run: |
# ./mvnw -T 2C -B clean verify -Dmaven.test.skip=false -Dgpg.skip=true --no-snapshot-updates # ./mvnw -T 2C -B clean verify -Dmaven.test.skip=false -Dgpg.skip=true --no-snapshot-updates
...@@ -145,6 +145,10 @@ ...@@ -145,6 +145,10 @@
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-core</artifactId> <artifactId>dlink-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-function</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-common</artifactId> <artifactId>dlink-common</artifactId>
......
...@@ -21,13 +21,13 @@ package com.dlink.controller; ...@@ -21,13 +21,13 @@ package com.dlink.controller;
import com.dlink.common.result.ProTableResult; import com.dlink.common.result.ProTableResult;
import com.dlink.common.result.Result; import com.dlink.common.result.Result;
import com.dlink.constant.PathConstant; import com.dlink.function.constant.PathConstant;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
import com.dlink.model.Jar; import com.dlink.model.Jar;
import com.dlink.model.Task; import com.dlink.model.Task;
import com.dlink.service.JarService; import com.dlink.service.JarService;
import com.dlink.service.TaskService; import com.dlink.service.TaskService;
import com.dlink.udf.UDF;
import com.dlink.utils.UDFUtil;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
...@@ -60,6 +60,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -60,6 +60,7 @@ import lombok.extern.slf4j.Slf4j;
@RestController @RestController
@RequestMapping("/api/jar") @RequestMapping("/api/jar")
public class JarController { public class JarController {
@Autowired @Autowired
private JarService jarService; private JarService jarService;
...@@ -132,11 +133,11 @@ public class JarController { ...@@ -132,11 +133,11 @@ public class JarController {
List<Task> allUDF = taskService.getAllUDF(); List<Task> allUDF = taskService.getAllUDF();
List<UDF> udfCodes = allUDF.stream().map(task -> { List<UDF> udfCodes = allUDF.stream().map(task -> {
return UDF.builder().code(task.getStatement()).className(task.getSavePointPath()) return UDF.builder().code(task.getStatement()).className(task.getSavePointPath())
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase())).build(); .functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase())).build();
}).collect(Collectors.toList()); }).collect(Collectors.toList());
Map<String, List<String>> resultMap = UDFUtil.buildJar(udfCodes); Map<String, List<String>> resultMap = UDFUtil.buildJar(udfCodes);
String msg = StrUtil.format("udf jar生成成功,jar文件在{};\n本次成功 class:{}。\n失败 class:{}" String msg = StrUtil.format("udf jar生成成功,jar文件在{};\n本次成功 class:{}。\n失败 class:{}", PathConstant.UDF_JAR_TMP_PATH,
, PathConstant.UDF_JAR_TMP_PATH, resultMap.get("success"), resultMap.get("failed")); resultMap.get("success"), resultMap.get("failed"));
return Result.succeed(resultMap, msg); return Result.succeed(resultMap, msg);
} }
} }
...@@ -59,6 +59,7 @@ public class StudioExecuteDTO extends AbstractStatementDTO { ...@@ -59,6 +59,7 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
private Integer jarId; private Integer jarId;
private String jobName; private String jobName;
private Integer taskId; private Integer taskId;
private Integer id;
private Integer maxRowNum; private Integer maxRowNum;
private Integer checkPoint; private Integer checkPoint;
private Integer parallelism; private Integer parallelism;
...@@ -87,4 +88,8 @@ public class StudioExecuteDTO extends AbstractStatementDTO { ...@@ -87,4 +88,8 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
clusterConfigurationId, jarId, taskId, jobName, isFragment(), statementSet, batchModel, clusterConfigurationId, jarId, taskId, jobName, isFragment(), statementSet, batchModel,
maxRowNum, checkPoint, parallelism, savePointStrategy, savePointPath, getVariables(), config); maxRowNum, checkPoint, parallelism, savePointStrategy, savePointPath, getVariables(), config);
} }
public Integer getTaskId() {
return taskId == null ? getId() : taskId;
}
} }
...@@ -19,8 +19,9 @@ ...@@ -19,8 +19,9 @@
package com.dlink.service; package com.dlink.service;
import com.dlink.executor.Executor;
import com.dlink.gateway.GatewayType; import com.dlink.gateway.GatewayType;
import com.dlink.model.UDFPath; import com.dlink.job.JobConfig;
/** /**
* @author ZackYoung * @author ZackYoung
...@@ -28,5 +29,13 @@ import com.dlink.model.UDFPath; ...@@ -28,5 +29,13 @@ import com.dlink.model.UDFPath;
*/ */
public interface UDFService { public interface UDFService {
UDFPath initUDF(String statement, GatewayType gatewayType); /**
*
* @param statement sql语句
* @param gatewayType flink 网关提交类型
* @param missionId 任务id
* @param executor flink执行器
* @param config job配置
*/
void initUDF(String statement, GatewayType gatewayType, Integer missionId,Executor executor, JobConfig config);
} }
...@@ -48,7 +48,6 @@ import com.dlink.model.Schema; ...@@ -48,7 +48,6 @@ import com.dlink.model.Schema;
import com.dlink.model.SystemConfiguration; import com.dlink.model.SystemConfiguration;
import com.dlink.model.Table; import com.dlink.model.Table;
import com.dlink.model.Task; import com.dlink.model.Task;
import com.dlink.model.UDFPath;
import com.dlink.process.context.ProcessContextHolder; import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity; import com.dlink.process.model.ProcessEntity;
import com.dlink.process.model.ProcessType; import com.dlink.process.model.ProcessType;
...@@ -181,12 +180,11 @@ public class StudioServiceImpl implements StudioService { ...@@ -181,12 +180,11 @@ public class StudioServiceImpl implements StudioService {
addFlinkSQLEnv(studioExecuteDTO); addFlinkSQLEnv(studioExecuteDTO);
JobConfig config = studioExecuteDTO.getJobConfig(); JobConfig config = studioExecuteDTO.getJobConfig();
buildSession(config); buildSession(config);
// To initialize java udf, but it only support local mode.
UDFPath udfPath = udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()));
config.setJarFiles(udfPath.getJarPaths());
config.setPyFiles(udfPath.getPyPaths());
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
// initUDF
udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()), studioExecuteDTO.getTaskId(), jobManager.getExecutor(), config);
JobResult jobResult = jobManager.executeSql(studioExecuteDTO.getStatement()); JobResult jobResult = jobManager.executeSql(studioExecuteDTO.getStatement());
RunTimeUtil.recovery(jobManager); RunTimeUtil.recovery(jobManager);
return jobResult; return jobResult;
...@@ -269,14 +267,13 @@ public class StudioServiceImpl implements StudioService { ...@@ -269,14 +267,13 @@ public class StudioServiceImpl implements StudioService {
config.buildLocal(); config.buildLocal();
buildSession(config); buildSession(config);
process.infoSuccess(); process.infoSuccess();
// To initialize java udf, but it has a bug in the product environment now.
UDFPath udfPath = udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()));
config.setJarFiles(udfPath.getJarPaths());
config.setPyFiles(udfPath.getPyPaths());
process.start(); process.start();
JobManager jobManager = JobManager.buildPlanMode(config); JobManager jobManager = JobManager.buildPlanMode(config);
// initUDF
udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()), studioExecuteDTO.getTaskId(), jobManager.getExecutor(), config);
List<SqlExplainResult> sqlExplainResults = List<SqlExplainResult> sqlExplainResults =
jobManager.explainSql(studioExecuteDTO.getStatement()).getSqlExplainResults(); jobManager.explainSql(studioExecuteDTO.getStatement()).getSqlExplainResults();
process.finish(); process.finish();
...@@ -316,10 +313,11 @@ public class StudioServiceImpl implements StudioService { ...@@ -316,10 +313,11 @@ public class StudioServiceImpl implements StudioService {
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to local. // If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to local.
config.buildLocal(); config.buildLocal();
buildSession(config); buildSession(config);
UDFPath udfPath = udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()));
config.setJarFiles(udfPath.getJarPaths());
config.setPyFiles(udfPath.getPyPaths());
JobManager jobManager = JobManager.buildPlanMode(config); JobManager jobManager = JobManager.buildPlanMode(config);
// initUDF
udfService.initUDF(studioExecuteDTO.getStatement(), GatewayType.get(config.getType()), studioExecuteDTO.getTaskId(), jobManager.getExecutor(), config);
String planJson = jobManager.getJobPlanJson(studioExecuteDTO.getStatement()); String planJson = jobManager.getJobPlanJson(studioExecuteDTO.getStatement());
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode(); ObjectNode objectNode = mapper.createObjectNode();
...@@ -571,12 +569,12 @@ public class StudioServiceImpl implements StudioService { ...@@ -571,12 +569,12 @@ public class StudioServiceImpl implements StudioService {
int i = 1; int i = 1;
for (Map<String, Object> item : rowData) { for (Map<String, Object> item : rowData) {
FlinkColumn column = FlinkColumn.build(i, FlinkColumn column = FlinkColumn.build(i,
item.get(FlinkQuery.columnName()).toString(), item.get(FlinkQuery.columnName()).toString(),
item.get(FlinkQuery.columnType()).toString(), item.get(FlinkQuery.columnType()).toString(),
item.get(FlinkQuery.columnKey()).toString(), item.get(FlinkQuery.columnKey()).toString(),
item.get(FlinkQuery.columnNull()).toString(), item.get(FlinkQuery.columnNull()).toString(),
item.get(FlinkQuery.columnExtras()).toString(), item.get(FlinkQuery.columnExtras()).toString(),
item.get(FlinkQuery.columnWatermark()).toString()); item.get(FlinkQuery.columnWatermark()).toString());
columns.add(column); columns.add(column);
i++; i++;
} }
......
...@@ -39,6 +39,8 @@ import com.dlink.dto.SqlDTO; ...@@ -39,6 +39,8 @@ import com.dlink.dto.SqlDTO;
import com.dlink.dto.TaskRollbackVersionDTO; import com.dlink.dto.TaskRollbackVersionDTO;
import com.dlink.dto.TaskVersionConfigureDTO; import com.dlink.dto.TaskVersionConfigureDTO;
import com.dlink.exception.BusException; import com.dlink.exception.BusException;
import com.dlink.function.compiler.CustomStringJavaCompiler;
import com.dlink.function.util.UDFUtil;
import com.dlink.gateway.GatewayType; import com.dlink.gateway.GatewayType;
import com.dlink.gateway.config.SavePointStrategy; import com.dlink.gateway.config.SavePointStrategy;
import com.dlink.gateway.config.SavePointType; import com.dlink.gateway.config.SavePointType;
...@@ -74,7 +76,6 @@ import com.dlink.model.Task; ...@@ -74,7 +76,6 @@ import com.dlink.model.Task;
import com.dlink.model.TaskOperatingSavepointSelect; import com.dlink.model.TaskOperatingSavepointSelect;
import com.dlink.model.TaskOperatingStatus; import com.dlink.model.TaskOperatingStatus;
import com.dlink.model.TaskVersion; import com.dlink.model.TaskVersion;
import com.dlink.model.UDFPath;
import com.dlink.model.UDFTemplate; import com.dlink.model.UDFTemplate;
import com.dlink.result.SqlExplainResult; import com.dlink.result.SqlExplainResult;
import com.dlink.result.TaskOperatingResult; import com.dlink.result.TaskOperatingResult;
...@@ -95,9 +96,7 @@ import com.dlink.service.TaskService; ...@@ -95,9 +96,7 @@ import com.dlink.service.TaskService;
import com.dlink.service.TaskVersionService; import com.dlink.service.TaskVersionService;
import com.dlink.service.UDFService; import com.dlink.service.UDFService;
import com.dlink.service.UDFTemplateService; import com.dlink.service.UDFTemplateService;
import com.dlink.utils.CustomStringJavaCompiler;
import com.dlink.utils.JSONUtil; import com.dlink.utils.JSONUtil;
import com.dlink.utils.UDFUtil;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
...@@ -198,7 +197,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -198,7 +197,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private String buildParas(Integer id) { private String buildParas(Integer id) {
return "--id " + id + " --driver " + driver + " --url " + url + " --username " + username + " --password " return "--id " + id + " --driver " + driver + " --url " + url + " --username " + username + " --password "
+ password; + password;
} }
@Override @Override
...@@ -207,13 +206,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -207,13 +206,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Asserts.checkNull(task, Tips.TASK_NOT_EXIST); Asserts.checkNull(task, Tips.TASK_NOT_EXIST);
if (Dialect.notFlinkSql(task.getDialect())) { if (Dialect.notFlinkSql(task.getDialect())) {
return executeCommonSql(SqlDTO.build(task.getStatement(), return executeCommonSql(SqlDTO.build(task.getStatement(),
task.getDatabaseId(), null)); task.getDatabaseId(), null));
} }
JobConfig config = buildJobConfig(task); JobConfig config = buildJobConfig(task);
UDFPath udfPath = udfService.initUDF(task.getStatement(), GatewayType.get(config.getType()));
config.setJarFiles(udfPath.getJarPaths());
config.setPyFiles(udfPath.getPyPaths());
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
// initUDF
udfService.initUDF(task.getStatement(), GatewayType.get(config.getType()), id, jobManager.getExecutor(),
config);
if (!config.isJarTask()) { if (!config.isJarTask()) {
return jobManager.executeSql(task.getStatement()); return jobManager.executeSql(task.getStatement());
} else { } else {
...@@ -228,7 +229,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -228,7 +229,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
task.setStep(JobLifeCycle.ONLINE.getValue()); task.setStep(JobLifeCycle.ONLINE.getValue());
if (Dialect.notFlinkSql(task.getDialect())) { if (Dialect.notFlinkSql(task.getDialect())) {
return executeCommonSql(SqlDTO.build(task.getStatement(), return executeCommonSql(SqlDTO.build(task.getStatement(),
task.getDatabaseId(), null)); task.getDatabaseId(), null));
} }
JobConfig config = buildJobConfig(task); JobConfig config = buildJobConfig(task);
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
...@@ -248,7 +249,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -248,7 +249,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
if (Dialect.notFlinkSql(task.getDialect())) { if (Dialect.notFlinkSql(task.getDialect())) {
return executeCommonSql(SqlDTO.build(task.getStatement(), return executeCommonSql(SqlDTO.build(task.getStatement(),
task.getDatabaseId(), null)); task.getDatabaseId(), null));
} }
if (StringUtils.isBlank(savePointPath)) { if (StringUtils.isBlank(savePointPath)) {
task.setSavePointStrategy(SavePointStrategy.LATEST.getValue()); task.setSavePointStrategy(SavePointStrategy.LATEST.getValue());
...@@ -373,13 +374,13 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -373,13 +374,13 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
UDFTemplate template = udfTemplateService.getById(config.get("templateId")); UDFTemplate template = udfTemplateService.getById(config.get("templateId"));
if (template != null) { if (template != null) {
String code = UDFUtil.templateParse(task.getDialect(), template.getTemplateCode(), String code = UDFUtil.templateParse(task.getDialect(), template.getTemplateCode(),
config.get("className")); config.get("className"));
task.setStatement(code); task.setStatement(code);
} }
} }
// to compiler udf // to compiler udf
if (Asserts.isNotNullString(task.getDialect()) && Dialect.JAVA.equalsVal(task.getDialect()) if (Asserts.isNotNullString(task.getDialect()) && Dialect.JAVA.equalsVal(task.getDialect())
&& Asserts.isNotNullString(task.getStatement())) { && Asserts.isNotNullString(task.getStatement())) {
CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(task.getStatement()); CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(task.getStatement());
task.setSavePointPath(compiler.getFullClassName()); task.setSavePointPath(compiler.getFullClassName());
} else if (Dialect.PYTHON.equalsVal(task.getDialect())) { } else if (Dialect.PYTHON.equalsVal(task.getDialect())) {
...@@ -394,8 +395,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -394,8 +395,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Task taskInfo = getById(task.getId()); Task taskInfo = getById(task.getId());
Assert.check(taskInfo); Assert.check(taskInfo);
if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep()) if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep()) || JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) { || JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) {
throw new BusException("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止修改!"); throw new BusException("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止修改!");
} }
task.setStep(JobLifeCycle.DEVELOP.getValue()); task.setStep(JobLifeCycle.DEVELOP.getValue());
...@@ -506,8 +507,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -506,8 +507,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public Task getUDFByClassName(String className) { public Task getUDFByClassName(String className) {
Task task = getOne( Task task = getOne(
new QueryWrapper<Task>().in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON).eq("enabled", 1) new QueryWrapper<Task>().in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON).eq("enabled", 1)
.eq("save_point_path", className)); .eq("save_point_path", className));
Assert.check(task); Assert.check(task);
task.setStatement(statementService.getById(task.getId()).getStatement()); task.setStatement(statementService.getById(task.getId()).getStatement());
return task; return task;
...@@ -516,8 +517,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -516,8 +517,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public List<Task> getAllUDF() { public List<Task> getAllUDF() {
List<Task> tasks = List<Task> tasks =
list(new QueryWrapper<Task>().in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON) list(new QueryWrapper<Task>().in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON)
.eq("enabled", 1).isNotNull("save_point_path")); .eq("enabled", 1).isNotNull("save_point_path"));
return tasks.stream().peek(task -> { return tasks.stream().peek(task -> {
Assert.check(task); Assert.check(task);
task.setStatement(statementService.getById(task.getId()).getStatement()); task.setStatement(statementService.getById(task.getId()).getStatement());
...@@ -554,7 +555,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -554,7 +555,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
List<TaskVersion> taskVersions = taskVersionService.getTaskVersionByTaskId(task.getId()); List<TaskVersion> taskVersions = taskVersionService.getTaskVersionByTaskId(task.getId());
List<Integer> versionIds = taskVersions.stream().map(TaskVersion::getVersionId).collect(Collectors.toList()); List<Integer> versionIds = taskVersions.stream().map(TaskVersion::getVersionId).collect(Collectors.toList());
Map<Integer, TaskVersion> versionMap = Map<Integer, TaskVersion> versionMap =
taskVersions.stream().collect(Collectors.toMap(TaskVersion::getVersionId, t -> t)); taskVersions.stream().collect(Collectors.toMap(TaskVersion::getVersionId, t -> t));
TaskVersion taskVersion = new TaskVersion(); TaskVersion taskVersion = new TaskVersion();
BeanUtil.copyProperties(task, taskVersion); BeanUtil.copyProperties(task, taskVersion);
...@@ -593,14 +594,14 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -593,14 +594,14 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Task taskInfo = getTaskInfoById(dto.getId()); Task taskInfo = getTaskInfoById(dto.getId());
if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep()) if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep()) || JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) { || JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) {
// throw new BusException("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止回滚!"); // throw new BusException("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止回滚!");
return Result.failed("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止回滚!"); return Result.failed("该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止回滚!");
} }
LambdaQueryWrapper<TaskVersion> queryWrapper = new LambdaQueryWrapper<TaskVersion>() LambdaQueryWrapper<TaskVersion> queryWrapper = new LambdaQueryWrapper<TaskVersion>()
.eq(TaskVersion::getTaskId, dto.getId()).eq(TaskVersion::getVersionId, dto.getVersionId()); .eq(TaskVersion::getTaskId, dto.getId()).eq(TaskVersion::getVersionId, dto.getVersionId());
TaskVersion taskVersion = taskVersionService.getOne(queryWrapper); TaskVersion taskVersion = taskVersionService.getOne(queryWrapper);
...@@ -747,7 +748,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -747,7 +748,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) { if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
Map<String, Object> gatewayConfig = Map<String, Object> gatewayConfig =
clusterConfigurationService.getGatewayConfig(cluster.getClusterConfigurationId()); clusterConfigurationService.getGatewayConfig(cluster.getClusterConfigurationId());
jobConfig.buildGatewayConfig(gatewayConfig); jobConfig.buildGatewayConfig(gatewayConfig);
jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName()); jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName());
useGateway = true; useGateway = true;
...@@ -783,7 +784,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -783,7 +784,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private JobConfig buildJobConfig(Task task) { private JobConfig buildJobConfig(Task task) {
boolean isJarTask = Dialect.FLINKJAR.equalsVal(task.getDialect()) boolean isJarTask = Dialect.FLINKJAR.equalsVal(task.getDialect())
|| Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect()); || Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect());
if (!isJarTask && Asserts.isNotNull(task.getFragment()) ? task.getFragment() : false) { if (!isJarTask && Asserts.isNotNull(task.getFragment()) ? task.getFragment() : false) {
String flinkWithSql = dataBaseService.getEnabledFlinkWithSql(); String flinkWithSql = dataBaseService.getEnabledFlinkWithSql();
if (Asserts.isNotNullString(flinkWithSql)) { if (Asserts.isNotNullString(flinkWithSql)) {
...@@ -803,20 +804,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -803,20 +804,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
// support custom K8s app submit, rather than clusterConfiguration // support custom K8s app submit, rather than clusterConfiguration
else if (Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect()) else if (Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect())
&& GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) { && GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) {
Map<String, Object> gatewayConfig = JSONUtil.toMap(task.getStatement(), String.class, Object.class); Map<String, Object> gatewayConfig = JSONUtil.toMap(task.getStatement(), String.class, Object.class);
config.buildGatewayConfig(gatewayConfig); config.buildGatewayConfig(gatewayConfig);
} else { } else {
Map<String, Object> gatewayConfig = Map<String, Object> gatewayConfig =
clusterConfigurationService.getGatewayConfig(task.getClusterConfigurationId()); clusterConfigurationService.getGatewayConfig(task.getClusterConfigurationId());
// submit application type with clusterConfiguration // submit application type with clusterConfiguration
if (GatewayType.YARN_APPLICATION.equalsValue(config.getType()) if (GatewayType.YARN_APPLICATION.equalsValue(config.getType())
|| GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) { || GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) {
if (!isJarTask) { if (!isJarTask) {
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances(); SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
gatewayConfig.put("userJarPath", systemConfiguration.getSqlSubmitJarPath()); gatewayConfig.put("userJarPath", systemConfiguration.getSqlSubmitJarPath());
gatewayConfig.put("userJarParas", gatewayConfig.put("userJarParas",
systemConfiguration.getSqlSubmitJarParas() + buildParas(config.getTaskId())); systemConfiguration.getSqlSubmitJarParas() + buildParas(config.getTaskId()));
gatewayConfig.put("userJarMainAppClass", systemConfiguration.getSqlSubmitJarMainAppClass()); gatewayConfig.put("userJarMainAppClass", systemConfiguration.getSqlSubmitJarMainAppClass());
} else { } else {
Jar jar = jarService.getById(task.getJarId()); Jar jar = jarService.getById(task.getJarId());
...@@ -874,7 +875,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -874,7 +875,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
history.setConfig(JSONUtil.parseObject(history.getConfigJson())); history.setConfig(JSONUtil.parseObject(history.getConfigJson()));
if (Asserts.isNotNull(history) && Asserts.isNotNull(history.getClusterConfigurationId())) { if (Asserts.isNotNull(history) && Asserts.isNotNull(history.getClusterConfigurationId())) {
jobInfoDetail.setClusterConfiguration( jobInfoDetail.setClusterConfiguration(
clusterConfigurationService.getClusterConfigById(history.getClusterConfigurationId())); clusterConfigurationService.getClusterConfigById(history.getClusterConfigurationId()));
} }
jobInfoDetail.setHistory(history); jobInfoDetail.setHistory(history);
jobInfoDetail.setJobHistory(jobHistoryService.getJobHistory(id)); jobInfoDetail.setJobHistory(jobHistoryService.getJobHistory(id));
...@@ -884,12 +885,12 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -884,12 +885,12 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
return jobInfoDetail.getInstance(); return jobInfoDetail.getInstance();
} }
JobHistory jobHistoryJson = JobHistory jobHistoryJson =
jobHistoryService.refreshJobHistory(id, jobInfoDetail.getCluster().getJobManagerHost(), jobHistoryService.refreshJobHistory(id, jobInfoDetail.getCluster().getJobManagerHost(),
jobInfoDetail.getInstance().getJid(), jobInfoDetail.isNeedSave()); jobInfoDetail.getInstance().getJid(), jobInfoDetail.isNeedSave());
JobHistory jobHistory = jobHistoryService.getJobHistoryInfo(jobHistoryJson); JobHistory jobHistory = jobHistoryService.getJobHistoryInfo(jobHistoryJson);
jobInfoDetail.setJobHistory(jobHistory); jobInfoDetail.setJobHistory(jobHistory);
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus()) if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus())
&& (Asserts.isNull(jobHistory.getJob()) || jobHistory.isError())) { && (Asserts.isNull(jobHistory.getJob()) || jobHistory.isError())) {
return jobInfoDetail.getInstance(); return jobInfoDetail.getInstance();
} }
String status = jobInfoDetail.getInstance().getStatus(); String status = jobInfoDetail.getInstance().getStatus();
...@@ -898,12 +899,12 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -898,12 +899,12 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
jobInfoDetail.getInstance().setStatus(JobStatus.UNKNOWN.getValue()); jobInfoDetail.getInstance().setStatus(JobStatus.UNKNOWN.getValue());
} else { } else {
jobInfoDetail.getInstance().setDuration( jobInfoDetail.getInstance().setDuration(
jobInfoDetail.getJobHistory().getJob().get(FlinkRestResultConstant.JOB_DURATION).asLong() / 1000); jobInfoDetail.getJobHistory().getJob().get(FlinkRestResultConstant.JOB_DURATION).asLong() / 1000);
jobInfoDetail.getInstance() jobInfoDetail.getInstance()
.setStatus(jobInfoDetail.getJobHistory().getJob().get(FlinkRestResultConstant.JOB_STATE).asText()); .setStatus(jobInfoDetail.getJobHistory().getJob().get(FlinkRestResultConstant.JOB_STATE).asText());
} }
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus()) if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus())
&& !status.equals(jobInfoDetail.getInstance().getStatus())) { && !status.equals(jobInfoDetail.getInstance().getStatus())) {
jobStatusChanged = true; jobStatusChanged = true;
jobInfoDetail.getInstance().setFinishTime(LocalDateTime.now()); jobInfoDetail.getInstance().setFinishTime(LocalDateTime.now());
// handleJobDone(jobInfoDetail.getInstance()); // handleJobDone(jobInfoDetail.getInstance());
...@@ -920,7 +921,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -920,7 +921,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private boolean inRefreshPlan(JobInstance jobInstance) { private boolean inRefreshPlan(JobInstance jobInstance) {
if ((!JobStatus.isDone(jobInstance.getStatus())) || (Asserts.isNotNull(jobInstance.getFinishTime()) if ((!JobStatus.isDone(jobInstance.getStatus())) || (Asserts.isNotNull(jobInstance.getFinishTime())
&& Duration.between(jobInstance.getFinishTime(), LocalDateTime.now()).toMinutes() < 1)) { && Duration.between(jobInstance.getFinishTime(), LocalDateTime.now()).toMinutes() < 1)) {
return true; return true;
} else { } else {
return false; return false;
...@@ -967,9 +968,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -967,9 +968,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
// clusterConfigurationName // clusterConfigurationName
if (Asserts.isNotNull(task.getClusterConfigurationId())) { if (Asserts.isNotNull(task.getClusterConfigurationId())) {
ClusterConfiguration clusterConfiguration = ClusterConfiguration clusterConfiguration =
clusterConfigurationService.getById(task.getClusterConfigurationId()); clusterConfigurationService.getById(task.getClusterConfigurationId());
((ObjectNode) jsonNode).put("clusterConfigurationName", ((ObjectNode) jsonNode).put("clusterConfigurationName",
Asserts.isNotNull(clusterConfiguration) ? clusterConfiguration.getName() : null); Asserts.isNotNull(clusterConfiguration) ? clusterConfiguration.getName() : null);
} }
// databaseName // databaseName
if (Asserts.isNotNull(task.getDatabaseId())) { if (Asserts.isNotNull(task.getDatabaseId())) {
...@@ -1045,15 +1046,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1045,15 +1046,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
if (Asserts.isNotNull(task.getClusterConfigurationName())) { if (Asserts.isNotNull(task.getClusterConfigurationName())) {
ClusterConfiguration clusterConfiguration = clusterConfigurationService ClusterConfiguration clusterConfiguration = clusterConfigurationService
.getOne(new QueryWrapper<ClusterConfiguration>().eq("name", .getOne(new QueryWrapper<ClusterConfiguration>().eq("name",
task.getClusterConfigurationName())); task.getClusterConfigurationName()));
if (Asserts.isNotNull(clusterConfiguration)) { if (Asserts.isNotNull(clusterConfiguration)) {
task.setClusterConfigurationId(clusterConfiguration.getId()); task.setClusterConfigurationId(clusterConfiguration.getId());
} }
} }
if (Asserts.isNotNull(task.getDatabaseName())) { if (Asserts.isNotNull(task.getDatabaseName())) {
DataBase dataBase = DataBase dataBase =
dataBaseService.getOne(new QueryWrapper<DataBase>().eq("name", task.getDatabaseName())); dataBaseService.getOne(new QueryWrapper<DataBase>().eq("name", task.getDatabaseName()));
if (Asserts.isNotNull(dataBase)) { if (Asserts.isNotNull(dataBase)) {
task.setDatabaseId(dataBase.getId()); task.setDatabaseId(dataBase.getId());
} }
...@@ -1070,7 +1071,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1070,7 +1071,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
*/ */
if (Asserts.isNotNull(task.getAlertGroupName())) { if (Asserts.isNotNull(task.getAlertGroupName())) {
AlertGroup alertGroup = AlertGroup alertGroup =
alertGroupService.getOne(new QueryWrapper<AlertGroup>().eq("name", task.getAlertGroupName())); alertGroupService.getOne(new QueryWrapper<AlertGroup>().eq("name", task.getAlertGroupName()));
if (Asserts.isNotNull(alertGroup)) { if (Asserts.isNotNull(alertGroup)) {
task.setAlertGroupId(alertGroup.getId()); task.setAlertGroupId(alertGroup.getId());
} }
...@@ -1106,7 +1107,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1106,7 +1107,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
return Result.failed("一共" + jsonNodes.size() + "个作业,全部导入失败"); return Result.failed("一共" + jsonNodes.size() + "个作业,全部导入失败");
} else if (errorNumber > 0) { } else if (errorNumber > 0) {
return Result.failed("一共" + jsonNodes.size() + "个作业,其中成功导入" + (jsonNode.size() - errorNumber) + "个,失败" return Result.failed("一共" + jsonNodes.size() + "个作业,其中成功导入" + (jsonNode.size() - errorNumber) + "个,失败"
+ errorNumber + "个"); + errorNumber + "个");
} }
return Result.succeed("成功导入" + jsonNodes.size() + "个作业"); return Result.succeed("成功导入" + jsonNodes.size() + "个作业");
} }
...@@ -1157,7 +1158,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1157,7 +1158,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
long minutes = ChronoUnit.MINUTES.between(startTime, endTime); long minutes = ChronoUnit.MINUTES.between(startTime, endTime);
long seconds = ChronoUnit.SECONDS.between(startTime, endTime); long seconds = ChronoUnit.SECONDS.between(startTime, endTime);
String duration = days + "天 " + (hours - (days * 24)) + "小时 " + (minutes - (hours * 60)) + "分 " String duration = days + "天 " + (hours - (days * 24)) + "小时 " + (minutes - (hours * 60)) + "分 "
+ (seconds - (minutes * 60)) + "秒"; + (seconds - (minutes * 60)) + "秒";
return duration; return duration;
} }
...@@ -1237,7 +1238,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1237,7 +1238,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private void sendAlert(AlertInstance alertInstance, JobInstance jobInstance, Task task, AlertMsg alertMsg) { private void sendAlert(AlertInstance alertInstance, JobInstance jobInstance, Task task, AlertMsg alertMsg) {
AlertConfig alertConfig = AlertConfig.build(alertInstance.getName(), alertInstance.getType(), AlertConfig alertConfig = AlertConfig.build(alertInstance.getName(), alertInstance.getType(),
JSONUtil.toMap(alertInstance.getParams())); JSONUtil.toMap(alertInstance.getParams()));
Alert alert = Alert.build(alertConfig); Alert alert = Alert.build(alertConfig);
String title = "任务【" + task.getAlias() + "】:" + jobInstance.getStatus(); String title = "任务【" + task.getAlias() + "】:" + jobInstance.getStatus();
String content = alertMsg.toString(); String content = alertMsg.toString();
...@@ -1256,10 +1257,10 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1256,10 +1257,10 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public Result queryAllCatalogue() { public Result queryAllCatalogue() {
final LambdaQueryWrapper<Catalogue> queryWrapper = new LambdaQueryWrapper<Catalogue>() final LambdaQueryWrapper<Catalogue> queryWrapper = new LambdaQueryWrapper<Catalogue>()
.select(Catalogue::getId, Catalogue::getName, Catalogue::getParentId) .select(Catalogue::getId, Catalogue::getName, Catalogue::getParentId)
.eq(Catalogue::getIsLeaf, 0) .eq(Catalogue::getIsLeaf, 0)
.eq(Catalogue::getEnabled, 1) .eq(Catalogue::getEnabled, 1)
.isNull(Catalogue::getTaskId); .isNull(Catalogue::getTaskId);
final List<Catalogue> catalogueList = catalogueService.list(queryWrapper); final List<Catalogue> catalogueList = catalogueService.list(queryWrapper);
return Result.succeed(TreeUtil.build(dealWithCatalogue(catalogueList), -1).get(0)); return Result.succeed(TreeUtil.build(dealWithCatalogue(catalogueList), -1).get(0));
} }
...@@ -1285,7 +1286,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1285,7 +1286,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
public Result<List<Task>> queryOnLineTaskByDoneStatus(List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses, public Result<List<Task>> queryOnLineTaskByDoneStatus(List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses,
boolean includeNull, Integer catalogueId) { boolean includeNull, Integer catalogueId) {
final Tree<Integer> node = ((Tree<Integer>) queryAllCatalogue().getDatas()) final Tree<Integer> node = ((Tree<Integer>) queryAllCatalogue().getDatas())
.getNode(Objects.isNull(catalogueId) ? 0 : catalogueId); .getNode(Objects.isNull(catalogueId) ? 0 : catalogueId);
final List<Integer> parentIds = new ArrayList<>(0); final List<Integer> parentIds = new ArrayList<>(0);
parentIds.add(node.getId()); parentIds.add(node.getId());
childrenNodeParse(node, parentIds); childrenNodeParse(node, parentIds);
...@@ -1296,8 +1297,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1296,8 +1297,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private List<Task> getTasks(List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses, boolean includeNull, private List<Task> getTasks(List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses, boolean includeNull,
List<Integer> parentIds) { List<Integer> parentIds) {
return this.baseMapper.queryOnLineTaskByDoneStatus(parentIds, return this.baseMapper.queryOnLineTaskByDoneStatus(parentIds,
jobLifeCycle.stream().filter(Objects::nonNull).map(JobLifeCycle::getValue).collect(Collectors.toList()), jobLifeCycle.stream().filter(Objects::nonNull).map(JobLifeCycle::getValue).collect(Collectors.toList()),
includeNull, jobStatuses.stream().map(JobStatus::name).collect(Collectors.toList())); includeNull, jobStatuses.stream().map(JobStatus::name).collect(Collectors.toList()));
} }
private void childrenNodeParse(Tree<Integer> node, List<Integer> parentIds) { private void childrenNodeParse(Tree<Integer> node, List<Integer> parentIds) {
...@@ -1317,7 +1318,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1317,7 +1318,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public void selectSavepointOnLineTask(TaskOperatingResult taskOperatingResult) { public void selectSavepointOnLineTask(TaskOperatingResult taskOperatingResult) {
final JobInstance jobInstanceByTaskId = final JobInstance jobInstanceByTaskId =
jobInstanceService.getJobInstanceByTaskId(taskOperatingResult.getTask().getId()); jobInstanceService.getJobInstanceByTaskId(taskOperatingResult.getTask().getId());
if (jobInstanceByTaskId == null) { if (jobInstanceByTaskId == null) {
startGoingLiveTask(taskOperatingResult, null); startGoingLiveTask(taskOperatingResult, null);
return; return;
...@@ -1336,8 +1337,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1336,8 +1337,8 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private void findTheConditionSavePointToOnline(TaskOperatingResult taskOperatingResult, private void findTheConditionSavePointToOnline(TaskOperatingResult taskOperatingResult,
JobInstance jobInstanceByTaskId) { JobInstance jobInstanceByTaskId) {
final LambdaQueryWrapper<JobHistory> queryWrapper = new LambdaQueryWrapper<JobHistory>() final LambdaQueryWrapper<JobHistory> queryWrapper = new LambdaQueryWrapper<JobHistory>()
.select(JobHistory::getId, JobHistory::getCheckpointsJson) .select(JobHistory::getId, JobHistory::getCheckpointsJson)
.eq(JobHistory::getId, jobInstanceByTaskId.getId()); .eq(JobHistory::getId, jobInstanceByTaskId.getId());
final JobHistory jobHistory = jobHistoryService.getOne(queryWrapper); final JobHistory jobHistory = jobHistoryService.getOne(queryWrapper);
if (jobHistory != null && StringUtils.isNotBlank(jobHistory.getCheckpointsJson())) { if (jobHistory != null && StringUtils.isNotBlank(jobHistory.getCheckpointsJson())) {
final ObjectNode jsonNodes = JSONUtil.parseObject(jobHistory.getCheckpointsJson()); final ObjectNode jsonNodes = JSONUtil.parseObject(jobHistory.getCheckpointsJson());
......
...@@ -19,21 +19,20 @@ ...@@ -19,21 +19,20 @@
package com.dlink.service.impl; package com.dlink.service.impl;
import com.dlink.constant.PathConstant;
import com.dlink.exception.BusException; import com.dlink.exception.BusException;
import com.dlink.executor.Executor;
import com.dlink.function.FunctionFactory;
import com.dlink.function.data.model.Env;
import com.dlink.function.data.model.UDF;
import com.dlink.function.data.model.UDFPath;
import com.dlink.gateway.GatewayType; import com.dlink.gateway.GatewayType;
import com.dlink.model.Task; import com.dlink.job.JobConfig;
import com.dlink.model.UDFPath;
import com.dlink.process.context.ProcessContextHolder; import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity; import com.dlink.process.model.ProcessEntity;
import com.dlink.service.TaskService; import com.dlink.service.TaskService;
import com.dlink.service.UDFService; import com.dlink.service.UDFService;
import com.dlink.udf.UDF; import com.dlink.utils.UDFUtils;
import com.dlink.utils.UDFUtil;
import org.apache.flink.table.catalog.FunctionLanguage;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -42,8 +41,8 @@ import javax.annotation.Resource; ...@@ -42,8 +41,8 @@ import javax.annotation.Resource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
/** /**
* @author ZackYoung * @author ZackYoung
...@@ -52,27 +51,35 @@ import cn.hutool.core.map.MapUtil; ...@@ -52,27 +51,35 @@ import cn.hutool.core.map.MapUtil;
@Service @Service
public class UDFServiceImpl implements UDFService { public class UDFServiceImpl implements UDFService {
private static final String YARN = "YARN";
private static final String APPLICATION = "APPLICATION";
/** /**
* 网关类型 map * 网关类型 map
* 快速获取 session 与 application 等类型,为了减少判断 * 快速获取 session 与 application 等类型,为了减少判断
*/ */
private static final Map<String, List<GatewayType>> GATEWAY_TYPE_MAP = MapUtil private static final Map<String, List<GatewayType>> GATEWAY_TYPE_MAP = MapUtil
.builder("session", .builder("session",
Arrays.asList(GatewayType.YARN_SESSION, GatewayType.KUBERNETES_SESSION, GatewayType.STANDALONE)) Arrays.asList(GatewayType.YARN_SESSION, GatewayType.KUBERNETES_SESSION, GatewayType.STANDALONE))
.build(); .put(YARN,
Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.YARN_PER_JOB))
.put(APPLICATION,
Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.KUBERNETES_APPLICATION))
.build();
@Resource @Resource
TaskService taskService; TaskService taskService;
/** /**
* init udf * @param statement sql语句
* * @param gatewayType flink 网关提交类型
* @param statement sql 语句 * @param missionId 任务id
* @param gatewayType flink gateway类型 * @param executor flink执行器
* @return {@link UDFPath} * @param config job配置
*/ */
@Override @Override
public UDFPath initUDF(String statement, GatewayType gatewayType) { public void initUDF(String statement, GatewayType gatewayType, Integer missionId, Executor executor,
JobConfig config) {
if (gatewayType == GatewayType.KUBERNETES_APPLICATION) { if (gatewayType == GatewayType.KUBERNETES_APPLICATION) {
throw new BusException("udf 暂不支持k8s application"); throw new BusException("udf 暂不支持k8s application");
} }
...@@ -80,40 +87,17 @@ public class UDFServiceImpl implements UDFService { ...@@ -80,40 +87,17 @@ public class UDFServiceImpl implements UDFService {
ProcessEntity process = ProcessContextHolder.getProcess(); ProcessEntity process = ProcessContextHolder.getProcess();
process.info("Initializing Flink UDF...Start"); process.info("Initializing Flink UDF...Start");
List<UDF> udfClassList = UDFUtil.getUDF(statement); List<UDF> udf = UDFUtils.getUDF(statement);
List<UDF> javaUdf = new ArrayList<>(); UDFPath udfPath = FunctionFactory.initUDF(udf, missionId, executor);
List<UDF> pythonUdf = new ArrayList<>();
udfClassList.forEach(udf -> {
Task task = taskService.getUDFByClassName(udf.getClassName());
udf.setCode(task.getStatement());
if (udf.getFunctionLanguage() == FunctionLanguage.PYTHON) {
pythonUdf.add(udf);
} else {
udf.setFunctionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()));
javaUdf.add(udf);
}
});
String[] javaUDFPath = initJavaUDF(javaUdf);
String[] pythonUDFPath = initPythonUDF(pythonUdf);
process.info("Initializing Flink UDF...Finish");
return UDFPath.builder().jarPaths(javaUDFPath).pyPaths(pythonUDFPath).build();
}
private static String[] initPythonUDF(List<UDF> udfList) { executor.initUDF(udfPath.getJarPaths());
return udfList == null || udfList.isEmpty() ? new String[0] : new String[] {UDFUtil.buildPy(udfList)}; executor.initPyUDF(Env.getPath(), udfPath.getPyPaths());
}
private static String[] initJavaUDF(List<UDF> udfList) { //
Opt<String> udfJarPath = Opt.empty(); if (GATEWAY_TYPE_MAP.get(YARN).contains(gatewayType)) {
if (!udfList.isEmpty()) { config.getGatewayConfig().setJarPaths(ArrayUtil.append(udfPath.getJarPaths(), udfPath.getPyPaths()));
udfJarPath = Opt.ofBlankAble(UDFUtil.getUdfFileAndBuildJar(udfList));
} }
if (udfJarPath.isPresent()) { process.info("Initializing Flink UDF...Finish");
return new String[] {PathConstant.UDF_PATH + udfJarPath.get()};
} else {
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 com.dlink.utils;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
import com.dlink.model.Task;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import com.dlink.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.table.catalog.FunctionLanguage;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.extra.spring.SpringUtil;
/**
* @author ZackYoung
* @since 0.6.8
*/
public class UDFUtils extends UDFUtil {
private static final String FUNCTION_SQL_REGEX =
"create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?;";
public static List<UDF> getUDF(String statement) {
ProcessEntity process = ProcessContextHolder.getProcess();
process.info("Parse UDF class name:");
Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE);
List<String> udfSqlList = ReUtil.findAllGroup0(pattern, statement);
List<UDF> udfList = udfSqlList.stream().map(sql -> {
List<String> groups = ReUtil.getAllGroups(pattern, sql);
String udfName = groups.get(1);
String className = groups.get(2);
Task task = SpringUtil.getBean(TaskService.class).getUDFByClassName(className);
String code = task.getStatement();
return UDF.builder()
.name(udfName)
.className(className)
.code(code)
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()))
.build();
}).collect(Collectors.toList());
List<String> classNameList = udfList.stream().map(UDF::getClassName).collect(Collectors.toList());
process.info(StringUtils.join(",", classNameList));
process.info(CharSequenceUtil.format("A total of {} UDF have been Parsed.", classNameList.size()));
return udfList;
}
}
...@@ -100,3 +100,7 @@ dinky: ...@@ -100,3 +100,7 @@ dinky:
project-name: Dinky project-name: Dinky
# Dolphinscheduler DinkyTask Address # Dolphinscheduler DinkyTask Address
address: http://127.0.0.1:8888 address: http://127.0.0.1:8888
# python udf 需要用到的 python 执行环境
python:
path: python
\ No newline at end of file
...@@ -84,11 +84,6 @@ ...@@ -84,11 +84,6 @@
<artifactId>dlink-flink-${dlink.flink.version}</artifactId> <artifactId>dlink-flink-${dlink.flink.version}</artifactId>
<scope>${scope.runtime}</scope> <scope>${scope.runtime}</scope>
</dependency> </dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-function</artifactId>
<scope>${scope.runtime}</scope>
</dependency>
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-gateway</artifactId> <artifactId>dlink-gateway</artifactId>
......
...@@ -38,8 +38,6 @@ import com.dlink.interceptor.FlinkInterceptor; ...@@ -38,8 +38,6 @@ import com.dlink.interceptor.FlinkInterceptor;
import com.dlink.interceptor.FlinkInterceptorResult; import com.dlink.interceptor.FlinkInterceptorResult;
import com.dlink.model.SystemConfiguration; import com.dlink.model.SystemConfiguration;
import com.dlink.parser.SqlType; import com.dlink.parser.SqlType;
import com.dlink.pool.ClassEntity;
import com.dlink.pool.ClassPool;
import com.dlink.process.context.ProcessContextHolder; import com.dlink.process.context.ProcessContextHolder;
import com.dlink.result.ErrorResult; import com.dlink.result.ErrorResult;
import com.dlink.result.ExplainResult; import com.dlink.result.ExplainResult;
...@@ -55,13 +53,12 @@ import com.dlink.session.SessionPool; ...@@ -55,13 +53,12 @@ import com.dlink.session.SessionPool;
import com.dlink.trans.Operations; import com.dlink.trans.Operations;
import com.dlink.utils.LogUtil; import com.dlink.utils.LogUtil;
import com.dlink.utils.SqlUtil; import com.dlink.utils.SqlUtil;
import com.dlink.utils.UDFUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.DeploymentOptions; import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.PipelineOptions; import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.core.execution.JobClient; import org.apache.flink.core.execution.JobClient;
import org.apache.flink.optimizer.CompilerException;
import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions; import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings; import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
...@@ -81,8 +78,6 @@ import org.slf4j.LoggerFactory; ...@@ -81,8 +78,6 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.util.ArrayUtil;
/** /**
* JobManager * JobManager
* *
...@@ -98,6 +93,7 @@ public class JobManager { ...@@ -98,6 +93,7 @@ public class JobManager {
private ExecutorSetting executorSetting; private ExecutorSetting executorSetting;
private JobConfig config; private JobConfig config;
private Executor executor; private Executor executor;
private Configuration configuration;
private boolean useGateway = false; private boolean useGateway = false;
private boolean isPlanMode = false; private boolean isPlanMode = false;
private boolean useStatementSet = false; private boolean useStatementSet = false;
...@@ -162,12 +158,6 @@ public class JobManager { ...@@ -162,12 +158,6 @@ public class JobManager {
initGatewayConfig(config); initGatewayConfig(config);
JobManager manager = new JobManager(config); JobManager manager = new JobManager(config);
manager.init(); manager.init();
manager.executor.initUDF(config.getJarFiles());
manager.executor.initPyUDF(config.getPyFiles());
if (config.getGatewayConfig() != null) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(config.getJarFiles(),config.getPyFiles()));
}
return manager; return manager;
} }
...@@ -175,7 +165,6 @@ public class JobManager { ...@@ -175,7 +165,6 @@ public class JobManager {
JobManager manager = new JobManager(config); JobManager manager = new JobManager(config);
manager.setPlanMode(true); manager.setPlanMode(true);
manager.init(); manager.init();
manager.executor.initUDF(config.getJarFiles());
ProcessContextHolder.getProcess().info("Build Flink plan mode success."); ProcessContextHolder.getProcess().info("Build Flink plan mode success.");
return manager; return manager;
} }
...@@ -640,22 +629,7 @@ public class JobManager { ...@@ -640,22 +629,7 @@ public class JobManager {
return sb.toString(); return sb.toString();
} }
public static void initUDF(String className, String code) { public Executor getExecutor() {
if (ClassPool.exist(ClassEntity.build(className, code))) { return executor;
UDFUtil.initClassLoader(className);
} else {
UDFUtil.buildClass(code);
}
}
public static void initMustSuccessUDF(String className, String code) {
if (ClassPool.exist(ClassEntity.build(className, code))) {
UDFUtil.initClassLoader(className);
} else {
// 如果编译失败,返回异常。因为必须用到的函数,也必须编译成功
if (!UDFUtil.buildClass(code)) {
throw new CompilerException(String.format("class:%s 编译异常,请检查代码", className));
}
}
} }
} }
...@@ -54,11 +54,6 @@ ...@@ -54,11 +54,6 @@
<artifactId>dlink-flink-${dlink.flink.version}</artifactId> <artifactId>dlink-flink-${dlink.flink.version}</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-function</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-metadata-base</artifactId> <artifactId>dlink-metadata-base</artifactId>
......
...@@ -254,13 +254,14 @@ public abstract class Executor { ...@@ -254,13 +254,14 @@ public abstract class Executor {
JarUtils.getJarFiles(udfFilePath).forEach(Executor::loadJar); JarUtils.getJarFiles(udfFilePath).forEach(Executor::loadJar);
} }
public void initPyUDF(String... udfPyFilePath) { public void initPyUDF(String executable,String... udfPyFilePath) {
if (udfPyFilePath == null || udfPyFilePath.length == 0) { if (udfPyFilePath == null || udfPyFilePath.length == 0) {
return; return;
} }
Map<String, String> config = executorSetting.getConfig(); Map<String, String> config = executorSetting.getConfig();
if (Asserts.isNotNull(config)) { if (Asserts.isNotNull(config)) {
config.put(PythonOptions.PYTHON_FILES.key(), String.join(",", udfPyFilePath)); config.put(PythonOptions.PYTHON_FILES.key(), String.join(",", udfPyFilePath));
config.put(PythonOptions.PYTHON_CLIENT_EXECUTABLE.key(), executable);
} }
update(executorSetting); update(executorSetting);
} }
......
...@@ -31,12 +31,27 @@ ...@@ -31,12 +31,27 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-client-1.13</artifactId> <artifactId>dlink-client-${dlink.flink.version}</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.dlink</groupId> <groupId>com.dlink</groupId>
<artifactId>dlink-flink-1.13</artifactId> <artifactId>dlink-flink-${dlink.flink.version}</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.dlink</groupId>
<artifactId>dlink-executor</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
</dependencies> </dependencies>
......
/*
*
* 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 com.dlink.function;
import com.dlink.executor.Executor;
import com.dlink.function.compiler.FunctionCompiler;
import com.dlink.function.compiler.FunctionPackage;
import com.dlink.function.data.model.UDF;
import com.dlink.function.data.model.UDFPath;
import java.util.List;
/**
* @author ZackYoung
* @since 0.6.8
*/
public class FunctionFactory {
/**
* udf编译 & 打包 初始化
* @param udfClassList udf列表
* @param missionId 当前任务id
* @param executor flink执行器
* @return 打包过后的路径
*/
public static UDFPath initUDF(List<UDF> udfClassList, Integer missionId, Executor executor) {
// 编译
FunctionCompiler.getCompiler(udfClassList, executor.getTableConfig().getConfiguration(), missionId);
// 打包
return FunctionPackage.bale(udfClassList, missionId);
}
}
...@@ -17,12 +17,12 @@ ...@@ -17,12 +17,12 @@
* *
*/ */
package com.dlink.catalog.function; package com.dlink.function.catalog;
import com.dlink.constant.FlinkFunctionConstant; import com.dlink.function.constant.FlinkFunctionConstant;
import com.dlink.ud.udf.GetKey; import com.dlink.function.udf.GetKey;
import com.dlink.ud.udtaf.RowsToMap; import com.dlink.function.udtaf.RowsToMap;
import com.dlink.ud.udtaf.Top2; import com.dlink.function.udtaf.Top2;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
...@@ -37,6 +37,7 @@ import java.util.Map; ...@@ -37,6 +37,7 @@ import java.util.Map;
public class FunctionManager { public class FunctionManager {
private static Map<String, UDFunction> functions = new HashMap<String, UDFunction>() { private static Map<String, UDFunction> functions = new HashMap<String, UDFunction>() {
{ {
put(FlinkFunctionConstant.GET_KEY, put(FlinkFunctionConstant.GET_KEY,
new UDFunction(FlinkFunctionConstant.GET_KEY, new UDFunction(FlinkFunctionConstant.GET_KEY,
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.catalog.function; package com.dlink.function.catalog;
import org.apache.flink.table.functions.FunctionDefinition; import org.apache.flink.table.functions.FunctionDefinition;
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.utils; package com.dlink.function.compiler;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
...@@ -54,16 +54,17 @@ import cn.hutool.core.util.StrUtil; ...@@ -54,16 +54,17 @@ import cn.hutool.core.util.StrUtil;
* @since 2021/12/28 22:46 * @since 2021/12/28 22:46
*/ */
public class CustomStringJavaCompiler { public class CustomStringJavaCompiler {
//类全名
// 类全名
private String fullClassName; private String fullClassName;
private String sourceCode; private String sourceCode;
//存放编译之后的字节码(key:类全名,value:编译之后输出的字节码) // 存放编译之后的字节码(key:类全名,value:编译之后输出的字节码)
private Map<String, ByteJavaFileObject> javaFileObjectMap = new ConcurrentHashMap<>(); private Map<String, ByteJavaFileObject> javaFileObjectMap = new ConcurrentHashMap<>();
//获取java的编译器 // 获取java的编译器
private JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); private JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//存放编译过程中输出的信息 // 存放编译过程中输出的信息
private DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>(); private DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<>();
//编译耗时(单位ms) // 编译耗时(单位ms)
private long compilerTakeTime; private long compilerTakeTime;
public String getFullClassName() { public String getFullClassName() {
...@@ -86,14 +87,15 @@ public class CustomStringJavaCompiler { ...@@ -86,14 +87,15 @@ public class CustomStringJavaCompiler {
*/ */
public boolean compiler() { public boolean compiler() {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
//标准的内容管理器,更换成自己的实现,覆盖部分方法 // 标准的内容管理器,更换成自己的实现,覆盖部分方法
StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null); StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null);
JavaFileManager javaFileManager = new StringJavaFileManage(standardFileManager); JavaFileManager javaFileManager = new StringJavaFileManage(standardFileManager);
//构造源代码对象 // 构造源代码对象
JavaFileObject javaFileObject = new StringJavaFileObject(fullClassName, sourceCode); JavaFileObject javaFileObject = new StringJavaFileObject(fullClassName, sourceCode);
//获取一个编译任务 // 获取一个编译任务
JavaCompiler.CompilationTask task = compiler.getTask(null, javaFileManager, diagnosticsCollector, null, null, Arrays.asList(javaFileObject)); JavaCompiler.CompilationTask task = compiler.getTask(null, javaFileManager, diagnosticsCollector, null, null,
//设置编译耗时 Arrays.asList(javaFileObject));
// 设置编译耗时
compilerTakeTime = System.currentTimeMillis() - startTime; compilerTakeTime = System.currentTimeMillis() - startTime;
return task.call(); return task.call();
} }
...@@ -105,18 +107,22 @@ public class CustomStringJavaCompiler { ...@@ -105,18 +107,22 @@ public class CustomStringJavaCompiler {
*/ */
public boolean compilerToTmpPath(String tmpPath) { public boolean compilerToTmpPath(String tmpPath) {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
File codeFile = FileUtil.writeUtf8String(sourceCode, tmpPath + StrUtil.replace(fullClassName, ".", "/") + ".java"); File codeFile =
//标准的内容管理器,更换成自己的实现,覆盖部分方法 FileUtil.writeUtf8String(sourceCode, tmpPath + StrUtil.replace(fullClassName, ".", "/") + ".java");
// 标准的内容管理器,更换成自己的实现,覆盖部分方法
StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null); StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null);
try { try {
standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singletonList(new File(tmpPath))); standardFileManager.setLocation(StandardLocation.CLASS_OUTPUT,
Collections.singletonList(new File(tmpPath)));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
Iterable<? extends JavaFileObject> javaFileObject = standardFileManager.getJavaFileObjectsFromFiles(Collections.singletonList(codeFile)); Iterable<? extends JavaFileObject> javaFileObject =
//获取一个编译任务 standardFileManager.getJavaFileObjectsFromFiles(Collections.singletonList(codeFile));
JavaCompiler.CompilationTask task = compiler.getTask(null, standardFileManager, diagnosticsCollector, null, null, javaFileObject); // 获取一个编译任务
//设置编译耗时 JavaCompiler.CompilationTask task =
compiler.getTask(null, standardFileManager, diagnosticsCollector, null, null, javaFileObject);
// 设置编译耗时
compilerTakeTime = System.currentTimeMillis() - startTime; compilerTakeTime = System.currentTimeMillis() - startTime;
return task.call(); return task.call();
} }
...@@ -163,16 +169,17 @@ public class CustomStringJavaCompiler { ...@@ -163,16 +169,17 @@ public class CustomStringJavaCompiler {
* 自定义一个字符串的源码对象 * 自定义一个字符串的源码对象
*/ */
private class StringJavaFileObject extends SimpleJavaFileObject { private class StringJavaFileObject extends SimpleJavaFileObject {
//等待编译的源码字段
// 等待编译的源码字段
private String contents; private String contents;
//java源代码 => StringJavaFileObject对象 的时候使用 // java源代码 => StringJavaFileObject对象 的时候使用
public StringJavaFileObject(String className, String contents) { public StringJavaFileObject(String className, String contents) {
super(URI.create("string:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE); super(URI.create("string:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), Kind.SOURCE);
this.contents = contents; this.contents = contents;
} }
//字符串源码会调用该方法 // 字符串源码会调用该方法
@Override @Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return contents; return contents;
...@@ -184,21 +191,22 @@ public class CustomStringJavaCompiler { ...@@ -184,21 +191,22 @@ public class CustomStringJavaCompiler {
* 自定义一个编译之后的字节码对象 * 自定义一个编译之后的字节码对象
*/ */
public class ByteJavaFileObject extends SimpleJavaFileObject { public class ByteJavaFileObject extends SimpleJavaFileObject {
//存放编译后的字节码
// 存放编译后的字节码
private ByteArrayOutputStream outPutStream; private ByteArrayOutputStream outPutStream;
public ByteJavaFileObject(String className, Kind kind) { public ByteJavaFileObject(String className, Kind kind) {
super(URI.create("string:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), kind); super(URI.create("string:///" + className.replaceAll("\\.", "/") + Kind.SOURCE.extension), kind);
} }
//StringJavaFileManage 编译之后的字节码输出会调用该方法(把字节码输出到outputStream) // StringJavaFileManage 编译之后的字节码输出会调用该方法(把字节码输出到outputStream)
@Override @Override
public OutputStream openOutputStream() { public OutputStream openOutputStream() {
outPutStream = new ByteArrayOutputStream(); outPutStream = new ByteArrayOutputStream();
return outPutStream; return outPutStream;
} }
//在类加载器加载的时候需要用到 // 在类加载器加载的时候需要用到
public byte[] getCompiledBytes() { public byte[] getCompiledBytes() {
return outPutStream.toByteArray(); return outPutStream.toByteArray();
} }
...@@ -208,17 +216,18 @@ public class CustomStringJavaCompiler { ...@@ -208,17 +216,18 @@ public class CustomStringJavaCompiler {
* 自定义一个JavaFileManage来控制编译之后字节码的输出位置 * 自定义一个JavaFileManage来控制编译之后字节码的输出位置
*/ */
private class StringJavaFileManage extends ForwardingJavaFileManager { private class StringJavaFileManage extends ForwardingJavaFileManager {
StringJavaFileManage(JavaFileManager fileManager) { StringJavaFileManage(JavaFileManager fileManager) {
super(fileManager); super(fileManager);
} }
//获取输出的文件对象,它表示给定位置处指定类型的指定类。 // 获取输出的文件对象,它表示给定位置处指定类型的指定类。
@Override @Override
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind,
FileObject sibling) throws IOException {
ByteJavaFileObject javaFileObject = new ByteJavaFileObject(className, kind); ByteJavaFileObject javaFileObject = new ByteJavaFileObject(className, kind);
javaFileObjectMap.put(className, javaFileObject); javaFileObjectMap.put(className, javaFileObject);
return javaFileObject; return javaFileObject;
} }
} }
} }
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
* *
*/ */
package com.dlink.utils; package com.dlink.function.compiler;
import com.dlink.constant.PathConstant; import com.dlink.function.constant.PathConstant;
import scala.tools.nsc.GenericRunnerSettings; import scala.tools.nsc.GenericRunnerSettings;
import scala.tools.nsc.interpreter.IMain; import scala.tools.nsc.interpreter.IMain;
...@@ -29,17 +29,13 @@ import scala.tools.nsc.interpreter.IMain; ...@@ -29,17 +29,13 @@ import scala.tools.nsc.interpreter.IMain;
* @since 0.6.8 * @since 0.6.8
*/ */
public class CustomStringScalaCompiler { public class CustomStringScalaCompiler {
private static IMain interpreter;
public static IMain getInterpreter() { public static IMain getInterpreter(Integer missionId) {
if (interpreter != null) {
return interpreter;
}
GenericRunnerSettings settings = new GenericRunnerSettings((err) -> null); GenericRunnerSettings settings = new GenericRunnerSettings((err) -> null);
settings.usejavacp().tryToSetFromPropertyValue("true"); settings.usejavacp().tryToSetFromPropertyValue("true");
settings.Yreploutdir().tryToSetFromPropertyValue(PathConstant.UDF_PATH); settings.Yreploutdir().tryToSetFromPropertyValue(PathConstant.getUdfCompilerJavaPath(missionId));
interpreter = new IMain(settings); return new IMain(settings);
return interpreter;
} }
} }
/*
*
* 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 com.dlink.function.compiler;
import com.dlink.assertion.Asserts;
import com.dlink.function.data.model.UDF;
import com.dlink.function.exception.UDFCompilerException;
import org.apache.flink.configuration.ReadableConfig;
import java.util.List;
import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.6.8
*/
public interface FunctionCompiler {
/**
* 函数代码在线动态编译
*
* @param udf udf
* @param conf flink-conf
* @param missionId 任务id
* @return 是否成功
*/
boolean compiler(UDF udf, ReadableConfig conf, Integer missionId);
/**
* 编译
* @param udf udf实例
* @param conf flink-conf
* @param missionId 任务id
* @return 编译状态
*/
static boolean getCompiler(UDF udf, ReadableConfig conf, Integer missionId) {
Asserts.checkNull(udf, "udf为空");
Asserts.checkNull(udf.getCode(), "udf 代码为空");
boolean success;
switch (udf.getFunctionLanguage()) {
case JAVA:
success = Singleton.get(JavaCompiler.class).compiler(udf, conf, missionId);
break;
case SCALA:
success = Singleton.get(ScalaCompiler.class).compiler(udf, conf, missionId);
break;
case PYTHON:
success = Singleton.get(PythonFunction.class).compiler(udf, conf, missionId);
break;
default:
throw UDFCompilerException.notSupportedException(udf.getFunctionLanguage().name());
}
return success;
}
/**
* 编译
* @param udfList udf、实例列表
* @param conf flink-conf
* @param missionId 任务id
*/
static void getCompiler(List<UDF> udfList, ReadableConfig conf, Integer missionId) {
for (UDF udf : udfList) {
if (!getCompiler(udf, conf, missionId)) {
throw new UDFCompilerException(StrUtil.format("codeLanguage:{} , className:{} 编译失败",
udf.getFunctionLanguage(), udf.getClassName()));
}
}
}
}
/*
*
* 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 com.dlink.function.compiler;
import com.dlink.function.data.model.UDF;
import com.dlink.function.data.model.UDFPath;
import java.util.ArrayList;
import java.util.List;
/**
* @author ZackYoung
* @since 0.6.8
*/
public interface FunctionPackage {
/**
* 打包
*
* @param udfList udf列表
* @param missionId 任务id
* @return 文件绝对路径
*/
String[] pack(List<UDF> udfList, Integer missionId);
/**
* 打包
*
* @param udfList udf 列表
* @param missionId 任务id
* @return 打包结果
*/
static UDFPath bale(List<UDF> udfList, Integer missionId) {
List<UDF> jvmList = new ArrayList<>();
List<UDF> pythonList = new ArrayList<>();
for (UDF udf : udfList) {
switch (udf.getFunctionLanguage()) {
default:
case JAVA:
case SCALA:
jvmList.add(udf);
break;
case PYTHON:
pythonList.add(udf);
}
}
return UDFPath.builder()
.jarPaths(new JVMPackage().pack(jvmList, missionId))
.pyPaths(new PythonFunction().pack(pythonList, missionId))
.build();
}
}
/*
*
* 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 com.dlink.function.compiler;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.ZipUtils;
import org.apache.flink.table.catalog.FunctionLanguage;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.6.8
*/
public class JVMPackage implements FunctionPackage {
@Override
public String[] pack(List<UDF> udfList, Integer missionId) {
if (CollUtil.isEmpty(udfList)) {
return new String[0];
}
List<String> classNameList = udfList.stream()
.filter(udf -> udf.getFunctionLanguage() == FunctionLanguage.JAVA
|| udf.getFunctionLanguage() == FunctionLanguage.SCALA)
.map(UDF::getClassName)
.collect(Collectors.toList());
String[] clazzs = new String[classNameList.size()];
InputStream[] fileInputStreams = new InputStream[classNameList.size()];
if (CollUtil.isEmpty(classNameList)) {
return new String[0];
}
for (int i = 0; i < classNameList.size(); i++) {
String className = classNameList.get(i);
String classFile = StrUtil.replace(className, ".", "/") + ".class";
String absoluteFilePath = PathConstant.getUdfCompilerJavaPath(missionId, classFile);
clazzs[i] = classFile;
fileInputStreams[i] = FileUtil.getInputStream(absoluteFilePath);
}
String jarPath = PathConstant.getUdfPackagePath(missionId, PathConstant.UDF_JAR_NAME);
// 编译好的文件打包jar
File file = FileUtil.file(jarPath);
FileUtil.del(file);
try (ZipUtils zipWriter = new ZipUtils(file, Charset.defaultCharset())) {
zipWriter.add(clazzs, fileInputStreams);
}
return new String[]{jarPath};
}
}
/*
*
* 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 com.dlink.function.compiler;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.data.model.UDF;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import org.apache.flink.configuration.ReadableConfig;
import lombok.extern.slf4j.Slf4j;
/**
* java 编译
*
* @author ZackYoung
* @since 0.6.8
*/
@Slf4j
public class JavaCompiler implements FunctionCompiler {
/**
* 函数代码在线动态编译
*
* @param udf udf
* @param conf flink-conf
* @param missionId 任务id
* @return 是否成功
*/
@Override
public boolean compiler(UDF udf, ReadableConfig conf, Integer missionId) {
ProcessEntity process = ProcessContextHolder.getProcess();
process.info("正在编译 java 代码 , class: " + udf.getClassName());
CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(udf.getCode());
boolean res = compiler.compilerToTmpPath(PathConstant.getUdfCompilerJavaPath(missionId));
String className = compiler.getFullClassName();
if (res) {
process.info("class编译成功:" + className);
process.info("compilerTakeTime:" + compiler.getCompilerTakeTime());
return true;
} else {
log.error("class编译失败:{}", className);
process.error("class编译失败:" + className);
process.error(compiler.getCompilerMessage());
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 com.dlink.function.compiler;
import com.dlink.assertion.Asserts;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.data.model.Env;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
import com.dlink.function.util.ZipUtils;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import org.apache.flink.client.python.PythonFunctionFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.ReadableConfig;
import org.apache.flink.python.PythonOptions;
import org.apache.flink.table.catalog.FunctionLanguage;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;
/**
* python 编译
*
* @author ZackYoung
* @since 0.6.8
*/
@Slf4j
public class PythonFunction implements FunctionCompiler, FunctionPackage {
/**
* 函数代码在线动态编译
*
* @param udf udf
* @param conf flink-conf
* @param missionId 任务id
* @return 是否成功
*/
@Override
public boolean compiler(UDF udf, ReadableConfig conf, Integer missionId) {
Asserts.checkNull(udf, "flink-config 不能为空");
ProcessEntity process = ProcessContextHolder.getProcess();
process.info("正在编译 python 代码 , class: " + udf.getClassName());
File pyFile = FileUtil.writeUtf8String(udf.getCode(),
PathConstant.getUdfCompilerPythonPath(missionId, UDFUtil.getPyFileName(udf.getClassName()) + ".py"));
File zipFile = ZipUtil.zip(pyFile);
FileUtil.del(pyFile);
try {
Configuration configuration = new Configuration((Configuration) conf);
configuration.set(PythonOptions.PYTHON_FILES, zipFile.getAbsolutePath());
configuration.set(PythonOptions.PYTHON_CLIENT_EXECUTABLE, Env.getPath());
configuration.set(PythonOptions.PYTHON_EXECUTABLE, Env.getPath());
PythonFunctionFactory.getPythonFunction(udf.getClassName(), configuration, null);
process.info("Python udf编译成功 ; className:" + udf.getClassName());
} catch (Exception e) {
process.error("Python udf编译失败 ; className:" + udf.getClassName() + " 。 原因: "
+ ExceptionUtil.getRootCauseMessage(e));
return false;
}
FileUtil.del(zipFile);
return true;
}
@Override
public String[] pack(List<UDF> udfList, Integer missionId) {
if (CollUtil.isEmpty(udfList)) {
return new String[0];
}
udfList = udfList.stream()
.filter(udf -> udf.getFunctionLanguage() == FunctionLanguage.PYTHON)
.collect(Collectors.toList());
if (CollUtil.isEmpty(udfList)) {
return new String[0];
}
InputStream[] inputStreams = udfList.stream().map(udf -> {
File file = FileUtil.writeUtf8String(udf.getCode(), PathConstant.getUdfCompilerPythonPath(missionId,
UDFUtil.getPyFileName(udf.getClassName()) + ".py"));
return FileUtil.getInputStream(file);
}).toArray(InputStream[]::new);
String[] paths =
udfList.stream().map(x -> StrUtil.split(x.getClassName(), ".").get(0) + ".py").toArray(String[]::new);
String path = PathConstant.getUdfPackagePath(missionId, PathConstant.UDF_PYTHON_NAME);
File file = FileUtil.file(path);
FileUtil.del(file);
try (ZipUtils zipWriter = new ZipUtils(file, Charset.defaultCharset())) {
zipWriter.add(paths, inputStreams);
}
return new String[]{path};
}
}
/*
*
* 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 com.dlink.function.compiler;
import com.dlink.function.data.model.UDF;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import org.apache.flink.configuration.ReadableConfig;
/**
* scala编译
*
* @author ZackYoung
* @since 0.6.8
*/
public class ScalaCompiler implements FunctionCompiler {
@Override
public boolean compiler(UDF udf, ReadableConfig conf, Integer missionId) {
ProcessEntity process = ProcessContextHolder.getProcess();
String className = udf.getClassName();
process.info("正在编译 scala 代码 , class: " + className);
if (CustomStringScalaCompiler.getInterpreter(missionId).compileString(udf.getCode())) {
process.info("scala class编译成功:" + className);
return true;
} else {
process.error("scala class编译失败:" + className);
return false;
}
}
}
...@@ -17,9 +17,10 @@ ...@@ -17,9 +17,10 @@
* *
*/ */
package com.dlink.constant; package com.dlink.function.constant;
public interface FlinkFunctionConstant { public interface FlinkFunctionConstant {
/** /**
* TO_MAP 函数 * TO_MAP 函数
*/ */
......
...@@ -17,10 +17,12 @@ ...@@ -17,10 +17,12 @@
* *
*/ */
package com.dlink.constant; package com.dlink.function.constant;
import java.io.File; import java.io.File;
import cn.hutool.core.util.StrUtil;
/** /**
* 文件路径常量 * 文件路径常量
* *
...@@ -37,11 +39,13 @@ public class PathConstant { ...@@ -37,11 +39,13 @@ public class PathConstant {
* tmp路径 * tmp路径
*/ */
public static final String TMP_PATH = WORK_DIR + File.separator + "tmp" + File.separator; public static final String TMP_PATH = WORK_DIR + File.separator + "tmp" + File.separator;
/** /**
* udf路径 * udf路径
*/ */
public static final String UDF_PATH = TMP_PATH + "udf" + File.separator; public static final String UDF_PATH = TMP_PATH + "udf" + File.separator;
public static final String UDF_PYTHON_PATH = TMP_PATH + "udf" + File.separator + "python" + File.separator; public static final String COMPILER = "compiler";
public static final String PACKAGE = "package";
/** /**
* udf jar规则 * udf jar规则
*/ */
...@@ -54,9 +58,27 @@ public class PathConstant { ...@@ -54,9 +58,27 @@ public class PathConstant {
* udf jar tmp名字 * udf jar tmp名字
*/ */
public static final String UDF_JAR_TMP_NAME = "udf-tmp.jar"; public static final String UDF_JAR_TMP_NAME = "udf-tmp.jar";
public static final String UDF_JAR_NAME = "udf.jar";
public static final String UDF_PYTHON_NAME = "python_udf.zip";
/** /**
* udf jar tmp路径 * udf jar tmp路径
*/ */
public static final String UDF_JAR_TMP_PATH = UDF_PATH + UDF_JAR_TMP_NAME; public static final String UDF_JAR_TMP_PATH = UDF_PATH + UDF_JAR_TMP_NAME;
public static String getPath(Object... path) {
return StrUtil.join(File.separator, path) + File.separator;
}
public static String getUdfCompilerJavaPath(Integer missionId, Object... path) {
return getPath(UDF_PATH, missionId, COMPILER, "java", path);
}
public static String getUdfCompilerPythonPath(Integer missionId, Object... path) {
return getPath(UDF_PATH, missionId, COMPILER, "python", path);
}
public static String getUdfPackagePath(Integer missionId, Object... path) {
return getPath(UDF_PATH, missionId, PACKAGE, path);
}
} }
/*
*
* 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 com.dlink.function.data.model;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author ZackYoung
* @since 0.6.8
*/
@Component
public class Env {
@Value("${dinky.python.path}")
private String path;
private static String PATH;
public static String getPath() {
return PATH;
}
@PostConstruct
public void init() {
PATH = path == null ? "python" : path;
}
}
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.udf; package com.dlink.function.data.model;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
...@@ -25,7 +25,6 @@ import lombok.Builder; ...@@ -25,7 +25,6 @@ import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
/** /**
* @author ZackYoung * @author ZackYoung
* @since 0.6.8 * @since 0.6.8
...@@ -34,6 +33,7 @@ import lombok.Setter; ...@@ -34,6 +33,7 @@ import lombok.Setter;
@Setter @Setter
@Builder @Builder
public class UDF { public class UDF {
/** /**
* 函数名 * 函数名
*/ */
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.model; package com.dlink.function.data.model;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
...@@ -31,6 +31,7 @@ import lombok.Setter; ...@@ -31,6 +31,7 @@ import lombok.Setter;
@Setter @Setter
@Builder @Builder
public class UDFPath { public class UDFPath {
String[] jarPaths; String[] jarPaths;
String[] pyPaths; String[] pyPaths;
} }
/*
*
* 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 com.dlink.function.exception;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.6.8
*/
public class UDFCompilerException extends RuntimeException {
public UDFCompilerException() {
}
public UDFCompilerException(String message) {
super(message);
}
public static UDFCompilerException notSupportedException(String codeType) {
return new UDFCompilerException(StrUtil.format("未知的代码类型:{}", codeType));
}
}
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.ud.udf; package com.dlink.function.udf;
import org.apache.flink.table.functions.ScalarFunction; import org.apache.flink.table.functions.ScalarFunction;
......
...@@ -17,9 +17,9 @@ ...@@ -17,9 +17,9 @@
* *
*/ */
package com.dlink.ud.udtaf; package com.dlink.function.udtaf;
import com.dlink.ud.udtaf.RowsToMap.MyAccum; import com.dlink.function.udtaf.RowsToMap.MyAccum;
import org.apache.flink.table.api.DataTypes; import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.catalog.DataTypeFactory; import org.apache.flink.table.catalog.DataTypeFactory;
...@@ -50,27 +50,26 @@ public class RowsToMap<K, V> extends TableAggregateFunction<Map<K, V>, MyAccum<K ...@@ -50,27 +50,26 @@ public class RowsToMap<K, V> extends TableAggregateFunction<Map<K, V>, MyAccum<K
@Override @Override
public TypeInference getTypeInference(DataTypeFactory typeFactory) { public TypeInference getTypeInference(DataTypeFactory typeFactory) {
return TypeInference.newBuilder() return TypeInference.newBuilder()
.inputTypeStrategy(InputTypeStrategies.sequence( .inputTypeStrategy(InputTypeStrategies.sequence(
InputTypeStrategies.ANY, InputTypeStrategies.ANY,
InputTypeStrategies.ANY InputTypeStrategies.ANY))
)) .accumulatorTypeStrategy(callContext -> {
.accumulatorTypeStrategy(callContext -> { List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); final DataType arg0DataType = argumentDataTypes.get(0);
final DataType arg0DataType = argumentDataTypes.get(0); final DataType arg1DataType = argumentDataTypes.get(1);
final DataType arg1DataType = argumentDataTypes.get(1); final DataType accDataType = DataTypes.STRUCTURED(
final DataType accDataType = DataTypes.STRUCTURED( MyAccum.class,
MyAccum.class, DataTypes.FIELD("mapView",
DataTypes.FIELD("mapView", DataTypes.MAP(arg0DataType, arg1DataType)));
DataTypes.MAP(arg0DataType, arg1DataType))); return Optional.of(accDataType);
return Optional.of(accDataType); })
}) .outputTypeStrategy(callContext -> {
.outputTypeStrategy(callContext -> { List<DataType> argumentDataTypes = callContext.getArgumentDataTypes();
List<DataType> argumentDataTypes = callContext.getArgumentDataTypes(); final DataType arg0DataType = argumentDataTypes.get(0);
final DataType arg0DataType = argumentDataTypes.get(0); final DataType arg1DataType = argumentDataTypes.get(1);
final DataType arg1DataType = argumentDataTypes.get(1); return Optional.of(DataTypes.MAP(arg0DataType, arg1DataType));
return Optional.of(DataTypes.MAP(arg0DataType, arg1DataType)); })
}) .build();
.build();
} }
@Override @Override
...@@ -79,7 +78,7 @@ public class RowsToMap<K, V> extends TableAggregateFunction<Map<K, V>, MyAccum<K ...@@ -79,7 +78,7 @@ public class RowsToMap<K, V> extends TableAggregateFunction<Map<K, V>, MyAccum<K
} }
public void accumulate( public void accumulate(
MyAccum<K, V> acc, K cls, V v) { MyAccum<K, V> acc, K cls, V v) {
if (v == null) { if (v == null) {
return; return;
} }
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.ud.udtaf; package com.dlink.function.udtaf;
import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.functions.TableAggregateFunction; import org.apache.flink.table.functions.TableAggregateFunction;
...@@ -33,6 +33,7 @@ import org.apache.flink.util.Collector; ...@@ -33,6 +33,7 @@ import org.apache.flink.util.Collector;
public class Top2 extends TableAggregateFunction<Tuple2<Integer, Integer>, Top2.Top2Accumulator> { public class Top2 extends TableAggregateFunction<Tuple2<Integer, Integer>, Top2.Top2Accumulator> {
public static class Top2Accumulator { public static class Top2Accumulator {
public Integer first; public Integer first;
public Integer second; public Integer second;
} }
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.ud.udtaf; package com.dlink.function.udtaf;
import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.functions.TableAggregateFunction; import org.apache.flink.table.functions.TableAggregateFunction;
...@@ -30,9 +30,12 @@ import org.apache.flink.util.Collector; ...@@ -30,9 +30,12 @@ import org.apache.flink.util.Collector;
* @since 2021/12/17 18:55 * @since 2021/12/17 18:55
*/ */
public class Top2WithRetract extends TableAggregateFunction<Tuple2<Integer, Integer>, Top2WithRetract.Top2WithRetractAccumulator> { public class Top2WithRetract
extends
TableAggregateFunction<Tuple2<Integer, Integer>, Top2WithRetract.Top2WithRetractAccumulator> {
public static class Top2WithRetractAccumulator { public static class Top2WithRetractAccumulator {
public Integer first; public Integer first;
public Integer second; public Integer second;
public Integer oldFirst; public Integer oldFirst;
...@@ -81,8 +84,8 @@ public class Top2WithRetract extends TableAggregateFunction<Tuple2<Integer, Inte ...@@ -81,8 +84,8 @@ public class Top2WithRetract extends TableAggregateFunction<Tuple2<Integer, Inte
} }
public void emitUpdateWithRetract( public void emitUpdateWithRetract(
Top2WithRetractAccumulator acc, Top2WithRetractAccumulator acc,
RetractableCollector<Tuple2<Integer, Integer>> out) { RetractableCollector<Tuple2<Integer, Integer>> out) {
if (!acc.first.equals(acc.oldFirst)) { if (!acc.first.equals(acc.oldFirst)) {
// if there is an update, retract the old value then emit a new value // if there is an update, retract the old value then emit a new value
if (acc.oldFirst != Integer.MIN_VALUE) { if (acc.oldFirst != Integer.MIN_VALUE) {
...@@ -101,5 +104,3 @@ public class Top2WithRetract extends TableAggregateFunction<Tuple2<Integer, Inte ...@@ -101,5 +104,3 @@ public class Top2WithRetract extends TableAggregateFunction<Tuple2<Integer, Inte
} }
} }
} }
...@@ -17,21 +17,19 @@ ...@@ -17,21 +17,19 @@
* *
*/ */
package com.dlink.utils; package com.dlink.function.util;
import com.dlink.assertion.Asserts; import com.dlink.assertion.Asserts;
import com.dlink.config.Dialect; import com.dlink.config.Dialect;
import com.dlink.constant.PathConstant; import com.dlink.function.compiler.CustomStringJavaCompiler;
import com.dlink.function.compiler.CustomStringScalaCompiler;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.data.model.UDF;
import com.dlink.pool.ClassEntity; import com.dlink.pool.ClassEntity;
import com.dlink.pool.ClassPool; import com.dlink.pool.ClassPool;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import com.dlink.udf.UDF;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -40,8 +38,6 @@ import java.util.Collections; ...@@ -40,8 +38,6 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.CompilerConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -53,7 +49,6 @@ import cn.hutool.core.io.FileUtil; ...@@ -53,7 +49,6 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5; import cn.hutool.crypto.digest.MD5;
...@@ -70,16 +65,12 @@ import groovy.lang.GroovyClassLoader; ...@@ -70,16 +65,12 @@ import groovy.lang.GroovyClassLoader;
*/ */
public class UDFUtil { public class UDFUtil {
private UDFUtil() {
}
protected static final Logger log = LoggerFactory.getLogger(UDFUtil.class); protected static final Logger log = LoggerFactory.getLogger(UDFUtil.class);
/** /**
* 存放 udf md5与版本对应的k,v值 * 存放 udf md5与版本对应的k,v值
*/ */
protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>(); protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>();
private static final String FUNCTION_REGEX = "function (.*?)'(.*?)'"; private static final String FUNCTION_REGEX = "function (.*?)'(.*?)'";
private static final String FUNCTION_SQL_REGEX = "create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?;";
private static final String LANGUAGE_REGEX = "language (.*);"; private static final String LANGUAGE_REGEX = "language (.*);";
public static final String PYTHON_UDF_ATTR = "(\\S)\\s+=\\s+ud(?:f|tf|af|taf)"; public static final String PYTHON_UDF_ATTR = "(\\S)\\s+=\\s+ud(?:f|tf|af|taf)";
public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):"; public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):";
...@@ -104,63 +95,27 @@ public class UDFUtil { ...@@ -104,63 +95,27 @@ public class UDFUtil {
String clazz = CollUtil.getLast(split); String clazz = CollUtil.getLast(split);
String packageName = StrUtil.strip(className, clazz); String packageName = StrUtil.strip(className, clazz);
Dict data = Dict.create() Dict data = Dict.create()
.set("className", clazz) .set("className", clazz)
.set("package", Asserts.isNullString(packageName) ? "" : StrUtil.strip(packageName, ".")); .set("package", Asserts.isNullString(packageName) ? "" : StrUtil.strip(packageName, "."));
return ENGINE.getTemplate(template).render(data); return ENGINE.getTemplate(template).render(data);
case PYTHON: case PYTHON:
default: default:
String clazzName = split.get(0); String clazzName = split.get(0);
Dict data2 = Dict.create() Dict data2 = Dict.create()
.set("className", clazzName) .set("className", clazzName)
.set("attr", split.size() > 1 ? split.get(1) : null); .set("attr", split.size() > 1 ? split.get(1) : null);
return ENGINE.getTemplate(template).render(data2); return ENGINE.getTemplate(template).render(data2);
} }
} }
public static List<UDF> getUDF(String statement) { public static String getPyFileName(String className) {
ProcessEntity process = ProcessContextHolder.getProcess(); Asserts.checkNullString(className, "类名不能为空");
process.info("Parse UDF class name:"); return StrUtil.split(className, ".").get(0);
Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE);
List<String> udfSqlList = ReUtil.findAllGroup0(pattern, statement);
List<UDF> udfList = udfSqlList.stream().map(sql -> {
List<String> groups = ReUtil.getAllGroups(pattern, sql);
String udfName = groups.get(1);
String className = groups.get(2);
return UDF.builder()
.name(udfName)
.className(className)
.functionLanguage(FunctionLanguage.valueOf(Opt.ofNullable(groups.get(4)).orElse("JAVA").toUpperCase()))
.build();
}).collect(Collectors.toList());
List<String> classNameList = udfList.stream().map(UDF::getClassName).collect(Collectors.toList());
process.info(StringUtils.join(",", classNameList));
process.info(CharSequenceUtil.format("A total of {} UDF have been Parsed.", classNameList.size()));
return udfList;
}
public static String buildPy(List<UDF> udfList) {
InputStream[] inputStreams = udfList.stream().map(x -> {
String s = buildPy(x);
return FileUtil.getInputStream(s);
}).toArray(InputStream[]::new);
String[] paths = udfList.stream().map(x -> StrUtil.split(x.getClassName(), ".").get(0) + ".py").toArray(String[]::new);
File file = FileUtil.file(PathConstant.UDF_PYTHON_PATH + "python_udf.zip");
FileUtil.del(file);
try (ZipUtils zipWriter = new ZipUtils(file, Charset.defaultCharset())) {
zipWriter.add(paths, inputStreams);
}
return file.getAbsolutePath();
}
public static String buildPy(UDF udf) {
File file = FileUtil.writeUtf8String(udf.getCode(), PathConstant.UDF_PYTHON_PATH + StrUtil.split(udf.getClassName(), ".").get(0) + ".py");
return file.getAbsolutePath();
} }
public static String getPyUDFAttr(String code) { public static String getPyUDFAttr(String code) {
return Opt.ofBlankAble(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_ATTR, code)) return Opt.ofBlankAble(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_ATTR, code))
.orElse(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_DEF, code)); .orElse(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_DEF, code));
} }
public static String getScalaFullClassName(String code) { public static String getScalaFullClassName(String code) {
...@@ -169,23 +124,6 @@ public class UDFUtil { ...@@ -169,23 +124,6 @@ public class UDFUtil {
return String.join(".", Arrays.asList(packageName, clazz)); return String.join(".", Arrays.asList(packageName, clazz));
} }
public static Boolean buildClass(String code) {
CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(code);
boolean res = compiler.compiler();
String className = compiler.getFullClassName();
if (res) {
byte[] compiledBytes = compiler.getJavaFileObjectMap(className).getCompiledBytes();
ClassPool.push(new ClassEntity(className, code, compiledBytes));
log.info("class:{} 编译成功", className);
log.info("compilerTakeTime:{}", compiler.getCompilerTakeTime());
initClassLoader(className);
} else {
log.warn("class:{} 编译失败", className);
log.warn(compiler.getCompilerMessage());
}
return res;
}
public static void initClassLoader(String name) { public static void initClassLoader(String name) {
ClassEntity classEntity = ClassPool.get(name); ClassEntity classEntity = ClassPool.get(name);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
...@@ -197,6 +135,7 @@ public class UDFUtil { ...@@ -197,6 +135,7 @@ public class UDFUtil {
Thread.currentThread().setContextClassLoader(groovyClassLoader); Thread.currentThread().setContextClassLoader(groovyClassLoader);
} }
@Deprecated
public static Map<String, List<String>> buildJar(List<UDF> codeList) { public static Map<String, List<String>> buildJar(List<UDF> codeList) {
List<String> successList = new ArrayList<>(); List<String> successList = new ArrayList<>();
List<String> failedList = new ArrayList<>(); List<String> failedList = new ArrayList<>();
...@@ -220,7 +159,7 @@ public class UDFUtil { ...@@ -220,7 +159,7 @@ public class UDFUtil {
} }
} else if (udf.getFunctionLanguage() == FunctionLanguage.SCALA) { } else if (udf.getFunctionLanguage() == FunctionLanguage.SCALA) {
String className = udf.getClassName(); String className = udf.getClassName();
if (CustomStringScalaCompiler.getInterpreter().compileString(udf.getCode())) { if (CustomStringScalaCompiler.getInterpreter(null).compileString(udf.getCode())) {
log.info("scala class编译成功:{}" + className); log.info("scala class编译成功:{}" + className);
successList.add(className); successList.add(className);
} else { } else {
...@@ -231,17 +170,17 @@ public class UDFUtil { ...@@ -231,17 +170,17 @@ public class UDFUtil {
}); });
String[] clazzs = successList.stream().map(className -> StrUtil.replace(className, ".", "/") + ".class") String[] clazzs = successList.stream().map(className -> StrUtil.replace(className, ".", "/") + ".class")
.toArray(String[]::new); .toArray(String[]::new);
InputStream[] fileInputStreams = InputStream[] fileInputStreams =
successList.stream().map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class") successList.stream().map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class")
.map(FileUtil::getInputStream).toArray(InputStream[]::new); .map(FileUtil::getInputStream).toArray(InputStream[]::new);
// 编译好的文件打包jar // 编译好的文件打包jar
try (ZipUtils zipWriter = new ZipUtils(FileUtil.file(udfJarPath), Charset.defaultCharset())) { try (ZipUtils zipWriter = new ZipUtils(FileUtil.file(udfJarPath), Charset.defaultCharset())) {
zipWriter.add(clazzs, fileInputStreams); zipWriter.add(clazzs, fileInputStreams);
} }
String md5 = md5sum(udfJarPath); String md5 = md5sum(udfJarPath);
return MapUtil.builder("success", successList).put("failed", failedList) return MapUtil.builder("success", successList).put("failed", failedList)
.put("md5", Collections.singletonList(md5)).build(); .put("md5", Collections.singletonList(md5)).build();
} }
/** /**
...@@ -250,6 +189,7 @@ public class UDFUtil { ...@@ -250,6 +189,7 @@ public class UDFUtil {
* @param codeList 代码列表 * @param codeList 代码列表
* @return {@link java.lang.String} * @return {@link java.lang.String}
*/ */
@Deprecated
public static String getUdfFileAndBuildJar(List<UDF> codeList) { public static String getUdfFileAndBuildJar(List<UDF> codeList) {
// 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过 // 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过
String md5 = buildJar(codeList).get("md5").get(0); String md5 = buildJar(codeList).get("md5").get(0);
...@@ -283,13 +223,14 @@ public class UDFUtil { ...@@ -283,13 +223,14 @@ public class UDFUtil {
/** /**
* 扫描udf包文件,写入md5到 UDF_MD5_MAP * 扫描udf包文件,写入md5到 UDF_MD5_MAP
*/ */
@Deprecated
private static void scanUDFMD5() { private static void scanUDFMD5() {
List<String> fileList = FileUtil.listFileNames(PathConstant.UDF_PATH); List<String> fileList = FileUtil.listFileNames(PathConstant.UDF_PATH);
fileList.stream().filter(fileName -> ReUtil.isMatch(PathConstant.UDF_JAR_RULE, fileName)).distinct() fileList.stream().filter(fileName -> ReUtil.isMatch(PathConstant.UDF_JAR_RULE, fileName)).distinct()
.forEach(fileName -> { .forEach(fileName -> {
Integer version = Convert.toInt(ReUtil.getGroup0(PathConstant.UDF_VERSION_RULE, fileName)); Integer version = Convert.toInt(ReUtil.getGroup0(PathConstant.UDF_VERSION_RULE, fileName));
UDF_MD5_MAP.put(md5sum(PathConstant.UDF_PATH + fileName), version); UDF_MD5_MAP.put(md5sum(PathConstant.UDF_PATH + fileName), version);
}); });
} }
private static String md5sum(String filePath) { private static String md5sum(String filePath) {
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
* *
*/ */
package com.dlink.utils; package com.dlink.function.util;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
...@@ -42,6 +42,7 @@ import cn.hutool.core.util.StrUtil; ...@@ -42,6 +42,7 @@ import cn.hutool.core.util.StrUtil;
* @since 0.6.8 * @since 0.6.8
*/ */
public class ZipUtils extends ZipWriter { public class ZipUtils extends ZipWriter {
public ZipUtils(File zipFile, Charset charset) { public ZipUtils(File zipFile, Charset charset) {
super(zipFile, charset); super(zipFile, charset);
} }
......
...@@ -102,7 +102,9 @@ public class YarnApplicationGateway extends YarnGateway { ...@@ -102,7 +102,9 @@ public class YarnApplicationGateway extends YarnGateway {
if (configuration.contains(TaskManagerOptions.NUM_TASK_SLOTS)) { if (configuration.contains(TaskManagerOptions.NUM_TASK_SLOTS)) {
clusterSpecificationBuilder.setSlotsPerTaskManager(configuration.get(TaskManagerOptions.NUM_TASK_SLOTS)).createClusterSpecification(); clusterSpecificationBuilder.setSlotsPerTaskManager(configuration.get(TaskManagerOptions.NUM_TASK_SLOTS)).createClusterSpecification();
} }
yarnClusterDescriptor.addShipFiles(Arrays.stream(config.getJarPaths()).map(FileUtil::file).collect(Collectors.toList())); if (config.getJarPaths() != null) {
yarnClusterDescriptor.addShipFiles(Arrays.stream(config.getJarPaths()).map(FileUtil::file).collect(Collectors.toList()));
}
try { try {
ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployApplicationCluster( ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployApplicationCluster(
......
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