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

[Feature #1906][git] support python udf develop & auto upload (#1993)

* add py udf * fix log repeat * update sql &console * update sql &console
parent 4473c445
......@@ -23,8 +23,14 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import cn.hutool.system.SystemUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
/**
* Dinky 启动器
*
......@@ -33,9 +39,27 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@SpringBootApplication(exclude = FreeMarkerAutoConfiguration.class)
@EnableCaching
@Slf4j
public class Dinky {
@SneakyThrows
public static void main(String[] args) {
SpringApplication.run(Dinky.class, args);
String ipAddress = SystemUtil.getHostInfo().getAddress();
System.setProperty("ipAddr", ipAddress);
SpringApplication app = new SpringApplication(Dinky.class);
ConfigurableApplicationContext application = app.run(args);
Environment env = application.getEnvironment();
String port = env.getProperty("server.port");
log.info(
"\n----------------------------------------------------------\n\t"
+ "Application 'Dinky' is running! Access URLs:\n\t"
+ "Local: \t\thttp://localhost:{}\n\t"
+ "External: \thttp://{}:{}\n\t"
+ "Doc: \thttp://{}:{}/doc.html\n"
+ "----------------------------------------------------------",
port,
ipAddress,
port,
ipAddress,
port);
}
}
......@@ -60,6 +60,7 @@ public class UdfClassLoaderAspect {
if (!(e instanceof DinkyException)) {
throw new DinkyException(e);
}
e.printStackTrace();
throw (DinkyException) e;
} finally {
if (proceed instanceof JobResult) {
......
......@@ -23,6 +23,7 @@ import org.dinky.assertion.Asserts;
import org.dinky.exception.BusException;
import org.dinky.function.constant.PathConstant;
import org.dinky.function.util.ZipWriter;
import org.dinky.model.FlinkUdfManifest;
import java.io.File;
import java.io.InputStream;
......@@ -40,9 +41,9 @@ import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
/** @since 0.7.0 */
......@@ -61,34 +62,45 @@ public class DownloadController {
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());
FlinkUdfManifest flinkUdfManifest =
JSONUtil.toBean(FileUtil.readUtf8String(depManifestFile), FlinkUdfManifest.class);
List<String> filePath =
flinkUdfManifest.getJars().stream()
.map(Convert::toStr)
.collect(Collectors.toList());
List<String> pyFilePath =
flinkUdfManifest.getPythonFiles().stream()
.map(Convert::toStr)
.collect(Collectors.toList());
String[] jarNameList =
filePath.stream()
.map(FileUtil::getName)
.map(x -> "jar/" + x)
.toArray(String[]::new);
String[] pyFileNameList =
pyFilePath.stream()
.map(FileUtil::getName)
.map(x -> "py/" + x)
.toArray(String[]::new);
File zipFile = FileUtil.file(udfPackagePath + PathConstant.DEP_ZIP);
InputStream[] inputStreams =
filePath.stream().map(FileUtil::getInputStream).toArray(InputStream[]::new);
InputStream[] pyInputStreams =
pyFilePath.stream().map(FileUtil::getInputStream).toArray(InputStream[]::new);
try (ZipWriter zip = new ZipWriter(zipFile, Charset.defaultCharset())) {
zip.add(jarNameList, inputStreams);
if (ArrayUtil.isNotEmpty(jarNameList)) {
zip.add(jarNameList, inputStreams);
}
if (ArrayUtil.isNotEmpty(pyFileNameList)) {
zip.add(pyFileNameList, pyInputStreams);
}
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) {
ServletUtil.write(
resp,
FileUtil.file(
PathConstant.getUdfPackagePath(taskId) + PathConstant.UDF_PYTHON_NAME));
}
/**
* 提供docker通过http下载dinky-app.jar
*
......
......@@ -71,7 +71,7 @@ public class GitController {
* @return {@link Result} of {@link Void}
*/
@PutMapping("/saveOrUpdate")
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProject gitProject) {
public Result<Void> saveOrUpdate(@Validated @RequestBody GitProjectDTO gitProject) {
gitProjectService.saveOrUpdate(gitProject);
GitRepository gitRepository =
new GitRepository(BeanUtil.copyProperties(gitProject, GitProjectDTO.class));
......
......@@ -64,4 +64,6 @@ public class GitProjectDTO {
/** */
@NotNull private Boolean enabled;
private Integer orderLine;
}
......@@ -31,6 +31,7 @@ import org.dinky.scheduler.client.ProjectClient;
import org.dinky.scheduler.config.DolphinSchedulerProperties;
import org.dinky.scheduler.exception.SchedulerException;
import org.dinky.scheduler.model.Project;
import org.dinky.service.GitProjectService;
import org.dinky.service.JobInstanceService;
import org.dinky.service.SysConfigService;
import org.dinky.service.TaskService;
......@@ -67,6 +68,7 @@ public class SystemInit implements ApplicationRunner {
private final TaskService taskService;
private final TenantService tenantService;
private final DolphinSchedulerProperties dolphinSchedulerProperties;
private final GitProjectService gitProjectService;
private static Project project;
@Override
......@@ -125,6 +127,7 @@ public class SystemInit implements ApplicationRunner {
taskService.getAllUDF().stream()
.map(UDFUtils::taskToUDF)
.collect(Collectors.toList()));
UdfCodePool.updateGitPool(gitProjectService.getGitPool());
TenantContextHolder.set(null);
}
}
......@@ -92,6 +92,9 @@ public class GitProject extends SuperEntity<GitProject> {
@TableField(value = "udf_class_map_list")
private String udfClassMapList;
@TableField(value = "order_line")
private Integer orderLine;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
......
......@@ -25,6 +25,7 @@ import org.dinky.dto.TreeNodeDTO;
import org.dinky.model.GitProject;
import java.util.List;
import java.util.Map;
/**
* @author ZackYoung
......@@ -38,6 +39,8 @@ public interface GitProjectService extends ISuperService<GitProject> {
*/
void saveOrUpdate(GitProjectDTO gitProjectDTO);
Map<String, String> getGitPool();
/**
* 更新状态
*
......
......@@ -20,9 +20,11 @@
package org.dinky.service.impl;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.dto.GitAnalysisJarDTO;
import org.dinky.dto.GitProjectDTO;
import org.dinky.dto.JarClassesDTO;
import org.dinky.dto.TreeNodeDTO;
import org.dinky.function.pool.UdfCodePool;
import org.dinky.mapper.GitProjectMapper;
import org.dinky.model.GitProject;
import org.dinky.process.exception.DinkyException;
......@@ -34,7 +36,9 @@ import org.dinky.utils.TreeUtil;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
......@@ -43,6 +47,8 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
/**
......@@ -66,9 +72,55 @@ public class GitProjectServiceImpl extends SuperServiceImpl<GitProjectMapper, Gi
}
GitProject gitProject = BeanUtil.toBean(gitProjectDTO, GitProject.class);
if (gitProject.getOrderLine() == null) {
Integer maxOrderLine =
Opt.ofNullable(
baseMapper
.selectOne(
new LambdaQueryWrapper<GitProject>()
.orderByAsc(GitProject::getOrderLine)
.last(" limit 1"))
.getOrderLine())
.orElse(999);
gitProject.setOrderLine(maxOrderLine + 1);
}
BeanUtil.copyProperties(gitProjectDTO, gitProject);
gitProject.insertOrUpdate();
ThreadUtil.execAsync(() -> UdfCodePool.updateGitPool(getGitPool()));
}
@Override
public Map<String, String> getGitPool() {
List<GitProject> list = list();
Map<String, String> gitPool = new LinkedHashMap<>();
Opt.ofEmptyAble(list)
.ifPresent(
l -> {
for (GitProject gitProject : list) {
List<GitAnalysisJarDTO> gitAnalysisJarList =
JSONUtil.toList(
gitProject.getUdfClassMapList(),
GitAnalysisJarDTO.class);
for (GitAnalysisJarDTO analysisJarDTO : gitAnalysisJarList) {
analysisJarDTO
.getClassList()
.forEach(
udf -> {
gitPool.computeIfAbsent(
udf,
k -> analysisJarDTO.getJarPath());
});
}
}
});
return gitPool;
}
@Override
public List<GitProject> list() {
return list(new LambdaQueryWrapper<GitProject>().orderByAsc(GitProject::getOrderLine));
}
@Override
......@@ -87,7 +139,8 @@ public class GitProjectServiceImpl extends SuperServiceImpl<GitProjectMapper, Gi
@Override
public List<TreeNodeDTO> getProjectCode(Integer id) {
GitProject gitProject = getById(id);
File projectDir = GitRepository.getProjectDir(gitProject.getName());
File projectDir =
new File(GitRepository.getProjectDir(gitProject.getName()), gitProject.getBranch());
return TreeUtil.treeNodeData(projectDir, true);
}
......
......@@ -19,6 +19,9 @@
package org.dinky.sse;
import org.dinky.function.pool.UdfCodePool;
import org.dinky.service.GitProjectService;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
......@@ -26,6 +29,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.lang.Dict;
import cn.hutool.extra.spring.SpringUtil;
/**
* @author ZackYoung
......@@ -43,5 +47,10 @@ public class DoneStepSse extends StepSse {
}
@Override
public void exec() {}
public void exec() {
addFileMsgCusLog("Updating UDF pool");
GitProjectService gitProjectService = SpringUtil.getBean(GitProjectService.class);
UdfCodePool.updateGitPool(gitProjectService.getGitPool());
addFileMsgCusLog("The UDF pool has been updated");
}
}
......@@ -40,5 +40,7 @@
${ew.sqlSegment}
</if>
</where>
order by order_line asc
</select>
</mapper>
......@@ -35,6 +35,7 @@ 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.python.PythonOptions;
import java.io.File;
import java.io.FileOutputStream;
......@@ -59,6 +60,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.URLUtil;
/**
......@@ -286,37 +288,46 @@ public class Submitter {
FileUtils.forceMkdir(new File(usrlib));
String depZip = flinkHome + "/dep.zip";
downloadFile(httpJar, depZip);
boolean exists = downloadFile(httpJar, depZip);
if (exists) {
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);
URL[] pyUrls =
FileUtil.listFileNames(depPath + "/py/").stream()
.map(f -> URLUtil.getURL(FileUtil.file(depPath + "/py/", f)))
.toArray(URL[]::new);
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;
downloadFile(httpPythonZip, flinkHome + "/python_udf.zip");
addURLs(jarUrls);
executorSetting
.getConfig()
.put(
PipelineOptions.JARS.key(),
Arrays.stream(jarUrls)
.map(URL::toString)
.collect(Collectors.joining(";")));
if (ArrayUtil.isNotEmpty(pyUrls)) {
executorSetting
.getConfig()
.put(
PythonOptions.PYTHON_FILES.key(),
Arrays.stream(jarUrls)
.map(URL::toString)
.collect(Collectors.joining(",")));
}
}
} catch (IOException e) {
logger.error("");
throw new RuntimeException(e);
......@@ -339,21 +350,26 @@ public class Submitter {
}
}
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位
byte[] b = new byte[1024];
int len = -1;
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
public static boolean downloadFile(String url, String path) throws IOException {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// 设置超时间为3秒
conn.setConnectTimeout(3 * 1000);
// 获取输入流
InputStream inputStream = conn.getInputStream();
// 获取输出流
FileOutputStream outputStream = new FileOutputStream(path);
// 每次下载1024位
byte[] b = new byte[1024];
int len = -1;
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
return true;
} catch (Exception e) {
return false;
}
inputStream.close();
outputStream.close();
}
}
......@@ -19,7 +19,7 @@
package org.dinky.classloader;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import java.io.File;
import java.net.MalformedURLException;
......@@ -84,7 +84,7 @@ public class DinkyClassLoader extends URLClassLoader {
return;
}
super.addURL(file.toURI().toURL());
JarPathContextHolder.addOtherPlugins(file);
FlinkUdfPathContextHolder.addOtherPlugins(file);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
......
......@@ -24,15 +24,20 @@ import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/** @since 0.7.0 */
public class JarPathContextHolder {
public class FlinkUdfPathContextHolder {
private static final ThreadLocal<Set<File>> UDF_PATH_CONTEXT = new ThreadLocal<>();
private static final ThreadLocal<Set<File>> OTHER_PLUGINS_PATH_CONTEXT = new ThreadLocal<>();
private static final ThreadLocal<Set<File>> PYTHON_UDF_FILE = new ThreadLocal<>();
public static void addUdfPath(File file) {
getUdfFile().add(file);
}
public static void addPyUdfPath(File file) {
getPyUdfFile().add(file);
}
public static void addOtherPlugins(File file) {
getOtherPluginsFiles().add(file);
}
......@@ -44,6 +49,13 @@ public class JarPathContextHolder {
return UDF_PATH_CONTEXT.get();
}
public static Set<File> getPyUdfFile() {
if (PYTHON_UDF_FILE.get() == null) {
PYTHON_UDF_FILE.set(new CopyOnWriteArraySet<>());
}
return PYTHON_UDF_FILE.get();
}
public static Set<File> getOtherPluginsFiles() {
if (OTHER_PLUGINS_PATH_CONTEXT.get() == null) {
OTHER_PLUGINS_PATH_CONTEXT.set(new CopyOnWriteArraySet<>());
......
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.dinky.model;
import java.net.URL;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class FlinkUdfManifest {
private List<URL> jars;
private List<URL> pythonFiles;
}
......@@ -22,7 +22,7 @@ package org.dinky.explainer;
import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.executor.Executor;
import org.dinky.explainer.watchTable.WatchStatementExplainer;
......@@ -113,9 +113,9 @@ public class Explainer {
SqlType operationType = Operations.getOperationType(statement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParser.getAllFilePath(statement)
.forEach(JarPathContextHolder::addOtherPlugins);
.forEach(FlinkUdfPathContextHolder::addOtherPlugins);
DinkyClassLoaderContextHolder.get()
.addURL(URLUtils.getURLs(JarPathContextHolder.getOtherPluginsFiles()));
.addURL(URLUtils.getURLs(FlinkUdfPathContextHolder.getOtherPluginsFiles()));
} else if (operationType.equals(SqlType.ADD_JAR)) {
Configuration combinationConfig = getCombinationConfig();
FileSystem.initialize(combinationConfig, null);
......
......@@ -28,7 +28,7 @@ import org.dinky.assertion.Asserts;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.executor.EnvironmentSetting;
import org.dinky.executor.Executor;
......@@ -48,6 +48,7 @@ import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult;
import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.interceptor.FlinkInterceptorResult;
import org.dinky.model.FlinkUdfManifest;
import org.dinky.model.SystemConfiguration;
import org.dinky.parser.SqlType;
import org.dinky.process.context.ProcessContextHolder;
......@@ -102,8 +103,8 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
/**
* JobManager
......@@ -260,14 +261,7 @@ public class JobManager {
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);
Map<String, Object> temp = getFlinkConfigurationMap();
temp.put(
PipelineOptions.CLASSPATHS.key(),
classpaths.stream().map(URL::toString).collect(Collectors.toList()));
......@@ -276,6 +270,22 @@ public class JobManager {
jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
private Map<String, Object> getFlinkConfigurationMap() {
Field configuration = null;
try {
configuration = StreamExecutionEnvironment.class.getDeclaredField("configuration");
configuration.setAccessible(true);
Configuration o =
(Configuration) configuration.get(executor.getStreamExecutionEnvironment());
Field confData = Configuration.class.getDeclaredField("confData");
confData.setAccessible(true);
Map<String, Object> temp = (Map<String, Object>) confData.get(o);
return temp;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void initUDF(List<UDF> udfList) {
if (Asserts.isNotNullCollection(udfList)) {
initUDF(udfList, runMode, config.getTaskId());
......@@ -290,9 +300,9 @@ public class JobManager {
// 这里要分开
// 1. 得到jar包路径,注入remote环境
Set<File> jarFiles = JarPathContextHolder.getUdfFile();
Set<File> jarFiles = FlinkUdfPathContextHolder.getUdfFile();
Set<File> otherPluginsFiles = JarPathContextHolder.getOtherPluginsFiles();
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
List<File> udfJars =
......@@ -309,16 +319,6 @@ public class JobManager {
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths);
}
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
writeManifest(taskId, 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 =
......@@ -329,22 +329,50 @@ public class JobManager {
executor.getTableConfig().getConfiguration());
executor.initUDF(jarPaths);
if (ArrayUtil.isNotEmpty(pyPaths)) {
for (String pyPath : pyPaths) {
if (StrUtil.isNotBlank(pyPath)) {
FlinkUdfPathContextHolder.addPyUdfPath(new File(pyPath));
}
}
}
executor.initPyUDF(Env.getPath(), pyPaths);
Set<File> pyUdfFile = FlinkUdfPathContextHolder.getPyUdfFile();
executor.initPyUDF(
Env.getPath(),
pyUdfFile.stream().map(File::getAbsolutePath).toArray(String[]::new));
if (GATEWAY_TYPE_MAP.get(YARN).contains(runMode)) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(jarPaths, pyPaths));
}
process.info(StrUtil.format("A total of {} UDF have been Init.", udfList.size()));
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
// 3.写入udf所需文件
writeManifest(taskId, jarList);
addConfigurationClsAndJars(
jarList, CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
logger.error("add configuration failed;reason:{}", LogUtil.getError(e));
throw new RuntimeException(e);
}
process.info(
StrUtil.format(
"A total of {} UDF have been Init.", udfList.size() + pyUdfFile.size()));
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);
FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest();
flinkUdfManifest.setJars(jarPaths);
flinkUdfManifest.setPythonFiles(
FlinkUdfPathContextHolder.getPyUdfFile().stream()
.map(URLUtil::getURL)
.collect(Collectors.toList()));
FileUtil.writeUtf8String(
object.toStringPretty(),
JSONUtil.toJsonStr(flinkUdfManifest),
PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST);
}
......@@ -379,7 +407,7 @@ public class JobManager {
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
JarPathContextHolder.addUdfPath(file);
FlinkUdfPathContextHolder.addUdfPath(file);
}
}
// add custom classpath
......@@ -390,7 +418,7 @@ public class JobManager {
if (!file.exists()) {
throw new DinkyException("file: " + path + " .not exists! ");
}
JarPathContextHolder.addOtherPlugins(file);
FlinkUdfPathContextHolder.addOtherPlugins(file);
}
}
}
......@@ -398,8 +426,8 @@ public class JobManager {
DinkyClassLoaderContextHolder.get()
.addURL(
CollUtil.addAll(
JarPathContextHolder.getUdfFile(),
JarPathContextHolder.getOtherPluginsFiles()));
FlinkUdfPathContextHolder.getUdfFile(),
FlinkUdfPathContextHolder.getOtherPluginsFiles()));
}
public JobResult executeSql(String statement) {
......
......@@ -302,6 +302,14 @@ public abstract class Executor {
if (udfPyFilePath == null || udfPyFilePath.length == 0) {
return;
}
// if (MapUtil.isNotEmpty(setConfig)) {
// setConfig.put(PythonOptions.PYTHON_FILES.key(), String.join(",",
// udfPyFilePath));
// setConfig.put(PythonOptions.PYTHON_CLIENT_EXECUTABLE.key(), executable);
// Configuration configuration =
// Configuration.fromMap(executorSetting.getConfig());
// environment.getConfig().configure(configuration, null);
// }
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
configuration.setString(PythonOptions.PYTHON_FILES, String.join(",", udfPyFilePath));
configuration.setString(PythonOptions.PYTHON_CLIENT_EXECUTABLE, executable);
......
......@@ -19,7 +19,7 @@
package org.dinky.trans.ddl;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.executor.Executor;
import org.dinky.parser.check.AddJarSqlParser;
import org.dinky.trans.AbstractOperation;
......@@ -54,6 +54,7 @@ public class AddJarOperation extends AbstractOperation implements Operation {
}
public void init() {
AddJarSqlParser.getAllFilePath(statement).forEach(JarPathContextHolder::addOtherPlugins);
AddJarSqlParser.getAllFilePath(statement)
.forEach(FlinkUdfPathContextHolder::addOtherPlugins);
}
}
......@@ -36,11 +36,18 @@ public class UdfCodePool {
/** udf code pool key -> class name value -> udf */
private static final Map<String, UDF> CODE_POOL = new ConcurrentHashMap<>();
private static final Map<String, String> GIT_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 updateGitPool(Map<String, String> newPool) {
GIT_POOL.clear();
GIT_POOL.putAll(newPool);
}
public static void addOrUpdate(UDF udf) {
CODE_POOL.put(udf.getClassName(), udf);
}
......@@ -53,4 +60,8 @@ public class UdfCodePool {
}
return udf;
}
public static String getGitPackage(String className) {
return GIT_POOL.get(className);
}
}
......@@ -22,7 +22,7 @@ package org.dinky.function.util;
import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.function.FunctionFactory;
import org.dinky.function.compiler.CustomStringJavaCompiler;
import org.dinky.function.compiler.CustomStringScalaCompiler;
......@@ -344,7 +344,7 @@ public class UDFUtil {
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
try {
JarPathContextHolder.addUdfPath(
FlinkUdfPathContextHolder.addUdfPath(
FileUtil.file(
DinkyClassLoaderContextHolder.get()
.loadClass(className)
......@@ -367,6 +367,15 @@ public class UDFUtil {
.functionLanguage(udf.getFunctionLanguage())
.build();
}
String gitPackage = UdfCodePool.getGitPackage(className);
if (StrUtil.isNotBlank(gitPackage) && FileUtil.exist(gitPackage)) {
if (FileUtil.getSuffix(gitPackage).equals("jar")) {
FlinkUdfPathContextHolder.addUdfPath(new File(gitPackage));
} else {
FlinkUdfPathContextHolder.addPyUdfPath(new File(gitPackage));
}
}
}
return null;
}
......
# -*- coding: utf-8 -*-
import importlib
import sys
import platform
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.gateway.GatewayType;
import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.result.GatewayResult;
......@@ -36,10 +37,12 @@ import org.apache.flink.runtime.client.JobStatusMessage;
import org.apache.flink.yarn.YarnClusterDescriptor;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* YarnApplicationGateway
......@@ -63,6 +66,12 @@ public class YarnApplicationGateway extends YarnGateway {
configuration.set(
PipelineOptions.JARS, Collections.singletonList(appConfig.getUserJarPath()));
configuration.setString(
"python.files",
FlinkUdfPathContextHolder.getPyUdfFile().stream()
.map(File::getName)
.collect(Collectors.joining(",")));
String[] userJarParas =
Asserts.isNotNull(appConfig.getUserJarParas())
? appConfig.getUserJarParas()
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.gateway.AbstractGateway;
import org.dinky.gateway.config.ActionType;
import org.dinky.gateway.config.ClusterConfig;
......@@ -57,6 +58,7 @@ import org.apache.hadoop.yarn.exceptions.YarnException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.Executors;
......@@ -293,6 +295,8 @@ public abstract class YarnGateway extends AbstractGateway {
Arrays.stream(config.getJarPaths())
.map(FileUtil::file)
.collect(Collectors.toList()));
yarnClusterDescriptor.addShipFiles(
new ArrayList<>(FlinkUdfPathContextHolder.getPyUdfFile()));
}
return yarnClusterDescriptor;
}
......
......@@ -49,7 +49,7 @@ export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
modalVisible,
values,
} = props;
const [logList, setLogList] = useState<Record<number, string[]>>({});
let [logList, setLogList] = useState<Record<number, string[]>>({});
const [log, setLog] = useState<string>("");
const [currentStep, setCurrentStep] = useState<number>(0);
const [showList, setShowList] = useState<boolean>(false);
......@@ -96,7 +96,7 @@ export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
if (type === 0) {
if (execNum === 1) {
setLogList({});
logList={}
}
execNum++;
let parseResultData = JSON.parse(data); // parse data
......
......@@ -97,6 +97,7 @@ CREATE TABLE `dinky_git_project` (
`build_step` tinyint(2) NOT NULL DEFAULT '0',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0-disable 1-enable',
`udf_class_map_list` text COMMENT 'scan udf class',
`order_line` int(11) NOT NULL DEFAULT '1' COMMENT 'order',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time',
PRIMARY KEY (`id`) USING BTREE,
......
......@@ -50,5 +50,5 @@ update dinky_data_source set `type` = 'MySQL' where `type` = 'Mysql';
update dinky_data_source set `type` = 'PostgreSQL' where `type` = 'PostgreSql';
update dinky_data_source set `type` = 'SQLServer' where `type` = 'SqlServer';
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`) VALUES (1, 1, 'java-udf', 'https://github.com/zackyoungh/dinky-quickstart-java.git', 'master', NULL, NULL, NULL, NULL, '-P flink-1.14', 1, 1, NULL, NULL, 1, 0, 1, '');
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`) VALUES (2, 1, 'python-udf', 'https://github.com/zackyoungh/dinky-quickstart-python.git', 'master', NULL, NULL, NULL, NULL, '', 2, 1, NULL, NULL, 1, 0, 1, '');
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`, `order_line`) VALUES (1, 1, 'java-udf', 'https://github.com/zackyoungh/dinky-quickstart-java.git', 'master', NULL, NULL, NULL, NULL, '-P flink-1.14', 1, 1, NULL, NULL, 0, 0, 1, '[]', 1);
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`, `order_line`) VALUES (2, 1, 'python-udf', 'https://github.com/zackyoungh/dinky-quickstart-python.git', 'master', NULL, NULL, NULL, NULL, '', 2, 1, NULL, NULL, 0, 0, 1, '[]',2);
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