Unverified Commit 0d0504cf authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Optimize][UDF] optimize UDF load (#1451)

* add (add jar sqlParser) * optimize udf and add (add jar) can use application model(CDCSOURCE)
parent d15571a1
......@@ -19,9 +19,16 @@
package com.dlink.controller;
import com.dlink.assertion.Asserts;
import com.dlink.exception.BusException;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.util.ZipWriter;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
......@@ -30,8 +37,11 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
/**
......@@ -42,13 +52,34 @@ import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/download")
public class DownloadController {
@GetMapping("downloadDepJar/{taskId}")
public void downloadJavaUDF(@PathVariable Integer taskId, HttpServletResponse resp) throws IOException {
ServletUtil.write(resp, FileUtil.file(PathConstant.getUdfPackagePath(taskId) + PathConstant.UDF_JAR_NAME));
public void downloadJavaUDF(@PathVariable Integer taskId, HttpServletResponse resp) {
if (Asserts.isNull(taskId)) {
throw new BusException("task id can not null!");
}
String udfPackagePath = PathConstant.getUdfPackagePath(taskId);
File depManifestFile = FileUtil.file(udfPackagePath + PathConstant.DEP_MANIFEST);
if (!depManifestFile.exists()) {
return;
}
JSONObject jsonObject = new JSONObject(FileUtil.readUtf8String(depManifestFile));
JSONArray jars = jsonObject.getJSONArray("jars");
List<String> filePath = jars.stream().map(Convert::toStr).collect(Collectors.toList());
String[] jarNameList = filePath.stream().map(FileUtil::getName).map(x -> "jar/" + x).toArray(String[]::new);
File zipFile = FileUtil.file(udfPackagePath + PathConstant.DEP_ZIP);
InputStream[] inputStreams = filePath.stream().map(FileUtil::getInputStream).toArray(InputStream[]::new);
try (ZipWriter zip = new ZipWriter(zipFile, Charset.defaultCharset())) {
zip.add(jarNameList, inputStreams);
zip.add(depManifestFile.getName(), FileUtil.getInputStream(depManifestFile));
}
ServletUtil.write(resp, FileUtil.getInputStream(zipFile));
FileUtil.del(zipFile);
}
@GetMapping("downloadPythonUDF/{taskId}")
public void downloadPythonUDF(@PathVariable Integer taskId, HttpServletResponse resp) throws IOException {
public void downloadPythonUDF(@PathVariable Integer taskId, HttpServletResponse resp) {
ServletUtil.write(resp, FileUtil.file(PathConstant.getUdfPackagePath(taskId) + PathConstant.UDF_PYTHON_NAME));
}
}
......@@ -22,6 +22,7 @@ package com.dlink.controller;
import com.dlink.common.result.ProTableResult;
import com.dlink.common.result.Result;
import com.dlink.dto.TaskRollbackVersionDTO;
import com.dlink.function.pool.UdfCodePool;
import com.dlink.job.JobResult;
import com.dlink.model.JobLifeCycle;
import com.dlink.model.JobStatus;
......@@ -29,11 +30,14 @@ import com.dlink.model.Task;
import com.dlink.model.TaskOperatingSavepointSelect;
import com.dlink.service.TaskService;
import com.dlink.utils.TaskOneClickOperatingUtil;
import com.dlink.utils.UDFUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
......@@ -60,6 +64,7 @@ import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/api/task")
public class TaskController {
@Autowired
private TaskService taskService;
......@@ -97,6 +102,8 @@ public class TaskController {
error.add(id);
}
}
CompletableFuture.runAsync(() -> UdfCodePool.registerPool(
taskService.getAllUDF().stream().map(UDFUtils::taskToUDF).collect(Collectors.toList())));
if (error.size() == 0 && !isAdmin) {
return Result.succeed("删除成功");
} else {
......@@ -228,7 +235,8 @@ public class TaskController {
* 选择保存点重启任务
*/
@GetMapping(value = "/selectSavePointRestartTask")
public Result selectSavePointRestartTask(@RequestParam Integer id, @RequestParam Boolean isOnLine, @RequestParam String savePointPath) {
public Result selectSavePointRestartTask(@RequestParam Integer id, @RequestParam Boolean isOnLine,
@RequestParam String savePointPath) {
if (isOnLine) {
return taskService.reOnLineTask(id, savePointPath);
} else {
......@@ -249,7 +257,7 @@ public class TaskController {
*/
@GetMapping(value = "/exportJsonByTaskId")
public Result exportJsonByTaskId(@RequestParam Integer id) {
return Result.succeed(taskService.exportJsonByTaskId(id),"获取成功");
return Result.succeed(taskService.exportJsonByTaskId(id), "获取成功");
}
/**
......@@ -257,7 +265,7 @@ public class TaskController {
*/
@PostMapping(value = "/exportJsonByTaskIds")
public Result exportJsonByTaskIds(@RequestBody JsonNode para) {
return Result.succeed(taskService.exportJsonByTaskIds(para),"获取成功");
return Result.succeed(taskService.exportJsonByTaskIds(para), "获取成功");
}
/**
......@@ -285,24 +293,23 @@ public class TaskController {
* @return
*/
@GetMapping("/queryOnClickOperatingTask")
public Result<List<Task>> queryOnClickOperatingTask(@RequestParam("operating") Integer operating
, @RequestParam("catalogueId") Integer catalogueId) {
public Result<List<Task>> queryOnClickOperatingTask(@RequestParam("operating") Integer operating,
@RequestParam("catalogueId") Integer catalogueId) {
if (operating == null) {
return Result.failed("操作不正确");
}
switch (operating) {
case 1:
return taskService.queryOnLineTaskByDoneStatus(Arrays.asList(JobLifeCycle.RELEASE)
, JobStatus.getAllDoneStatus(), true, catalogueId);
return taskService.queryOnLineTaskByDoneStatus(Arrays.asList(JobLifeCycle.RELEASE),
JobStatus.getAllDoneStatus(), true, catalogueId);
case 2:
return taskService.queryOnLineTaskByDoneStatus(Arrays.asList(JobLifeCycle.ONLINE)
, Collections.singletonList(JobStatus.RUNNING), false, catalogueId);
return taskService.queryOnLineTaskByDoneStatus(Arrays.asList(JobLifeCycle.ONLINE),
Collections.singletonList(JobStatus.RUNNING), false, catalogueId);
default:
return Result.failed("操作不正确");
}
}
/**
* 一键操作任务
*
......@@ -317,8 +324,9 @@ public class TaskController {
switch (operating.get("operating").asInt()) {
case 1:
final JsonNode savepointSelect = operating.get("taskOperatingSavepointSelect");
return TaskOneClickOperatingUtil.oneClickOnline(TaskOneClickOperatingUtil.parseJsonNode(operating)
, TaskOperatingSavepointSelect.valueByCode(savepointSelect == null ? 0 : savepointSelect.asInt()));
return TaskOneClickOperatingUtil.oneClickOnline(TaskOneClickOperatingUtil.parseJsonNode(operating),
TaskOperatingSavepointSelect
.valueByCode(savepointSelect == null ? 0 : savepointSelect.asInt()));
case 2:
return TaskOneClickOperatingUtil.onClickOffline(TaskOneClickOperatingUtil.parseJsonNode(operating));
default:
......@@ -326,7 +334,6 @@ public class TaskController {
}
}
/**
* 查询一键操作任务状态
*
......@@ -338,4 +345,3 @@ public class TaskController {
}
}
......@@ -20,8 +20,10 @@
package com.dlink.init;
import com.dlink.assertion.Asserts;
import com.dlink.context.TenantContextHolder;
import com.dlink.daemon.task.DaemonFactory;
import com.dlink.daemon.task.DaemonTaskConfig;
import com.dlink.function.pool.UdfCodePool;
import com.dlink.job.FlinkJobTask;
import com.dlink.model.JobInstance;
import com.dlink.model.Tenant;
......@@ -33,9 +35,11 @@ import com.dlink.service.JobInstanceService;
import com.dlink.service.SysConfigService;
import com.dlink.service.TaskService;
import com.dlink.service.TenantService;
import com.dlink.utils.UDFUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -79,6 +83,7 @@ public class SystemInit implements ApplicationRunner {
}
initTaskMonitor();
initDolphinScheduler();
registerUDF();
}
/**
......@@ -121,4 +126,12 @@ public class SystemInit implements ApplicationRunner {
}
return project;
}
public void registerUDF() {
// 设置admin用户 ,获取全部的udf代码,此地方没有租户隔离
TenantContextHolder.set(1);
UdfCodePool
.registerPool(taskService.getAllUDF().stream().map(UDFUtils::taskToUDF).collect(Collectors.toList()));
TenantContextHolder.set(null);
}
}
......@@ -19,17 +19,10 @@
package com.dlink.service;
import com.dlink.job.JobConfig;
/**
* @author ZackYoung
* @since 0.6.8
*/
public interface UDFService {
/**
* @param statement sql语句
* @param config job配置
*/
void init(String statement, JobConfig config);
}
......@@ -181,8 +181,6 @@ public class StudioServiceImpl implements StudioService {
process.info("Initializing Flink job config...");
JobConfig config = studioExecuteDTO.getJobConfig();
buildSession(config);
// init UDF
udfService.init(studioExecuteDTO.getStatement(), config);
JobManager jobManager = JobManager.build(config);
process.start();
JobResult jobResult = jobManager.executeSql(studioExecuteDTO.getStatement());
......@@ -269,8 +267,6 @@ public class StudioServiceImpl implements StudioService {
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to local.
config.buildLocal();
buildSession(config);
// init UDF
udfService.init(studioExecuteDTO.getStatement(), config);
JobManager jobManager = JobManager.build(config);
process.start();
List<SqlExplainResult> sqlExplainResults = jobManager.explainSql(studioExecuteDTO.getStatement())
......@@ -322,8 +318,6 @@ public class StudioServiceImpl implements StudioService {
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to local.
config.buildLocal();
buildSession(config);
// init UDF
udfService.init(studioExecuteDTO.getStatement(), config);
JobManager jobManager = JobManager.build(config);
......
......@@ -41,6 +41,7 @@ import com.dlink.dto.TaskRollbackVersionDTO;
import com.dlink.dto.TaskVersionConfigureDTO;
import com.dlink.exception.BusException;
import com.dlink.function.compiler.CustomStringJavaCompiler;
import com.dlink.function.pool.UdfCodePool;
import com.dlink.function.util.UDFUtil;
import com.dlink.gateway.Gateway;
import com.dlink.gateway.GatewayType;
......@@ -104,6 +105,7 @@ import com.dlink.service.UDFService;
import com.dlink.service.UDFTemplateService;
import com.dlink.utils.DockerClientUtils;
import com.dlink.utils.JSONUtil;
import com.dlink.utils.UDFUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
......@@ -231,8 +233,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
}
process.info("Initializing Flink job config...");
JobConfig config = buildJobConfig(task);
// init UDF
udfService.init(task.getStatement(), config);
if (GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) {
loadDocker(id, config.getClusterConfigurationId(), config.getGatewayConfig());
......@@ -449,6 +449,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} else if (Dialect.SCALA.equalsVal(task.getDialect())) {
task.setSavePointPath(UDFUtil.getScalaFullClassName(task.getStatement()));
}
UdfCodePool.addOrUpdate(UDFUtils.taskToUDF(task));
}
// if modify task else create task
......@@ -586,7 +587,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Task task = getOne(
new QueryWrapper<Task>().in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON).eq("enabled", 1)
.eq("save_point_path", className));
Asserts.checkNull(task,StrUtil.format("class: {} ,not exists!",className));
Asserts.checkNull(task, StrUtil.format("class: {} ,not exists!", className));
task.setStatement(statementService.getById(task.getId()).getStatement());
return task;
}
......
......@@ -19,17 +19,10 @@
package com.dlink.service.impl;
import com.dlink.classloader.DinkyClassLoader;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.job.JobConfig;
import com.dlink.service.UDFService;
import com.dlink.utils.UDFUtils;
import org.springframework.stereotype.Service;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.6.8
......@@ -37,30 +30,4 @@ import cn.hutool.core.util.StrUtil;
@Service
public class UDFServiceImpl implements UDFService {
/**
* 获取所有udf相关的代码
*
* @param statement sql语句
* @return jobManage
*/
@Override
public void init(String statement, JobConfig config) {
initClassLoader(config);
config.setUdfList(UDFUtils.getUDF(statement));
}
private void initClassLoader(JobConfig config) {
DinkyClassLoader classLoader = new DinkyClassLoader(null, Thread.currentThread().getContextClassLoader());
DinkyClassLoaderContextHolder.set(classLoader);
if (CollUtil.isNotEmpty(config.getConfig())) {
String pipelineJars = config.getConfig().get("pipeline.jars");
// add custom jar path
if (StrUtil.isNotBlank(pipelineJars)) {
String[] paths = pipelineJars.split(",");
DinkyClassLoaderContextHolder.get().addURL(paths);
}
}
}
}
......@@ -19,9 +19,10 @@
package com.dlink.utils;
import com.dlink.constant.FlinkSQLConstant;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.context.JarPathContextHolder;
import com.dlink.exception.BusException;
import com.dlink.function.context.UDFPathContextHolder;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
import com.dlink.model.Task;
......@@ -37,8 +38,10 @@ import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ReUtil;
......@@ -51,50 +54,48 @@ import cn.hutool.extra.spring.SpringUtil;
*/
public class UDFUtils extends UDFUtil {
private static final String FUNCTION_SQL_REGEX = "(--\\s+)?create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?;";
public static List<UDF> getUDF(String statement) {
String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement), FlinkSQLConstant.SEPARATOR);
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).stream()
.filter(x -> !x.contains("--"))
.filter(x -> !ClassLoaderUtil.isPresent(x))
.collect(Collectors.toList());
List<UDF> udfList = udfSqlList.stream().map(sql -> {
List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(pattern, sql));
String udfName = groups.get(1);
String className = groups.get(2);
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
try {
UDFPathContextHolder.add(
DinkyClassLoaderContextHolder.get().loadClass(className).getProtectionDomain()
.getCodeSource().getLocation().getPath());
} catch (ClassNotFoundException e) {
throw new DinkyException(e);
}
return null;
}
List<UDF> udfList = Stream.of(statements).map(s -> ReUtil.findAll(FUNCTION_SQL_REGEX, s, 0))
.filter(CollUtil::isNotEmpty)
.map(x -> x.get(0))
.map(sql -> {
List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(pattern, sql));
String udfName = groups.get(1);
String className = groups.get(2);
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
try {
JarPathContextHolder.addUdfPath(
FileUtil.file(DinkyClassLoaderContextHolder.get().loadClass(className)
.getProtectionDomain()
.getCodeSource().getLocation().getPath()));
} catch (ClassNotFoundException e) {
throw new DinkyException(e);
}
return null;
}
Task task = null;
try {
task = SpringUtil.getBean(TaskService.class).getUDFByClassName(className);
} catch (Exception e) {
String errMsg = StrUtil.format("class:{} not exists!", className);
process.error(errMsg);
throw new BusException(errMsg);
}
String code = task.getStatement();
return UDF.builder()
.name(udfName)
.className(className)
.code(code)
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()))
.build();
}).filter(Objects::nonNull).collect(Collectors.toList());
Task task = null;
try {
task = SpringUtil.getBean(TaskService.class).getUDFByClassName(className);
} catch (Exception e) {
String errMsg = StrUtil.format("class:{} not exists!", className);
process.error(errMsg);
throw new BusException(errMsg);
}
String code = task.getStatement();
return UDF.builder()
.name(udfName)
.className(className)
.code(code)
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()))
.build();
}).filter(Objects::nonNull).collect(Collectors.toList());
List<String> classNameList = udfList.stream().map(UDF::getClassName).collect(Collectors.toList());
if (classNameList.size() > 0) {
process.info(StringUtils.join(classNameList, ","));
......@@ -103,4 +104,12 @@ public class UDFUtils extends UDFUtil {
return udfList;
}
public static UDF taskToUDF(Task task) {
return UDF.builder()
.className(task.getSavePointPath())
.code(task.getStatement())
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()))
.build();
}
}
......@@ -2,6 +2,7 @@
ARG FLINK_VERSION=1.14.5
FROM flink:${FLINK_VERSION}
ARG FLINK_VERSION
ENV PYTHON_HOME /opt/miniconda3
USER root
......
......@@ -44,6 +44,15 @@
<groupId>com.dlink</groupId>
<artifactId>dlink-executor</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<profiles>
......
......@@ -29,17 +29,19 @@ import com.dlink.interceptor.FlinkInterceptor;
import com.dlink.parser.SqlType;
import com.dlink.trans.Operations;
import com.dlink.utils.SqlUtil;
import com.dlink.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.util.FlinkUserCodeClassLoader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
......@@ -51,10 +53,14 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
/**
* FlinkSQLFactory
*
......@@ -78,8 +84,8 @@ public class Submiter {
throw new SQLException("请指定任务ID");
}
return "select id, name, alias as jobName, type,check_point as checkpoint,"
+ "save_point_path as savePointPath, parallelism,fragment as useSqlFragment,statement_set as useStatementSet,config_json as config,"
+ " env_id as envId,batch_model AS useBatchModel from dlink_task where id = " + id;
+ "save_point_path as savePointPath, parallelism,fragment as useSqlFragment,statement_set as useStatementSet,config_json as config,"
+ " env_id as envId,batch_model AS useBatchModel from dlink_task where id = " + id;
}
private static String getFlinkSQLStatement(Integer id, DBConfig config) {
......@@ -88,7 +94,7 @@ public class Submiter {
statement = DBUtil.getOneByID(getQuerySQL(id), config);
} catch (IOException | SQLException e) {
logger.error("{} --> 获取 FlinkSQL 配置异常,ID 为 {}, 连接信息为:{} ,异常信息为:{} ", LocalDateTime.now(), id,
config.toString(), e.getMessage(), e);
config.toString(), e.getMessage(), e);
}
return statement;
}
......@@ -99,7 +105,7 @@ public class Submiter {
task = DBUtil.getMapByID(getTaskInfo(id), config);
} catch (IOException | SQLException e) {
logger.error("{} --> 获取 FlinkSQL 配置异常,ID 为 {}, 连接信息为:{} ,异常信息为:{} ", LocalDateTime.now(), id,
config.toString(), e.getMessage(), e);
config.toString(), e.getMessage(), e);
}
return task;
}
......@@ -123,7 +129,7 @@ public class Submiter {
}
} catch (IOException | SQLException e) {
logger.error("{} --> 获取 数据源信息异常,请检查数据库连接,连接信息为:{} ,异常信息为:{}", LocalDateTime.now(),
dbConfig.toString(), e.getMessage(), e);
dbConfig.toString(), e.getMessage(), e);
}
return "";
......@@ -157,11 +163,11 @@ public class Submiter {
String uuid = UUID.randomUUID().toString().replace("-", "");
if (executorSetting.getConfig().containsKey(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key())) {
executorSetting.getConfig().put(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key(),
executorSetting.getConfig().get(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key()) + "/" + uuid);
executorSetting.getConfig().get(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key()) + "/" + uuid);
}
if (executorSetting.getConfig().containsKey(CheckpointingOptions.SAVEPOINT_DIRECTORY.key())) {
executorSetting.getConfig().put(CheckpointingOptions.SAVEPOINT_DIRECTORY.key(),
executorSetting.getConfig().get(CheckpointingOptions.SAVEPOINT_DIRECTORY.key()) + "/" + uuid);
executorSetting.getConfig().get(CheckpointingOptions.SAVEPOINT_DIRECTORY.key()) + "/" + uuid);
}
logger.info("作业配置如下: {}", executorSetting);
Executor executor = Executor.buildAppStreamExecutor(executorSetting);
......@@ -241,15 +247,26 @@ public class Submiter {
try {
String httpJar = "http://" + dinkyAddr + "/download/downloadDepJar/" + taskId;
logger.info("下载依赖 http-url为:{}", httpJar);
URLClassLoader urlClassLoader =
FlinkUserCodeClassLoader.newInstance(new URL[] {new URL(httpJar)}, Thread.currentThread().getContextClassLoader());
String flinkHome = System.getenv("FLINK_HOME");
String usrlib = flinkHome + "/usrlib";
FileUtils.forceMkdir(new File(usrlib));
String udfJarPath = usrlib + "/udf.jar";
downloadFile(httpJar, udfJarPath);
executorSetting.getConfig().put(PipelineOptions.JARS.key(), "file://" + udfJarPath);
Thread.currentThread().setContextClassLoader(urlClassLoader);
String depZip = flinkHome + "/dep.zip";
downloadFile(httpJar, depZip);
String depPath = flinkHome + "/dep";
ZipUtils.unzip(depZip, depPath);
// move all jar
FileUtil.listFileNames(depPath + "/jar").forEach(f -> {
FileUtil.moveContent(FileUtil.file(depPath + "/jar/" + f), FileUtil.file(usrlib + "/" + f), true);
});
URL[] jarUrls = FileUtil.listFileNames(usrlib)
.stream().map(f -> URLUtil.getURL(FileUtil.file(usrlib, f)))
.toArray(URL[]::new);
addURLs(jarUrls);
executorSetting.getConfig().put(PipelineOptions.JARS.key(),
Arrays.stream(jarUrls).map(URL::toString).collect(Collectors.joining(";")));
// download python_udf.zip
String httpPythonZip = "http://" + dinkyAddr + "/download/downloadPythonUDF/" + taskId;
......@@ -262,15 +279,29 @@ public class Submiter {
executorSetting.getConfig().put("python.files", "./python_udf.zip");
}
private static void addURLs(URL[] jarUrls) {
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Method add = null;
try {
add = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
add.setAccessible(true);
for (URL jarUrl : jarUrls) {
add.invoke(urlClassLoader, jarUrl);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static void downloadFile(String url, String path) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
//获取输入流
// 获取输入流
InputStream inputStream = conn.getInputStream();
//获取输出流
// 获取输出流
FileOutputStream outputStream = new FileOutputStream(path);
//每次下载1024位
// 每次下载1024位
byte[] b = new byte[1024];
int len = -1;
while ((len = inputStream.read(b)) != -1) {
......
......@@ -19,11 +19,15 @@
package com.dlink.classloader;
import com.dlink.context.JarPathContextHolder;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.util.Collection;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
......@@ -35,15 +39,27 @@ import lombok.extern.slf4j.Slf4j;
public class DinkyClassLoader extends URLClassLoader {
public DinkyClassLoader(URL[] urls, ClassLoader parent) {
super(new URL[] {}, parent);
super(new URL[]{}, parent);
}
public DinkyClassLoader(Collection<File> fileSet, ClassLoader parent) {
super(new URL[]{}, parent);
URL[] urls = fileSet.stream().map(x -> {
try {
return x.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}).toArray(URL[]::new);
addURL(urls);
}
public DinkyClassLoader(URL[] urls) {
super(new URL[] {});
super(new URL[]{});
}
public DinkyClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(new URL[] {}, parent, factory);
super(new URL[]{}, parent, factory);
}
public void addURL(URL... urls) {
......@@ -52,14 +68,25 @@ public class DinkyClassLoader extends URLClassLoader {
}
}
public void addURL(String... paths) {
public void addURL(String[] paths, List<String> notExistsFiles) {
for (String path : paths) {
File file = new File(path);
try {
if (!file.exists()) {
if (notExistsFiles != null && !notExistsFiles.isEmpty()) {
notExistsFiles.add(file.getAbsolutePath());
}
return;
}
super.addURL(file.toURI().toURL());
JarPathContextHolder.addOtherPlugins(file);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
public void addURL(String... paths) {
this.addURL(paths, null);
}
}
/*
*
* 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.context;
import java.io.File;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class JarPathContextHolder {
private static final ThreadLocal<Set<File>> UDF_PATH_CONTEXT = new ThreadLocal<>();
private static final ThreadLocal<Set<File>> OTHER_PLUGINS_PATH_CONTEXT = new ThreadLocal<>();
public static void addUdfPath(File file) {
getUdfFile().add(file);
}
public static void addOtherPlugins(File file) {
getOtherPluginsFiles().add(file);
}
public static Set<File> getUdfFile() {
if (UDF_PATH_CONTEXT.get() == null) {
UDF_PATH_CONTEXT.set(new CopyOnWriteArraySet<>());
}
return UDF_PATH_CONTEXT.get();
}
public static Set<File> getOtherPluginsFiles() {
if (OTHER_PLUGINS_PATH_CONTEXT.get() == null) {
OTHER_PLUGINS_PATH_CONTEXT.set(new CopyOnWriteArraySet<>());
}
return OTHER_PLUGINS_PATH_CONTEXT.get();
}
public static void clear() {
UDF_PATH_CONTEXT.remove();
OTHER_PLUGINS_PATH_CONTEXT.remove();
}
}
/*
*
* 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 java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class URLUtils {
/**
* 获得URL,常用于使用绝对路径时的情况
*
* @param files URL对应的文件对象
* @return URL
*/
public static URL[] getURLs(File... files) {
final URL[] urls = new URL[files.length];
try {
for (int i = 0; i < files.length; i++) {
urls[i] = files[i].toURI().toURL();
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return urls;
}
/**
* 获得URL,常用于使用绝对路径时的情况
*
* @param files URL对应的文件对象
* @return URL
*/
public static URL[] getURLs(Set<File> files) {
return getURLs(files.stream().filter(File::exists).toArray(File[]::new));
}
public static String toString(URL[] urls) {
return Arrays.stream(urls).map(URL::toString).collect(Collectors.joining(","));
}
}
/*
*
* 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 org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Enumeration;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.7.0
*/
@Slf4j
public class ZipUtils {
public static void unzip(String zipFile, String dir) {
try (ZipFile zip = new ZipFile(zipFile)) {
Enumeration<ZipArchiveEntry> entries = zip.getEntries();
while (entries.hasMoreElements()) {
ZipArchiveEntry zipArchiveEntry = entries.nextElement();
File file = new File(dir, zipArchiveEntry.getName());
writeFile(file, zip.getInputStream(zipArchiveEntry));
log.info("======解压成功=======,file:{}", file.getAbsolutePath());
}
} catch (IOException e) {
log.error("压缩包处理异常,异常信息:", e);
}
}
private static void writeFile(File file, InputStream inputStream) {
if (!file.exists()) {
file.getParentFile().mkdirs();
}
if (file.isDirectory()) {
return;
}
try (OutputStream outputStream = new FileOutputStream(file)) {
byte[] bytes = new byte[4096];
int len;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
// unzip("/Users/zackyoung/Downloads/85.zip", "/Users/zackyoung/Downloads/85");
Files.move(Paths.get("/Users/zackyoung/Downloads/85/jar/"), Paths.get("/Users/zackyoung/Downloads/85/123/"));
}
}
......@@ -21,6 +21,8 @@ package com.dlink.explainer;
import com.dlink.assertion.Asserts;
import com.dlink.constant.FlinkSQLConstant;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.context.JarPathContextHolder;
import com.dlink.executor.Executor;
import com.dlink.explainer.ca.ColumnCA;
import com.dlink.explainer.ca.ColumnCAResult;
......@@ -32,12 +34,15 @@ import com.dlink.explainer.lineage.LineageColumnGenerator;
import com.dlink.explainer.lineage.LineageTableGenerator;
import com.dlink.explainer.trans.Trans;
import com.dlink.explainer.trans.TransGenerator;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
import com.dlink.interceptor.FlinkInterceptor;
import com.dlink.job.JobParam;
import com.dlink.job.StatementParam;
import com.dlink.model.LineageRel;
import com.dlink.model.SystemConfiguration;
import com.dlink.parser.SqlType;
import com.dlink.parser.check.AddJarSqlParser;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
import com.dlink.result.ExplainResult;
......@@ -46,6 +51,7 @@ import com.dlink.trans.Operations;
import com.dlink.utils.FlinkUtil;
import com.dlink.utils.LogUtil;
import com.dlink.utils.SqlUtil;
import com.dlink.utils.URLUtils;
import org.apache.flink.runtime.rest.messages.JobPlanInfo;
import org.apache.flink.table.catalog.CatalogManager;
......@@ -58,6 +64,7 @@ import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
/**
......@@ -108,13 +115,18 @@ public class Explainer {
List<StatementParam> trans = new ArrayList<>();
List<StatementParam> execute = new ArrayList<>();
List<String> statementList = new ArrayList<>();
List<UDF> udfList = new ArrayList<>();
for (String item : statements) {
String statement = executor.pretreatStatement(item);
if (statement.isEmpty()) {
continue;
}
SqlType operationType = Operations.getOperationType(statement);
if (operationType.equals(SqlType.INSERT) || operationType.equals(SqlType.SELECT)
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParser.getAllFilePath(statement).forEach(JarPathContextHolder::addOtherPlugins);
DinkyClassLoaderContextHolder.get()
.addURL(URLUtils.getURLs(JarPathContextHolder.getOtherPluginsFiles()));
} else if (operationType.equals(SqlType.INSERT) || operationType.equals(SqlType.SELECT)
|| operationType.equals(SqlType.SHOW)
|| operationType.equals(SqlType.DESCRIBE) || operationType.equals(SqlType.DESC)) {
trans.add(new StatementParam(statement, operationType));
......@@ -125,11 +137,12 @@ public class Explainer {
} else if (operationType.equals(SqlType.EXECUTE)) {
execute.add(new StatementParam(statement, operationType));
} else {
udfList.add(UDFUtil.toUDF(statement));
ddl.add(new StatementParam(statement, operationType));
statementList.add(statement);
}
}
return new JobParam(statementList, ddl, trans, execute);
return new JobParam(statementList, ddl, trans, execute, CollUtil.removeNull(udfList));
}
public List<SqlExplainResult> explainSqlResult(String statement) {
......
......@@ -22,7 +22,6 @@ package com.dlink.job;
import com.dlink.assertion.Asserts;
import com.dlink.constant.NetConstant;
import com.dlink.executor.ExecutorSetting;
import com.dlink.function.data.model.UDF;
import com.dlink.gateway.GatewayType;
import com.dlink.gateway.config.AppConfig;
import com.dlink.gateway.config.ClusterConfig;
......@@ -68,7 +67,6 @@ public class JobConfig {
private boolean isJarTask = false;
private String address;
private Integer taskId;
private List<UDF> udfList;
private String[] jarFiles;
private String[] pyFiles;
private String jobName;
......
......@@ -25,13 +25,15 @@ import static com.dlink.function.util.UDFUtil.YARN;
import com.dlink.api.FlinkAPI;
import com.dlink.assertion.Asserts;
import com.dlink.classloader.DinkyClassLoader;
import com.dlink.constant.FlinkSQLConstant;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.context.JarPathContextHolder;
import com.dlink.executor.EnvironmentSetting;
import com.dlink.executor.Executor;
import com.dlink.executor.ExecutorSetting;
import com.dlink.explainer.Explainer;
import com.dlink.function.constant.PathConstant;
import com.dlink.function.context.UDFPathContextHolder;
import com.dlink.function.data.model.Env;
import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil;
......@@ -48,6 +50,7 @@ import com.dlink.interceptor.FlinkInterceptorResult;
import com.dlink.model.SystemConfiguration;
import com.dlink.parser.SqlType;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.exception.DinkyException;
import com.dlink.process.model.ProcessEntity;
import com.dlink.result.ErrorResult;
import com.dlink.result.ExplainResult;
......@@ -63,6 +66,7 @@ import com.dlink.session.SessionPool;
import com.dlink.trans.Operations;
import com.dlink.utils.LogUtil;
import com.dlink.utils.SqlUtil;
import com.dlink.utils.URLUtils;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.CoreOptions;
......@@ -73,12 +77,17 @@ import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.yarn.configuration.YarnConfigOptions;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
......@@ -94,6 +103,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
/**
* JobManager
......@@ -259,44 +271,59 @@ public class JobManager {
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
initExecutorSetting();
initUDF();
createExecutorWithSession();
return false;
}
private void initUDF() {
private void addConfigurationClsAndJars(List<URL> jarList, List<URL> classpaths) throws Exception {
Field configuration = StreamExecutionEnvironment.class.getDeclaredField("configuration");
configuration.setAccessible(true);
Configuration o = (Configuration) configuration.get(executor.getStreamExecutionEnvironment());
Field confData = Configuration.class.getDeclaredField("confData");
confData.setAccessible(true);
Map<String, Object> temp = (Map<String, Object>) confData.get(o);
temp.put(PipelineOptions.CLASSPATHS.key(), classpaths.stream().map(URL::toString).collect(Collectors.toList()));
temp.put(PipelineOptions.JARS.key(), jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
private void initUDF(List<UDF> udfList) {
ProcessEntity process = ProcessContextHolder.getProcess();
// 这里要分开
// 1. 得到jar包路径,注入remote环境
List<UDF> udfList = config.getUdfList();
Set<String> libUDFs = UDFPathContextHolder.get();
List<String> libHDFList = new ArrayList<>();
if (CollUtil.isNotEmpty(libUDFs)) {
libUDFs.forEach(path -> {
String destPath = PathConstant.getUdfPackagePath(config.getTaskId()) + "udf-lib-"
+ FileUtil.getName(path);
FileUtil.copy(path, destPath, true);
libHDFList.add(destPath);
});
} else if (CollUtil.isEmpty(udfList)) {
createExecutorWithSession();
return;
}
Set<File> jarFiles = JarPathContextHolder.getUdfFile();
Set<File> otherPluginsFiles = JarPathContextHolder.getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
CollUtil.addAll(libHDFList, UDFUtil.initJavaUDF(udfList, runMode, config.getTaskId()));
List<File> udfJars = Arrays.stream(UDFUtil.initJavaUDF(udfList, runMode, config.getTaskId())).map(File::new)
.collect(Collectors.toList());
jarFiles.addAll(udfJars);
String[] jarPaths = CollUtil.removeEmpty(libHDFList).toArray(new String[]{});
String[] jarPaths = CollUtil.removeNull(jarFiles).stream().map(File::getAbsolutePath).toArray(String[]::new);
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths);
}
// 2.实例化remote环境
createExecutorWithSession();
// 3.编译python
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
writeManifest(config.getTaskId(), jarList);
addConfigurationClsAndJars(jarList,
CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
logger.error("add configuration failed;reason:{}", LogUtil.getError(e));
throw new RuntimeException(e);
}
// 2.编译python
String[] pyPaths = UDFUtil.initPythonUDF(udfList, runMode, config.getTaskId(),
executor.getTableConfig().getConfiguration());
executor.initUDF(jarPaths);
executor.initPyUDF(Env.getPath(), pyPaths);
if (GATEWAY_TYPE_MAP.get(YARN).contains(runMode)) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(jarPaths, pyPaths));
......@@ -304,6 +331,14 @@ public class JobManager {
process.info("Initializing Flink UDF...Finish");
}
private void writeManifest(Integer taskId, List<URL> jarPaths) {
JSONArray array = new JSONArray(jarPaths.stream().map(URL::getFile).collect(Collectors.toList()));
JSONObject object = new JSONObject();
object.set("jars", array);
FileUtil.writeUtf8String(object.toStringPretty(),
PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST);
}
private boolean ready() {
return handler.init();
}
......@@ -321,7 +356,42 @@ public class JobManager {
return false;
}
private void initClassLoader(JobConfig config) {
if (CollUtil.isNotEmpty(config.getConfig())) {
String pipelineJars = config.getConfig().get(PipelineOptions.JARS.key());
String classpaths = config.getConfig().get(PipelineOptions.CLASSPATHS.key());
// add custom jar path
if (StrUtil.isNotBlank(pipelineJars)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
JarPathContextHolder.addUdfPath(file);
}
}
// add custom classpath
if (StrUtil.isNotBlank(classpaths)) {
String[] paths = pipelineJars.split(",");
for (String path : paths) {
File file = FileUtil.file(path);
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
JarPathContextHolder.addOtherPlugins(file);
}
}
}
DinkyClassLoader classLoader = new DinkyClassLoader(
CollUtil.addAll(JarPathContextHolder.getUdfFile(), JarPathContextHolder.getOtherPluginsFiles()),
Thread.currentThread().getContextClassLoader());
DinkyClassLoaderContextHolder.set(classLoader);
}
public JobResult executeSql(String statement) {
initClassLoader(config);
ProcessEntity process = ProcessContextHolder.getProcess();
Job job = Job.init(runMode, config, executorSetting, executor, statement, useGateway);
if (!useGateway) {
......@@ -333,6 +403,8 @@ public class JobManager {
JobParam jobParam = Explainer.build(executor, useStatementSet, sqlSeparator)
.pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator));
try {
initUDF(jobParam.getUdfList());
for (StatementParam item : jobParam.getDdl()) {
currentSql = item.getValue();
executor.executeSql(item.getValue());
......
......@@ -19,6 +19,8 @@
package com.dlink.job;
import com.dlink.function.data.model.UDF;
import java.util.ArrayList;
import java.util.List;
......@@ -29,21 +31,25 @@ import java.util.List;
* @since 2021/11/16
*/
public class JobParam {
private List<String> statements;
private List<StatementParam> ddl;
private List<StatementParam> trans;
private List<StatementParam> execute;
private List<UDF> udfList;
public JobParam(List<StatementParam> ddl, List<StatementParam> trans) {
this.ddl = ddl;
this.trans = trans;
}
public JobParam(List<String> statements, List<StatementParam> ddl, List<StatementParam> trans, List<StatementParam> execute) {
public JobParam(List<String> statements, List<StatementParam> ddl, List<StatementParam> trans,
List<StatementParam> execute, List<UDF> udfList) {
this.statements = statements;
this.ddl = ddl;
this.trans = trans;
this.execute = execute;
this.udfList = udfList;
}
public List<String> getStatements() {
......@@ -68,7 +74,7 @@ public class JobParam {
public List<String> getTransStatement() {
List<String> statementList = new ArrayList<>();
for (StatementParam statementParam: trans) {
for (StatementParam statementParam : trans) {
statementList.add(statementParam.getValue());
}
return statementList;
......@@ -85,4 +91,8 @@ public class JobParam {
public void setExecute(List<StatementParam> execute) {
this.execute = execute;
}
public List<UDF> getUdfList() {
return udfList;
}
}
......@@ -48,8 +48,6 @@ import org.apache.hadoop.security.UserGroupInformation;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -329,33 +327,6 @@ public abstract class Executor {
update(executorSetting);
}
private static void loadJar(final URL jarUrl) {
// 从URLClassLoader类加载器中获取类的addURL方法
Method method = null;
try {
method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
} catch (NoSuchMethodException | SecurityException e) {
logger.error(e.getMessage());
}
// 获取方法的访问权限
boolean accessible = method.isAccessible();
try {
// 修改访问权限为可写
if (!accessible) {
method.setAccessible(true);
}
// 获取系统类加载器
URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
// jar路径加入到系统url路径里
method.invoke(classLoader, jarUrl);
} catch (Exception e) {
logger.error(e.getMessage());
} finally {
method.setAccessible(accessible);
}
}
public String explainSql(String statement, ExplainDetail... extraDetails) {
statement = pretreatStatement(statement);
if (pretreatExecute(statement).isNoExecute()) {
......
......@@ -37,9 +37,11 @@ public class RemoteBatchExecutor extends Executor {
this.executorSetting = executorSetting;
if (Asserts.isNotNull(executorSetting.getConfig())) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig());
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(), environmentSetting.getPort(), configuration);
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(),
environmentSetting.getPort(), configuration, environmentSetting.getJarFiles());
} else {
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(), environmentSetting.getPort());
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(),
environmentSetting.getPort(), environmentSetting.getJarFiles());
}
init();
}
......
......@@ -22,7 +22,7 @@ package com.dlink.executor;
import com.dlink.assertion.Asserts;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.environment.RemoteStreamEnvironment;
/**
* RemoteStreamExecutor
......@@ -35,12 +35,12 @@ public class RemoteStreamExecutor extends Executor {
public RemoteStreamExecutor(EnvironmentSetting environmentSetting, ExecutorSetting executorSetting) {
this.environmentSetting = environmentSetting;
this.executorSetting = executorSetting;
if (Asserts.isNotNull(executorSetting.getConfig())) {
Configuration configuration = Configuration.fromMap(executorSetting.getConfig());
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(), environmentSetting.getPort(), configuration, environmentSetting.getJarFiles());
} else {
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(environmentSetting.getHost(), environmentSetting.getPort(), environmentSetting.getJarFiles());
}
Configuration configuration = Asserts.isNotNull(executorSetting.getConfig())
? Configuration.fromMap(executorSetting.getConfig())
: null;
this.environment = new RemoteStreamEnvironment(environmentSetting.getHost(), environmentSetting.getPort(),
configuration);
init();
}
......
......@@ -26,23 +26,11 @@ package com.dlink.parser;
* @since 2021/7/3 11:11
*/
public enum SqlType {
SELECT("SELECT"),
CREATE("CREATE"),
DROP("DROP"),
ALTER("ALTER"),
INSERT("INSERT"),
DESC("DESC"),
DESCRIBE("DESCRIBE"),
EXPLAIN("EXPLAIN"),
USE("USE"),
SHOW("SHOW"),
LOAD("LOAD"),
UNLOAD("UNLOAD"),
SET("SET"),
RESET("RESET"),
EXECUTE("EXECUTE"),
UNKNOWN("UNKNOWN"),
;
SELECT("SELECT"), CREATE("CREATE"), DROP("DROP"), ALTER("ALTER"), INSERT("INSERT"), DESC("DESC"), DESCRIBE(
"DESCRIBE"), EXPLAIN("EXPLAIN"), USE("USE"), SHOW("SHOW"), LOAD("LOAD"), UNLOAD(
"UNLOAD"), SET("SET"), RESET("RESET"), EXECUTE("EXECUTE"), ADD("ADD"), UNKNOWN("UNKNOWN"),
;
private String type;
......
/*
*
* 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.parser.check;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.exception.DinkyException;
import com.dlink.process.model.ProcessEntity;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class AddJarSqlParser {
private static final String ADD_JAR = "(add\\s+jar)\\s+'(.*.jar)'";
private static final Pattern ADD_JAR_PATTERN = Pattern.compile(ADD_JAR, Pattern.CASE_INSENSITIVE);
protected static List<String> patternStatements(String[] statements) {
return Stream.of(statements).filter(s -> ReUtil.isMatch(ADD_JAR_PATTERN, s))
.map(x -> ReUtil.findAllGroup0(ADD_JAR_PATTERN, x).get(0)).collect(Collectors.toList());
}
public static Set<File> getAllFilePath(String[] statements) {
Set<File> fileSet = new HashSet<>();
ProcessEntity process = ProcessContextHolder.getProcess();
patternStatements(statements).stream().map(x -> ReUtil.findAll(ADD_JAR_PATTERN, x, 2).get(0))
.distinct().forEach(path -> {
if (!FileUtil.exist(path)) {
throw new DinkyException(StrUtil.format("file : {} not exists!", path));
}
fileSet.add(FileUtil.file(path));
});
return fileSet;
}
public static Set<File> getAllFilePath(String statements) {
return getAllFilePath(new String[]{statements});
}
}
......@@ -20,6 +20,7 @@
package com.dlink.trans;
import com.dlink.parser.SqlType;
import com.dlink.trans.ddl.AddJarOperation;
import com.dlink.trans.ddl.CreateAggTableOperation;
import com.dlink.trans.ddl.CreateCDCSourceOperation;
import com.dlink.trans.ddl.SetOperation;
......@@ -39,11 +40,9 @@ public class Operations {
private Operations() {
}
private static final Operation[] ALL_OPERATIONS = {new CreateAggTableOperation()
, new SetOperation()
, new CreateCDCSourceOperation()
, new ShowFragmentsOperation()
, new ShowFragmentOperation()
private static final Operation[] ALL_OPERATIONS = {new CreateAggTableOperation(), new SetOperation(),
new CreateCDCSourceOperation(), new ShowFragmentsOperation(), new ShowFragmentOperation(),
new AddJarOperation()
};
public static SqlType getSqlTypeFromStatements(String statement) {
......
/*
*
* 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.trans.ddl;
import com.dlink.context.JarPathContextHolder;
import com.dlink.executor.Executor;
import com.dlink.parser.check.AddJarSqlParser;
import com.dlink.trans.AbstractOperation;
import com.dlink.trans.Operation;
import org.apache.flink.table.api.TableResult;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class AddJarOperation extends AbstractOperation implements Operation {
private static final String KEY_WORD = "ADD JAR";
public AddJarOperation(String statement) {
super(statement);
}
public AddJarOperation() {
}
@Override
public String getHandle() {
return KEY_WORD;
}
@Override
public Operation create(String statement) {
return new AddJarOperation(statement);
}
@Override
public TableResult build(Executor executor) {
return null;
}
public void init() {
AddJarSqlParser.getAllFilePath(statement).forEach(JarPathContextHolder::addOtherPlugins);
}
}
......@@ -21,7 +21,7 @@ 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 com.dlink.function.util.ZipWriter;
import org.apache.flink.table.catalog.FunctionLanguage;
......@@ -70,7 +70,7 @@ public class JVMPackage implements FunctionPackage {
// 编译好的文件打包jar
File file = FileUtil.file(jarPath);
FileUtil.del(file);
try (ZipUtils zipWriter = new ZipUtils(file, Charset.defaultCharset())) {
try (ZipWriter zipWriter = new ZipWriter(file, Charset.defaultCharset())) {
zipWriter.add(clazzs, fileInputStreams);
}
return new String[]{jarPath};
......
......@@ -24,7 +24,7 @@ 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.function.util.ZipWriter;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.model.ProcessEntity;
......@@ -71,7 +71,7 @@ public class PythonFunction implements FunctionCompiler, FunctionPackage {
process.info("正在编译 python 代码 , class: " + udf.getClassName());
File pyFile = FileUtil.writeUtf8String(udf.getCode(),
PathConstant.getUdfCompilerPythonPath(missionId, UDFUtil.getPyFileName(udf.getClassName()) + ".py"));
PathConstant.getUdfCompilerPythonPath(missionId, UDFUtil.getPyFileName(udf.getClassName()) + ".py"));
File zipFile = ZipUtil.zip(pyFile);
FileUtil.del(pyFile);
try {
......@@ -84,7 +84,7 @@ public class PythonFunction implements FunctionCompiler, FunctionPackage {
process.info("Python udf编译成功 ; className:" + udf.getClassName());
} catch (Exception e) {
process.error("Python udf编译失败 ; className:" + udf.getClassName() + " 。 原因: "
+ ExceptionUtil.getRootCauseMessage(e));
+ ExceptionUtil.getRootCauseMessage(e));
return false;
}
FileUtil.del(zipFile);
......@@ -97,8 +97,8 @@ public class PythonFunction implements FunctionCompiler, FunctionPackage {
return new String[0];
}
udfList = udfList.stream()
.filter(udf -> udf.getFunctionLanguage() == FunctionLanguage.PYTHON)
.collect(Collectors.toList());
.filter(udf -> udf.getFunctionLanguage() == FunctionLanguage.PYTHON)
.collect(Collectors.toList());
if (CollUtil.isEmpty(udfList)) {
return new String[0];
......@@ -106,18 +106,18 @@ public class PythonFunction implements FunctionCompiler, FunctionPackage {
InputStream[] inputStreams = udfList.stream().map(udf -> {
File file = FileUtil.writeUtf8String(udf.getCode(), PathConstant.getUdfCompilerPythonPath(missionId,
UDFUtil.getPyFileName(udf.getClassName()) + ".py"));
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[] 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())) {
try (ZipWriter zipWriter = new ZipWriter(file, Charset.defaultCharset())) {
zipWriter.add(paths, inputStreams);
}
return new String[] {path};
return new String[]{path};
}
}
......@@ -59,7 +59,8 @@ public class PathConstant {
*/
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_MANIFEST = "udf_manifest.json";
public static final String DEP_MANIFEST = "dep_manifest.json";
public static final String DEP_ZIP = "dep.zip";
public static final String UDF_PYTHON_NAME = "python_udf.zip";
/**
* udf jar tmp路径
......
package com.dlink.function.context;
import java.util.Set;
import cn.hutool.core.collection.ConcurrentHashSet;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class UDFPathContextHolder {
private static final ThreadLocal<Set<String>> UDF_PATH_CONTEXT = new ThreadLocal<>();
public static void add(String path) {
if (UDF_PATH_CONTEXT.get() == null) {
UDF_PATH_CONTEXT.set(new ConcurrentHashSet<>());
}
UDF_PATH_CONTEXT.get().add(path);
}
public static Set<String> get() {
return UDF_PATH_CONTEXT.get();
}
public static void clear() {
UDF_PATH_CONTEXT.remove();
}
}
/*
*
* 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.pool;
import com.dlink.function.data.model.UDF;
import com.dlink.process.exception.DinkyException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import cn.hutool.core.util.StrUtil;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class UdfCodePool {
/**
* udf code pool
* key -> class name
* value -> udf
*/
private static final Map<String, UDF> CODE_POOL = new ConcurrentHashMap<>();
public static void registerPool(List<UDF> udfList) {
CODE_POOL.clear();
CODE_POOL.putAll(udfList.stream().collect(Collectors.toMap(UDF::getClassName, udf -> udf)));
}
public static void addOrUpdate(UDF udf) {
CODE_POOL.put(udf.getClassName(), udf);
}
public static UDF getUDF(String className) {
UDF udf = CODE_POOL.get(className);
if (udf == null) {
throw new DinkyException(StrUtil.format("class: {} is not exists!", className));
}
return udf;
}
}
......@@ -21,14 +21,18 @@ package com.dlink.function.util;
import com.dlink.assertion.Asserts;
import com.dlink.config.Dialect;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.context.JarPathContextHolder;
import com.dlink.function.FunctionFactory;
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.function.pool.UdfCodePool;
import com.dlink.gateway.GatewayType;
import com.dlink.pool.ClassEntity;
import com.dlink.pool.ClassPool;
import com.dlink.process.exception.DinkyException;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.catalog.FunctionLanguage;
......@@ -41,6 +45,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.slf4j.Logger;
......@@ -52,6 +57,7 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
......@@ -68,6 +74,8 @@ import groovy.lang.GroovyClassLoader;
*/
public class UDFUtil {
public static final String FUNCTION_SQL_REGEX = "create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?";
public static final String SESSION = "SESSION";
public static final String YARN = "YARN";
public static final String APPLICATION = "APPLICATION";
......@@ -210,7 +218,7 @@ public class UDFUtil {
.map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class")
.map(FileUtil::getInputStream).toArray(InputStream[]::new);
// 编译好的文件打包jar
try (ZipUtils zipWriter = new ZipUtils(FileUtil.file(udfJarPath), Charset.defaultCharset())) {
try (ZipWriter zipWriter = new ZipWriter(FileUtil.file(udfJarPath), Charset.defaultCharset())) {
zipWriter.add(clazzs, fileInputStreams);
}
String md5 = md5sum(udfJarPath);
......@@ -272,4 +280,36 @@ public class UDFUtil {
return MD5.create().digestHex(FileUtil.file(filePath));
}
public static boolean isUdfStatement(String statement) {
return !StrUtil.isBlank(statement) && CollUtil.isNotEmpty(ReUtil.findAll(FUNCTION_SQL_REGEX, statement, 0));
}
public static UDF toUDF(String statement) {
if (isUdfStatement(statement)) {
Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE);
List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(pattern, statement));
String udfName = groups.get(1);
String className = groups.get(2);
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
try {
JarPathContextHolder.addUdfPath(
FileUtil.file(DinkyClassLoaderContextHolder.get().loadClass(className).getProtectionDomain()
.getCodeSource().getLocation().getPath()));
} catch (ClassNotFoundException e) {
throw new DinkyException(e);
}
return null;
}
UDF udf = UdfCodePool.getUDF(className);
return UDF.builder()
.name(udfName)
.className(className)
.code(udf.getCode())
.functionLanguage(udf.getFunctionLanguage())
.build();
}
return null;
}
}
......@@ -28,7 +28,6 @@ import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import cn.hutool.core.compress.ZipWriter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.io.IoUtil;
......@@ -41,22 +40,22 @@ import cn.hutool.core.util.StrUtil;
* @author ZackYoung
* @since 0.6.8
*/
public class ZipUtils extends ZipWriter {
public class ZipWriter extends cn.hutool.core.compress.ZipWriter {
public ZipUtils(File zipFile, Charset charset) {
public ZipWriter(File zipFile, Charset charset) {
super(zipFile, charset);
}
public ZipUtils(OutputStream out, Charset charset) {
public ZipWriter(OutputStream out, Charset charset) {
super(out, charset);
}
public ZipUtils(ZipOutputStream out) {
public ZipWriter(ZipOutputStream out) {
super(out);
}
@Override
public ZipWriter add(String[] paths, InputStream[] ins) throws IORuntimeException {
public cn.hutool.core.compress.ZipWriter add(String[] paths, InputStream[] ins) throws IORuntimeException {
if (ArrayUtil.isEmpty(paths) || ArrayUtil.isEmpty(ins)) {
throw new IllegalArgumentException("Paths or ins is empty !");
}
......@@ -71,7 +70,7 @@ public class ZipUtils extends ZipWriter {
return this;
}
public ZipWriter add(String path, InputStream in, long fileTime) throws IORuntimeException {
public cn.hutool.core.compress.ZipWriter add(String path, InputStream in, long fileTime) throws IORuntimeException {
path = StrUtil.nullToEmpty(path);
if (null == in) {
// 空目录需要检查路径规范性,目录以"/"结尾
......@@ -84,7 +83,8 @@ public class ZipUtils extends ZipWriter {
return putEntry(path, in, fileTime);
}
private ZipWriter putEntry(String path, InputStream in, long fileTime) throws IORuntimeException {
private cn.hutool.core.compress.ZipWriter putEntry(String path, InputStream in, long fileTime)
throws IORuntimeException {
try {
ZipEntry zipEntry = new ZipEntry(path);
zipEntry.setTime(fileTime);
......
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