Unverified Commit b431a944 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature][UDF] session model support dynamic classLoader external jar (#1410)

* add pipeline.jar loader * add pipeline.jars loader * change udf find null msg * change compile fail * change log print. add protocol header
parent 49b9197d
......@@ -19,16 +19,15 @@
package com.dlink.aop;
import com.dlink.classloader.DinkyClassLoader;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.job.JobResult;
import java.io.IOException;
import java.net.URLClassLoader;
import com.dlink.process.exception.DinkyException;
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;
......@@ -61,30 +60,21 @@ public class UdfClassLoaderAspect {
@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);
if (!(e instanceof DinkyException)) {
throw new DinkyException(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();
}
}
if (proceed instanceof JobResult) {
ClassLoader lastContextClassLoader = Thread.currentThread().getContextClassLoader();
if (lastContextClassLoader instanceof DinkyClassLoader) {
DinkyClassLoaderContextHolder.clear();
}
}
}
return proceed;
}
......
......@@ -586,7 +586,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));
Assert.check(task);
Asserts.checkNull(task,StrUtil.format("class: {} ,not exists!",className));
task.setStatement(statementService.getById(task.getId()).getStatement());
return task;
}
......
......@@ -19,12 +19,17 @@
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
......@@ -40,6 +45,22 @@ public class UDFServiceImpl implements UDFService {
*/
@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,12 +19,14 @@
package com.dlink.utils;
import com.dlink.context.DinkyClassLoaderContextHolder;
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;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.process.exception.DinkyException;
import com.dlink.process.model.ProcessEntity;
import com.dlink.service.TaskService;
......@@ -40,7 +42,6 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
......@@ -67,8 +68,14 @@ public class UDFUtils extends UDFUtil {
String className = groups.get(2);
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
UDFPathContextHolder.set(ReflectUtil.newInstance(className).getClass().getProtectionDomain()
.getCodeSource().getLocation().getPath());
try {
UDFPathContextHolder.add(
DinkyClassLoaderContextHolder.get().loadClass(className).getProtectionDomain()
.getCodeSource().getLocation().getPath());
} catch (ClassNotFoundException e) {
throw new DinkyException(e);
}
return 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.classloader;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.7.0
*/
@Slf4j
public class DinkyClassLoader extends URLClassLoader {
public DinkyClassLoader(URL[] urls, ClassLoader parent) {
super(new URL[] {}, parent);
}
public DinkyClassLoader(URL[] urls) {
super(new URL[] {});
}
public DinkyClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(new URL[] {}, parent, factory);
}
public void addURL(URL... urls) {
for (URL url : urls) {
super.addURL(url);
}
}
public void addURL(String... paths) {
for (String path : paths) {
File file = new File(path);
try {
super.addURL(file.toURI().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
}
}
/*
*
* 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 com.dlink.classloader.DinkyClassLoader;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.7.0
*/
@Slf4j
public class DinkyClassLoaderContextHolder {
private static final ThreadLocal<DinkyClassLoader> CLASS_LOADER_CONTEXT = new ThreadLocal<>();
private static final ThreadLocal<ClassLoader> INIT_CLASS_LOADER_CONTEXT = new ThreadLocal<>();
public static void set(DinkyClassLoader classLoader) {
CLASS_LOADER_CONTEXT.set(classLoader);
INIT_CLASS_LOADER_CONTEXT.set(Thread.currentThread().getContextClassLoader());
Thread.currentThread().setContextClassLoader(classLoader);
}
public static DinkyClassLoader get() {
return CLASS_LOADER_CONTEXT.get();
}
public static void clear() {
DinkyClassLoader dinkyClassLoader = get();
CLASS_LOADER_CONTEXT.remove();
try {
dinkyClassLoader.close();
} catch (IOException e) {
log.error("卸载类失败,reason: {}", e.getMessage());
throw new RuntimeException(e);
}
dinkyClassLoader = null;
Thread.currentThread().setContextClassLoader(INIT_CLASS_LOADER_CONTEXT.get());
INIT_CLASS_LOADER_CONTEXT.remove();
}
}
......@@ -37,7 +37,7 @@ public class LogUtil {
private static final Logger logger = LoggerFactory.getLogger(LogUtil.class);
public static String getError(Exception e) {
public static String getError(Throwable e) {
String error = null;
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
......@@ -51,7 +51,7 @@ public class LogUtil {
}
}
public static String getError(String msg, Exception e) {
public static String getError(String msg, Throwable e) {
String error = null;
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
......
......@@ -76,7 +76,6 @@ import org.apache.flink.streaming.api.environment.ExecutionCheckpointingOptions;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.yarn.configuration.YarnConfigOptions;
import org.apache.kerby.util.OSUtil;
import java.time.LocalDateTime;
import java.util.ArrayList;
......@@ -210,13 +209,9 @@ public class JobManager {
return executor;
} 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(",")));
}
config.getExecutorSetting().getConfig().put(PipelineOptions.JARS.key(),
Stream.of(config.getJarFiles()).map(FileUtil::getAbsolutePath)
.collect(Collectors.joining(",")));
}
executor = Executor.buildLocalExecutor(config.getExecutorSetting());
......@@ -289,6 +284,7 @@ public class JobManager {
}
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)) {
......
......@@ -20,6 +20,7 @@
package com.dlink.executor;
import com.dlink.assertion.Asserts;
import com.dlink.context.DinkyClassLoaderContextHolder;
import com.dlink.interceptor.FlinkInterceptor;
import com.dlink.interceptor.FlinkInterceptorResult;
import com.dlink.model.LineageRel;
......@@ -42,10 +43,8 @@ import org.apache.flink.table.api.StatementSet;
import org.apache.flink.table.api.TableConfig;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.catalog.CatalogManager;
import org.apache.flink.util.FlinkUserCodeClassLoader;
import org.apache.hadoop.security.UserGroupInformation;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
......@@ -54,7 +53,6 @@ import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -63,8 +61,6 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
/**
......@@ -318,9 +314,7 @@ public abstract class Executor {
* @param udfFilePath udf文件路径
*/
public void initUDF(String... udfFilePath) {
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);
DinkyClassLoaderContextHolder.get().addURL(udfFilePath);
}
public void initPyUDF(String executable, String... udfPyFilePath) {
......
......@@ -59,6 +59,7 @@ 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 UDF_PYTHON_NAME = "python_udf.zip";
/**
* udf jar tmp路径
......
......@@ -11,7 +11,7 @@ import cn.hutool.core.collection.ConcurrentHashSet;
public class UDFPathContextHolder {
private static final ThreadLocal<Set<String>> UDF_PATH_CONTEXT = new ThreadLocal<>();
public static void set(String path) {
public static void add(String path) {
if (UDF_PATH_CONTEXT.get() == null) {
UDF_PATH_CONTEXT.set(new ConcurrentHashSet<>());
}
......
/*
*
* 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.process.exception;
import com.dlink.process.context.ProcessContextHolder;
import com.dlink.utils.LogUtil;
/**
* @author ZackYoung
* @since 0.7.0
*/
public class DinkyException extends RuntimeException {
public DinkyException() {
}
public DinkyException(String message) {
super(message);
ProcessContextHolder.getProcess().error(message);
}
public DinkyException(String message, Throwable cause) {
super(message, cause);
ProcessContextHolder.getProcess().error(LogUtil.getError(cause));
}
public DinkyException(Throwable cause) {
super(cause);
ProcessContextHolder.getProcess().error(cause.toString());
}
public DinkyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
ProcessContextHolder.getProcess().error(LogUtil.getError(cause));
}
}
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