Unverified Commit 49b9197d authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Fix][UDF] fix udf in windows used. And JDK Classloader (#1400)

* 1. fix udf save 2. Fix that existing java classes cannot be used 3. Fix the coexistence problem of class loaders in jdk8 and jdk11 * spotless apply * spotless apply * spotless apply * spotless apply * Add classloaderAop: release the class instance of the new classloader when the task ends. Fix the second udf submission problem of windows * Add classloaderAop: release the class instance of the new classloader when the task ends. Fix the second udf submission problem of windows * Add classloaderAop: release the class instance of the new classloader when the task ends. Fix the second udf submission problem of windows * Add classloaderAop: release the class instance of the new classloader when the task ends. Fix the second udf submission problem of windows * Add classloaderAop: release the class instance of the new classloader when the task ends. Fix the second udf submission problem of windows
parent f9327d93
/*
*
* 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.aop;
import com.dlink.job.JobResult;
import java.io.IOException;
import java.net.URLClassLoader;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.web.embedded.tomcat.TomcatEmbeddedWebappClassLoader;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.7.0
*/
@Aspect
@Component
@Slf4j
public class UdfClassLoaderAspect {
@Pointcut("execution(* com.dlink.service.TaskService.*(..))")
public void taskServicePointcut() {
}
@Pointcut("execution(* com.dlink.service.APIService.*(..))")
public void apiServicePointcut() {
}
@Pointcut("execution(* com.dlink.service.StudioService.*(..))")
public void studioServicePointcut() {
}
@Pointcut("apiServicePointcut() || taskServicePointcut() || studioServicePointcut()")
public void allPointcut() {
}
@Around("allPointcut()")
public Object round(ProceedingJoinPoint proceedingJoinPoint) {
Object proceed = null;
ClassLoader initContextClassLoader = Thread.currentThread().getContextClassLoader();
try {
proceed = proceedingJoinPoint.proceed();
} catch (Throwable e) {
throw new RuntimeException(e);
} finally {
ClassLoader lastContextClassLoader = Thread.currentThread().getContextClassLoader();
if (!(lastContextClassLoader instanceof TomcatEmbeddedWebappClassLoader)) {
if (lastContextClassLoader.getParent() instanceof TomcatEmbeddedWebappClassLoader) {
if (proceed instanceof JobResult) {
Thread.currentThread().setContextClassLoader(initContextClassLoader);
try {
((URLClassLoader) lastContextClassLoader).close();
} catch (IOException e) {
log.error("卸载类失败,reason: {}", e.getMessage());
e.printStackTrace();
}
}
}
}
}
return proceed;
}
}
...@@ -428,9 +428,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -428,9 +428,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public boolean saveOrUpdateTask(Task task) { public boolean saveOrUpdateTask(Task task) {
if (CollUtil.isNotEmpty(task.getConfig()) && Dialect.isUDF(task.getDialect()) if (Dialect.isUDF(task.getDialect())) {
if (CollUtil.isNotEmpty(task.getConfig()) && Asserts.isNullString(task.getStatement())
&& Convert.toInt(task.getConfig().get(0).get("templateId"), 0) != 0) { && Convert.toInt(task.getConfig().get(0).get("templateId"), 0) != 0) {
if (Asserts.isNullString(task.getStatement())) {
Map<String, String> config = task.getConfig().get(0); Map<String, String> config = task.getConfig().get(0);
UDFTemplate template = udfTemplateService.getById(config.get("templateId")); UDFTemplate template = udfTemplateService.getById(config.get("templateId"));
if (template != null) { if (template != null) {
......
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package com.dlink.utils; package com.dlink.utils;
import com.dlink.exception.BusException;
import com.dlink.function.context.UDFPathContextHolder;
import com.dlink.function.data.model.UDF; import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil; import com.dlink.function.util.UDFUtil;
import com.dlink.model.Task; import com.dlink.model.Task;
...@@ -30,11 +32,16 @@ import org.apache.commons.lang3.StringUtils; ...@@ -30,11 +32,16 @@ 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.List;
import java.util.Objects;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil; import cn.hutool.extra.spring.SpringUtil;
/** /**
...@@ -43,18 +50,36 @@ import cn.hutool.extra.spring.SpringUtil; ...@@ -43,18 +50,36 @@ import cn.hutool.extra.spring.SpringUtil;
*/ */
public class UDFUtils extends UDFUtil { public class UDFUtils extends UDFUtil {
private static final String FUNCTION_SQL_REGEX = "create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?;"; private static final String FUNCTION_SQL_REGEX = "(--\\s+)?create\\s+.*function\\s+(.*)\\s+as\\s+'(.*)'(\\s+language (.*))?;";
public static List<UDF> getUDF(String statement) { public static List<UDF> getUDF(String statement) {
ProcessEntity process = ProcessContextHolder.getProcess(); ProcessEntity process = ProcessContextHolder.getProcess();
process.info("Parse UDF class name:"); process.info("Parse UDF class name:");
Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE); Pattern pattern = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE);
List<String> udfSqlList = ReUtil.findAllGroup0(pattern, statement); 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<UDF> udfList = udfSqlList.stream().map(sql -> {
List<String> groups = ReUtil.getAllGroups(pattern, sql); List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(pattern, sql));
String udfName = groups.get(1); String udfName = groups.get(1);
String className = groups.get(2); String className = groups.get(2);
Task task = SpringUtil.getBean(TaskService.class).getUDFByClassName(className); if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
UDFPathContextHolder.set(ReflectUtil.newInstance(className).getClass().getProtectionDomain()
.getCodeSource().getLocation().getPath());
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(); String code = task.getStatement();
return UDF.builder() return UDF.builder()
.name(udfName) .name(udfName)
...@@ -62,7 +87,7 @@ public class UDFUtils extends UDFUtil { ...@@ -62,7 +87,7 @@ public class UDFUtils extends UDFUtil {
.code(code) .code(code)
.functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase())) .functionLanguage(FunctionLanguage.valueOf(task.getDialect().toUpperCase()))
.build(); .build();
}).collect(Collectors.toList()); }).filter(Objects::nonNull).collect(Collectors.toList());
List<String> classNameList = udfList.stream().map(UDF::getClassName).collect(Collectors.toList()); List<String> classNameList = udfList.stream().map(UDF::getClassName).collect(Collectors.toList());
if (classNameList.size() > 0) { if (classNameList.size() > 0) {
process.info(StringUtils.join(classNameList, ",")); process.info(StringUtils.join(classNameList, ","));
...@@ -70,4 +95,5 @@ public class UDFUtils extends UDFUtil { ...@@ -70,4 +95,5 @@ public class UDFUtils extends UDFUtil {
process.info(CharSequenceUtil.format("A total of {} UDF have been Parsed.", classNameList.size())); process.info(CharSequenceUtil.format("A total of {} UDF have been Parsed.", classNameList.size()));
return udfList; return udfList;
} }
} }
...@@ -752,7 +752,7 @@ public final class ExtractionUtils { ...@@ -752,7 +752,7 @@ public final class ExtractionUtils {
} else { } else {
extractor = new ParameterExtractor((Method) executable); extractor = new ParameterExtractor((Method) executable);
} }
getClassReader(executable.getDeclaringClass()).accept(extractor, 0); // getClassReader(executable.getDeclaringClass()).accept(extractor, 0);
final List<String> extractedNames = extractor.getParameterNames(); final List<String> extractedNames = extractor.getParameterNames();
if (extractedNames.size() == 0) { if (extractedNames.size() == 0) {
......
...@@ -30,6 +30,8 @@ import com.dlink.executor.EnvironmentSetting; ...@@ -30,6 +30,8 @@ import com.dlink.executor.EnvironmentSetting;
import com.dlink.executor.Executor; import com.dlink.executor.Executor;
import com.dlink.executor.ExecutorSetting; import com.dlink.executor.ExecutorSetting;
import com.dlink.explainer.Explainer; 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.Env;
import com.dlink.function.data.model.UDF; import com.dlink.function.data.model.UDF;
import com.dlink.function.util.UDFUtil; import com.dlink.function.util.UDFUtil;
...@@ -74,12 +76,16 @@ import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions; ...@@ -74,12 +76,16 @@ import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.graph.StreamGraph; import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.TableResult;
import org.apache.flink.yarn.configuration.YarnConfigOptions; import org.apache.flink.yarn.configuration.YarnConfigOptions;
import org.apache.kerby.util.OSUtil;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -87,6 +93,7 @@ import org.slf4j.LoggerFactory; ...@@ -87,6 +93,7 @@ import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
/** /**
...@@ -202,6 +209,16 @@ public class JobManager { ...@@ -202,6 +209,16 @@ public class JobManager {
executor = Executor.buildRemoteExecutor(environmentSetting, config.getExecutorSetting()); executor = Executor.buildRemoteExecutor(environmentSetting, config.getExecutorSetting());
return executor; return executor;
} else { } else {
if (ArrayUtil.isNotEmpty(config.getJarFiles())) {
if (OSUtil.isWindows()) {
config.getExecutorSetting().getConfig().put(PipelineOptions.JARS.key(),
Stream.of(config.getJarFiles()).map(x -> "file:///" + x).collect(Collectors.joining(",")));
} else {
config.getExecutorSetting().getConfig().put(PipelineOptions.JARS.key(),
Stream.of(config.getJarFiles()).map(x -> "file://" + x).collect(Collectors.joining(",")));
}
}
executor = Executor.buildLocalExecutor(config.getExecutorSetting()); executor = Executor.buildLocalExecutor(config.getExecutorSetting());
return executor; return executor;
} }
...@@ -257,11 +274,22 @@ public class JobManager { ...@@ -257,11 +274,22 @@ public class JobManager {
// 这里要分开 // 这里要分开
// 1. 得到jar包路径,注入remote环境 // 1. 得到jar包路径,注入remote环境
List<UDF> udfList = config.getUdfList(); List<UDF> udfList = config.getUdfList();
if (CollUtil.isEmpty(udfList)) { 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(); createExecutorWithSession();
return; return;
} }
String[] jarPaths = UDFUtil.initJavaUDF(udfList, runMode, config.getTaskId());
CollUtil.addAll(libHDFList, UDFUtil.initJavaUDF(udfList, runMode, config.getTaskId()));
String[] jarPaths = CollUtil.removeEmpty(libHDFList).toArray(new String[]{});
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) { if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths); config.setJarFiles(jarPaths);
......
...@@ -42,9 +42,10 @@ import org.apache.flink.table.api.StatementSet; ...@@ -42,9 +42,10 @@ import org.apache.flink.table.api.StatementSet;
import org.apache.flink.table.api.TableConfig; import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableResult; import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.catalog.CatalogManager; import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.util.JarUtils; import org.apache.flink.util.FlinkUserCodeClassLoader;
import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.UserGroupInformation;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
...@@ -53,6 +54,7 @@ import java.net.URLClassLoader; ...@@ -53,6 +54,7 @@ import java.net.URLClassLoader;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Stream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -61,6 +63,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; ...@@ -61,6 +63,8 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
...@@ -314,7 +318,9 @@ public abstract class Executor { ...@@ -314,7 +318,9 @@ public abstract class Executor {
* @param udfFilePath udf文件路径 * @param udfFilePath udf文件路径
*/ */
public void initUDF(String... udfFilePath) { public void initUDF(String... udfFilePath) {
JarUtils.getJarFiles(udfFilePath).forEach(Executor::loadJar); File[] files = Stream.of(udfFilePath).map(FileUtil::file).toArray(File[]::new);
URLClassLoader classLoader = FlinkUserCodeClassLoader.newInstance(URLUtil.getURLs(files), Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(classLoader);
} }
public void initPyUDF(String executable, String... udfPyFilePath) { public void initPyUDF(String executable, String... udfPyFilePath) {
......
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 set(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();
}
}
...@@ -184,6 +184,7 @@ public class UDFUtil { ...@@ -184,6 +184,7 @@ public class UDFUtil {
if (res) { if (res) {
log.info("class编译成功:{}" + className); log.info("class编译成功:{}" + className);
log.info("compilerTakeTime:" + compiler.getCompilerTakeTime()); log.info("compilerTakeTime:" + compiler.getCompilerTakeTime());
ClassPool.push(ClassEntity.build(className, udf.getCode()));
successList.add(className); successList.add(className);
} else { } else {
log.warn("class编译失败:{}" + className); log.warn("class编译失败:{}" + className);
...@@ -194,6 +195,7 @@ public class UDFUtil { ...@@ -194,6 +195,7 @@ public class UDFUtil {
String className = udf.getClassName(); String className = udf.getClassName();
if (CustomStringScalaCompiler.getInterpreter(null).compileString(udf.getCode())) { if (CustomStringScalaCompiler.getInterpreter(null).compileString(udf.getCode())) {
log.info("scala class编译成功:{}" + className); log.info("scala class编译成功:{}" + className);
ClassPool.push(ClassEntity.build(className, udf.getCode()));
successList.add(className); successList.add(className);
} else { } else {
log.warn("scala class编译失败:{}" + className); log.warn("scala class编译失败:{}" + className);
...@@ -204,8 +206,8 @@ public class UDFUtil { ...@@ -204,8 +206,8 @@ public class UDFUtil {
}); });
String[] clazzs = successList.stream().map(className -> StrUtil.replace(className, ".", "/") + ".class") String[] clazzs = successList.stream().map(className -> StrUtil.replace(className, ".", "/") + ".class")
.toArray(String[]::new); .toArray(String[]::new);
InputStream[] fileInputStreams = InputStream[] fileInputStreams = successList.stream()
successList.stream().map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class") .map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class")
.map(FileUtil::getInputStream).toArray(InputStream[]::new); .map(FileUtil::getInputStream).toArray(InputStream[]::new);
// 编译好的文件打包jar // 编译好的文件打包jar
try (ZipUtils zipWriter = new ZipUtils(FileUtil.file(udfJarPath), Charset.defaultCharset())) { try (ZipUtils zipWriter = new ZipUtils(FileUtil.file(udfJarPath), Charset.defaultCharset())) {
......
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