Unverified Commit 05159fec authored by Licho's avatar Licho Committed by GitHub

refactor: refact UDF (#1908)

* refactor: refact UDF Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com>
parent 65ded4ca
...@@ -19,107 +19,15 @@ ...@@ -19,107 +19,15 @@
package org.dinky.utils; package org.dinky.utils;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.JarPathContextHolder;
import org.dinky.exception.BusException;
import org.dinky.function.data.model.UDF; import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil; import org.dinky.function.util.UDFUtil;
import org.dinky.model.Task; import org.dinky.model.Task;
import org.dinky.process.context.ProcessContextHolder;
import org.dinky.process.exception.DinkyException;
import org.dinky.process.model.ProcessEntity;
import org.dinky.service.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
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;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
/** @since 0.6.8 */ /** @since 0.6.8 */
public class UDFUtils extends UDFUtil { public class UDFUtils extends UDFUtil {
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<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());
List<String> classNameList =
udfList.stream().map(UDF::getClassName).collect(Collectors.toList());
if (classNameList.size() > 0) {
process.info(StringUtils.join(classNameList, ","));
}
process.info(
CharSequenceUtil.format(
"A total of {} UDF have been Parsed.", classNameList.size()));
return udfList;
}
public static UDF taskToUDF(Task task) { public static UDF taskToUDF(Task task) {
return UDF.builder() return UDF.builder()
.className(task.getSavePointPath()) .className(task.getSavePointPath())
......
...@@ -28,8 +28,10 @@ import java.util.concurrent.ConcurrentHashMap; ...@@ -28,8 +28,10 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/** @since 0.7.0 */ /** @since 0.7.0 */
@Slf4j
public class UdfCodePool { public class UdfCodePool {
/** udf code pool key -> class name value -> udf */ /** udf code pool key -> class name value -> udf */
...@@ -47,7 +49,9 @@ public class UdfCodePool { ...@@ -47,7 +49,9 @@ public class UdfCodePool {
public static UDF getUDF(String className) { public static UDF getUDF(String className) {
UDF udf = CODE_POOL.get(className); UDF udf = CODE_POOL.get(className);
if (udf == null) { if (udf == null) {
throw new DinkyException(StrUtil.format("class: {} is not exists!", className)); String error = StrUtil.format("class: {} is not exists!", className);
log.error(error);
throw new DinkyException(error);
} }
return udf; return udf;
} }
......
...@@ -47,7 +47,6 @@ import java.util.List; ...@@ -47,7 +47,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -64,7 +63,6 @@ import cn.hutool.crypto.digest.MD5; ...@@ -64,7 +63,6 @@ import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine; import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine;
import groovy.lang.GroovyClassLoader;
/** /**
* UDFUtil * UDFUtil
...@@ -75,6 +73,8 @@ public class UDFUtil { ...@@ -75,6 +73,8 @@ public class UDFUtil {
public static final String FUNCTION_SQL_REGEX = public static final String FUNCTION_SQL_REGEX =
"^CREATE\\s+(?:(?:TEMPORARY|TEMPORARY\\s+SYSTEM)\\s+)?FUNCTION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\S+)\\s+AS\\s+'(\\S+)'\\s*(?:LANGUAGE\\s+(?:JAVA|SCALA|PYTHON)\\s+)?(?:USING\\s+JAR\\s+'(\\S+)'\\s*(?:,\\s*JAR\\s+'(\\S+)'\\s*)*)?"; "^CREATE\\s+(?:(?:TEMPORARY|TEMPORARY\\s+SYSTEM)\\s+)?FUNCTION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\S+)\\s+AS\\s+'(\\S+)'\\s*(?:LANGUAGE\\s+(?:JAVA|SCALA|PYTHON)\\s+)?(?:USING\\s+JAR\\s+'(\\S+)'\\s*(?:,\\s*JAR\\s+'(\\S+)'\\s*)*)?";
public static final Pattern PATTERN =
Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE);
public static final String SESSION = "SESSION"; public static final String SESSION = "SESSION";
public static final String YARN = "YARN"; public static final String YARN = "YARN";
...@@ -102,8 +102,6 @@ public class UDFUtil { ...@@ -102,8 +102,6 @@ public class UDFUtil {
/** 存放 udf md5与版本对应的k,v值 */ /** 存放 udf md5与版本对应的k,v值 */
protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>(); protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>();
private static final String FUNCTION_REGEX = "function (.*?)'(.*?)'";
private static final String LANGUAGE_REGEX = "language (.*);";
public static final String PYTHON_UDF_ATTR = "(\\S)\\s+=\\s+ud(?:f|tf|af|taf)"; public static final String PYTHON_UDF_ATTR = "(\\S)\\s+=\\s+ud(?:f|tf|af|taf)";
public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):"; public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):";
public static final String SCALA_UDF_CLASS = "class\\s+(\\w+)(\\s*\\(.*\\)){0,1}\\s+extends"; public static final String SCALA_UDF_CLASS = "class\\s+(\\w+)(\\s*\\(.*\\)){0,1}\\s+extends";
...@@ -188,17 +186,6 @@ public class UDFUtil { ...@@ -188,17 +186,6 @@ public class UDFUtil {
return String.join(".", Arrays.asList(packageName, clazz)); return String.join(".", Arrays.asList(packageName, clazz));
} }
public static void initClassLoader(String name) {
ClassEntity classEntity = ClassPool.get(name);
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
CompilerConfiguration config = new CompilerConfiguration();
config.setSourceEncoding("UTF-8");
GroovyClassLoader groovyClassLoader = new GroovyClassLoader(contextClassLoader, config);
groovyClassLoader.setShouldRecompile(true);
groovyClassLoader.defineClass(classEntity.getName(), classEntity.getClassByte());
Thread.currentThread().setContextClassLoader(groovyClassLoader);
}
@Deprecated @Deprecated
public static Map<String, List<String>> buildJar(List<UDF> codeList) { public static Map<String, List<String>> buildJar(List<UDF> codeList) {
List<String> successList = new ArrayList<>(); List<String> successList = new ArrayList<>();
...@@ -215,12 +202,12 @@ public class UDFUtil { ...@@ -215,12 +202,12 @@ public class UDFUtil {
boolean res = compiler.compilerToTmpPath(tmpPath); boolean res = compiler.compilerToTmpPath(tmpPath);
String className = compiler.getFullClassName(); String className = compiler.getFullClassName();
if (res) { if (res) {
log.info("class编译成功:{}" + className); log.info("class compile successful:{}", className);
log.info("compilerTakeTime:" + compiler.getCompilerTakeTime()); log.info("compilerTakeTime:" + compiler.getCompilerTakeTime());
ClassPool.push(ClassEntity.build(className, udf.getCode())); ClassPool.push(ClassEntity.build(className, udf.getCode()));
successList.add(className); successList.add(className);
} else { } else {
log.warn("class编译失败:{}" + className); log.warn("class compile failed:{}", className);
log.warn(compiler.getCompilerMessage()); log.warn(compiler.getCompilerMessage());
failedList.add(className); failedList.add(className);
} }
...@@ -228,15 +215,16 @@ public class UDFUtil { ...@@ -228,15 +215,16 @@ public class UDFUtil {
String className = udf.getClassName(); String className = udf.getClassName();
if (CustomStringScalaCompiler.getInterpreter(null) if (CustomStringScalaCompiler.getInterpreter(null)
.compileString(udf.getCode())) { .compileString(udf.getCode())) {
log.info("scala class编译成功:{}" + className); log.info("scala class compile successful:{}", className);
ClassPool.push(ClassEntity.build(className, udf.getCode())); ClassPool.push(ClassEntity.build(className, udf.getCode()));
successList.add(className); successList.add(className);
} else { } else {
log.warn("scala class编译失败:{}" + className); log.warn("scala class compile failed:{}", className);
failedList.add(className); failedList.add(className);
} }
} }
}); });
String[] clazzs = String[] clazzs =
successList.stream() successList.stream()
.map(className -> StrUtil.replace(className, ".", "/") + ".class") .map(className -> StrUtil.replace(className, ".", "/") + ".class")
...@@ -246,6 +234,7 @@ public class UDFUtil { ...@@ -246,6 +234,7 @@ public class UDFUtil {
.map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class") .map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class")
.map(FileUtil::getInputStream) .map(FileUtil::getInputStream)
.toArray(InputStream[]::new); .toArray(InputStream[]::new);
// 编译好的文件打包jar // 编译好的文件打包jar
try (ZipWriter zipWriter = try (ZipWriter zipWriter =
new ZipWriter(FileUtil.file(udfJarPath), Charset.defaultCharset())) { new ZipWriter(FileUtil.file(udfJarPath), Charset.defaultCharset())) {
...@@ -267,21 +256,21 @@ public class UDFUtil { ...@@ -267,21 +256,21 @@ public class UDFUtil {
@Deprecated @Deprecated
public static String getUdfFileAndBuildJar(List<UDF> codeList) { public static String getUdfFileAndBuildJar(List<UDF> codeList) {
// 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过 // 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过
String md5 = buildJar(codeList).get("md5").get(0); FileUtil.mkdir(PathConstant.UDF_PATH);
if (!FileUtil.exist(PathConstant.UDF_PATH)) {
FileUtil.mkdir(PathConstant.UDF_PATH);
}
try { try {
// 获取所有的udf jar的 md5 值,放入 map 里面 // 获取所有的udf jar的 md5 值,放入 map 里面
if (UDF_MD5_MAP.isEmpty()) { if (UDF_MD5_MAP.isEmpty()) {
scanUDFMD5(); scanUDFMD5();
} }
// 2. 如果有匹配的,返回对应udf 版本,没有则构建jar,对应信息写入 jar // 2. 如果有匹配的,返回对应udf 版本,没有则构建jar,对应信息写入 jar
String md5 = buildJar(codeList).get("md5").get(0);
if (UDF_MD5_MAP.containsKey(md5)) { if (UDF_MD5_MAP.containsKey(md5)) {
FileUtil.del(PathConstant.UDF_JAR_TMP_PATH); FileUtil.del(PathConstant.UDF_JAR_TMP_PATH);
return StrUtil.format("udf-{}.jar", UDF_MD5_MAP.get(md5)); return StrUtil.format("udf-{}.jar", UDF_MD5_MAP.get(md5));
} }
// 3. 生成新版本jar // 3. 生成新版本jar
Integer newVersion = Integer newVersion =
UDF_MD5_MAP.values().size() > 0 ? CollUtil.max(UDF_MD5_MAP.values()) + 1 : 1; UDF_MD5_MAP.values().size() > 0 ? CollUtil.max(UDF_MD5_MAP.values()) + 1 : 1;
...@@ -323,9 +312,8 @@ public class UDFUtil { ...@@ -323,9 +312,8 @@ public class UDFUtil {
} }
public static UDF toUDF(String statement) { public static UDF toUDF(String statement) {
Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE); if (isUdfStatement(PATTERN, statement)) {
if (isUdfStatement(pattern, statement)) { List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(PATTERN, statement));
List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(pattern, statement));
String udfName = groups.get(1); String udfName = groups.get(1);
String className = groups.get(2); String className = groups.get(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