Unverified Commit 4aa5794b authored by Licho's avatar Licho Committed by GitHub

fix: remove DinkyClassLoaderContextHolder and two others (#2617)

* refactor: remove DinkyClassLoaderContextHolder Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> * feat: remove ExecutorContext.java and reflactor FlinkUdfPathContextHolder * Spotless Apply * refactor: remove JobContextHolder.java * Spotless Apply * fix: 14 15 17 18 * fix: * Spotless Apply * fix Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> * fix: addUrl problem in jdk8 * fix: typo * fix: test * Spotless Apply * fix: only use DinkyClassLoader to actually load UDF, break parent delegation. * Spotless Apply --------- Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com>
parent 435bde76
......@@ -19,8 +19,6 @@
package org.dinky.aop;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.data.exception.DinkyException;
import org.dinky.job.JobResult;
......@@ -63,12 +61,7 @@ public class UdfClassLoaderAspect {
e.printStackTrace();
throw (DinkyException) e;
} finally {
if (proceed instanceof JobResult) {
ClassLoader lastContextClassLoader = Thread.currentThread().getContextClassLoader();
if (lastContextClassLoader instanceof DinkyClassLoader) {
DinkyClassLoaderContextHolder.clear();
}
}
if (proceed instanceof JobResult) {}
}
return proceed;
}
......
......@@ -17,21 +17,11 @@
*
*/
package org.dinky.executor;
package org.dinky.job.handler;
public class ExecutorContext {
import org.dinky.job.Job;
import org.dinky.job.JobHandler;
private static final ThreadLocal<Executor> EXECUTOR = new ThreadLocal<>();
public static void setExecutor(Executor executor) {
EXECUTOR.set(executor);
}
public static Executor getExecutor() {
return EXECUTOR.get();
}
public static void clear() {
EXECUTOR.remove();
}
public abstract class AbsJobHandler implements JobHandler {
protected Job job;
}
......@@ -36,8 +36,6 @@ import org.dinky.data.model.mapping.ClusterInstanceMapping;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.job.FlinkJobTask;
import org.dinky.job.Job;
import org.dinky.job.JobContextHolder;
import org.dinky.job.JobHandler;
import org.dinky.service.ClusterConfigurationService;
import org.dinky.service.ClusterInstanceService;
import org.dinky.service.HistoryService;
......@@ -55,7 +53,7 @@ import org.springframework.context.annotation.DependsOn;
* @since 2021/6/27 0:04
*/
@DependsOn("springContextUtils")
public class Job2MysqlHandler implements JobHandler {
public class Job2MysqlHandler extends AbsJobHandler {
private static final HistoryService historyService;
private static final ClusterInstanceService clusterInstanceService;
......@@ -75,8 +73,8 @@ public class Job2MysqlHandler implements JobHandler {
}
@Override
public boolean init() {
Job job = JobContextHolder.getJob();
public boolean init(Job job) {
this.job = job;
History history = new History();
history.setType(job.getType().getLongValue());
if (job.isUseGateway()) {
......@@ -110,7 +108,6 @@ public class Job2MysqlHandler implements JobHandler {
@Override
public boolean success() {
Job job = JobContextHolder.getJob();
Integer taskId = job.getJobConfig().getTaskId();
History history = new History();
......@@ -206,7 +203,6 @@ public class Job2MysqlHandler implements JobHandler {
@Override
public boolean failed() {
Job job = JobContextHolder.getJob();
History history = new History();
history.setBatchModel(job.getJobConfig().isBatchModel());
history.setId(job.getId());
......
......@@ -28,6 +28,7 @@ import org.dinky.app.resource.impl.HdfsResourceManager;
import org.dinky.app.resource.impl.OssResourceManager;
import org.dinky.app.url.RsURLStreamHandlerFactory;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.config.Dialect;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.data.app.AppParamConfig;
......@@ -59,6 +60,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
......@@ -154,7 +156,8 @@ public class Submitter {
// .config(JsonUtils.toMap(appTask.getConfigJson()))
.build();
Executor executor = ExecutorFactory.buildAppStreamExecutor(executorConfig);
Executor executor = ExecutorFactory.buildAppStreamExecutor(
executorConfig, new WeakReference<>(DinkyClassLoader.build()).get());
// 加载第三方jar //TODO 这里有问题,需要修一修
// loadDep(appTask.getType(),
......@@ -287,9 +290,12 @@ public class Submitter {
ExecuteJarOperation executeJarOperation = new ExecuteJarOperation(sqlStatement);
executeJarOperation.execute(executor.getCustomTableEnvironment());
break;
} else if (Operations.getOperationType(sqlStatement) == SqlType.ADD
&& "kubernetes-application".equals(type)) {
executor.addJar(AddJarSqlParseStrategy.getInfo(sqlStatement));
} else if (Operations.getOperationType(sqlStatement) == SqlType.ADD) {
File[] info = AddJarSqlParseStrategy.getInfo(sqlStatement);
Arrays.stream(info).forEach(executor.getDinkyClassLoader().getUdfPathContextHolder()::addOtherPlugins);
if ("kubernetes-application".equals(type)) {
executor.addJar(info);
}
}
}
}
......
......@@ -31,6 +31,8 @@ public abstract class AbstractCustomTableEnvironment
implements CustomTableEnvironment, DefaultTableEnvironmentInternal, DefaultStreamTableEnvironment {
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected Executor executor;
protected AbstractCustomTableEnvironment() {}
......@@ -48,6 +50,11 @@ public abstract class AbstractCustomTableEnvironment
return ((StreamTableEnvironmentImpl) streamTableEnvironment).execEnv();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
public Planner getPlanner() {
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
......
......@@ -121,7 +121,8 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
this.executor = executor;
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(executionEnvironment, EnvironmentSettings.newInstance().build(), TableConfig.getDefault());
}
......
......@@ -31,6 +31,7 @@ public abstract class AbstractCustomTableEnvironment
implements CustomTableEnvironment, DefaultTableEnvironmentInternal, DefaultStreamTableEnvironment {
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected AbstractCustomTableEnvironment() {}
......@@ -51,6 +52,11 @@ public abstract class AbstractCustomTableEnvironment
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
@Override
public Configuration getRootConfiguration() {
return (Configuration) this.getConfig().getRootConfiguration();
......
......@@ -110,7 +110,8 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
userClassLoader));
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(executionEnvironment, EnvironmentSettings.newInstance().build());
}
......
......@@ -36,6 +36,8 @@ public abstract class AbstractCustomTableEnvironment
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected AbstractCustomTableEnvironment() {}
protected AbstractCustomTableEnvironment(StreamTableEnvironment streamTableEnvironment) {
......@@ -55,6 +57,11 @@ public abstract class AbstractCustomTableEnvironment
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
@Override
public void injectParser(CustomParser parser) {
ReflectUtil.setFieldValue(getPlanner(), "parser", new ParserWrapper(parser));
......
......@@ -20,7 +20,6 @@
package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.data.model.LineageRel;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.utils.JsonUtils;
......@@ -61,7 +60,6 @@ import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
......@@ -75,18 +73,15 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
private static final Logger log = LoggerFactory.getLogger(CustomTableEnvironmentImpl.class);
private static final ObjectMapper mapper = new ObjectMapper();
public CustomTableEnvironmentImpl(StreamTableEnvironment streamTableEnvironment) {
super(streamTableEnvironment);
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(
executionEnvironment,
EnvironmentSettings.newInstance()
.withClassLoader(DinkyClassLoaderContextHolder.get())
.build());
EnvironmentSettings.newInstance().withClassLoader(classLoader).build());
}
public static CustomTableEnvironmentImpl createBatch(StreamExecutionEnvironment executionEnvironment) {
......@@ -123,8 +118,8 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
}
List<ModifyOperation> modifyOperations = operations.stream()
.filter(operation -> operation instanceof ModifyOperation)
.map(operation -> (ModifyOperation) operation)
.filter(ModifyOperation.class::isInstance)
.map(ModifyOperation.class::cast)
.collect(Collectors.toList());
StreamGraph streamGraph = transOperatoinsToStreamGraph(modifyOperations);
......
......@@ -35,6 +35,7 @@ public abstract class AbstractCustomTableEnvironment
implements CustomTableEnvironment, DefaultTableEnvironmentInternal, DefaultStreamTableEnvironment {
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected AbstractCustomTableEnvironment() {}
......@@ -55,6 +56,11 @@ public abstract class AbstractCustomTableEnvironment
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
@Override
public void injectParser(CustomParser parser) {
ReflectUtil.setFieldValue(getPlanner(), "parser", new ParserWrapper(parser));
......
......@@ -20,7 +20,6 @@
package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.data.model.LineageRel;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.utils.LineageContext;
......@@ -82,12 +81,11 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
super(streamTableEnvironment);
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(
executionEnvironment,
EnvironmentSettings.newInstance()
.withClassLoader(DinkyClassLoaderContextHolder.get())
.build());
EnvironmentSettings.newInstance().withClassLoader(classLoader).build());
}
public static CustomTableEnvironmentImpl createBatch(StreamExecutionEnvironment executionEnvironment) {
......
......@@ -33,6 +33,7 @@ public abstract class AbstractCustomTableEnvironment
implements CustomTableEnvironment, DefaultTableEnvironmentInternal, DefaultStreamTableEnvironment {
protected StreamTableEnvironment streamTableEnvironment;
protected ClassLoader userClassLoader;
protected AbstractCustomTableEnvironment() {}
......@@ -49,6 +50,11 @@ public abstract class AbstractCustomTableEnvironment
return ((StreamTableEnvironmentImpl) streamTableEnvironment).execEnv();
}
@Override
public ClassLoader getUserClassLoader() {
return userClassLoader;
}
public Planner getPlanner() {
return ((StreamTableEnvironmentImpl) streamTableEnvironment).getPlanner();
}
......
......@@ -20,7 +20,6 @@
package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.data.model.LineageRel;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.utils.LineageContext;
......@@ -84,12 +83,11 @@ public class CustomTableEnvironmentImpl extends AbstractCustomTableEnvironment {
super(streamTableEnvironment);
}
public static CustomTableEnvironmentImpl create(StreamExecutionEnvironment executionEnvironment) {
public static CustomTableEnvironmentImpl create(
StreamExecutionEnvironment executionEnvironment, ClassLoader classLoader) {
return create(
executionEnvironment,
EnvironmentSettings.newInstance()
.withClassLoader(DinkyClassLoaderContextHolder.get())
.build());
EnvironmentSettings.newInstance().withClassLoader(classLoader).build());
}
public static CustomTableEnvironmentImpl createBatch(StreamExecutionEnvironment executionEnvironment) {
......
......@@ -73,6 +73,8 @@ public interface CustomTableEnvironment
Planner getPlanner();
ClassLoader getUserClassLoader();
Configuration getRootConfiguration();
default List<LineageRel> getLineage(String statement) {
......
......@@ -19,15 +19,12 @@
package org.dinky.trans.ddl;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.executor.CustomTableEnvironment;
import org.dinky.trans.AbstractOperation;
import org.dinky.trans.ExtendOperation;
import org.dinky.trans.parse.AddJarSqlParseStrategy;
import org.apache.flink.table.api.TableResult;
import java.util.Arrays;
import java.util.Optional;
/**
......@@ -45,7 +42,6 @@ public class AddJarOperation extends AbstractOperation implements ExtendOperatio
@Override
public Optional<? extends TableResult> execute(CustomTableEnvironment tEnv) {
Arrays.stream(AddJarSqlParseStrategy.getInfo(statement)).forEach(FlinkUdfPathContextHolder::addOtherPlugins);
return Optional.of(TABLE_RESULT_OK);
}
......
......@@ -27,22 +27,27 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
/** @since 0.7.0 */
/**
* @since 0.7.0
*/
@Slf4j
public class DinkyClassLoader extends URLClassLoader {
FlinkUdfPathContextHolder udfPathContextHolder = new FlinkUdfPathContextHolder();
public DinkyClassLoader(URL[] urls, ClassLoader parent) {
super(new URL[] {}, parent);
}
public DinkyClassLoader(Collection<File> fileSet, ClassLoader parent) {
super(new URL[] {}, parent);
addURL(fileSet);
addURLs(fileSet);
}
public DinkyClassLoader(URL[] urls) {
......@@ -53,13 +58,28 @@ public class DinkyClassLoader extends URLClassLoader {
super(new URL[] {}, parent, factory);
}
public void addURL(URL... urls) {
// this class factory method
public static DinkyClassLoader build() {
return new DinkyClassLoader(new URL[] {});
}
// class factory method with urls parameters
public static DinkyClassLoader build(URL... urls) {
return new DinkyClassLoader(urls);
}
// return udfPathContextHolder
public FlinkUdfPathContextHolder getUdfPathContextHolder() {
return udfPathContextHolder;
}
public void addURLs(URL... urls) {
for (URL url : urls) {
super.addURL(url);
}
}
public void addURL(Collection<File> fileSet) {
public void addURLs(Collection<File> fileSet) {
URL[] urls = fileSet.stream()
.map(x -> {
try {
......@@ -69,21 +89,55 @@ public class DinkyClassLoader extends URLClassLoader {
}
})
.toArray(URL[]::new);
addURL(urls);
addURLs(urls);
}
public void addURLs(List<File> files) {
files.stream()
.map(x -> {
try {
return x.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
})
.forEach(this::addURL);
}
public void addURL(URL url) {
super.addURL(url);
}
public void addURL(String[] paths, List<String> notExistsFiles) {
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
Class<?> loadedClass = findLoadedClass(name);
if (loadedClass == null) {
try {
// try to use this classloader to load
loadedClass = this.findClass(name);
} catch (ClassNotFoundException e) {
// maybe is system class, try parents delegate
return super.loadClass(name, false);
}
}
if (resolve) {
resolveClass(loadedClass);
}
return loadedClass;
}
}
public static List<File> getJarFiles(String[] paths, List<String> notExistsFiles) {
List<File> result = new LinkedList<>();
for (String path : paths) {
File file = new File(path);
try {
if (file.isDirectory()) {
FileUtil.walkFiles(file, f -> {
if (FileUtil.getSuffix(f).equals("jar")) {
try {
super.addURL(f.toURI().toURL());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
result.add(f);
}
});
continue;
......@@ -94,15 +148,8 @@ public class DinkyClassLoader extends URLClassLoader {
}
continue;
}
super.addURL(file.toURI().toURL());
FlinkUdfPathContextHolder.addOtherPlugins(file);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
result.add(file);
}
}
public void addURL(String... paths) {
this.addURL(paths, null);
return result;
}
}
/*
*
* 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.context;
import org.dinky.classloader.DinkyClassLoader;
import java.io.IOException;
import java.net.URL;
import lombok.extern.slf4j.Slf4j;
/** @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<>();
protected 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() {
DinkyClassLoader dinkyClassLoader = CLASS_LOADER_CONTEXT.get();
if (dinkyClassLoader == null) {
dinkyClassLoader = new DinkyClassLoader(new URL[0]);
set(dinkyClassLoader);
}
return dinkyClassLoader;
}
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();
}
}
......@@ -20,51 +20,37 @@
package org.dinky.context;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/** @since 0.7.0 */
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<>();
private final Set<File> UDF_PATH_CONTEXT = new HashSet<>();
private final Set<File> OTHER_PLUGINS_PATH_CONTEXT = new HashSet<>();
private final Set<File> PYTHON_UDF_FILE = new HashSet<>();
public static void addUdfPath(File file) {
public void addUdfPath(File file) {
getUdfFile().add(file);
}
public static void addPyUdfPath(File file) {
public void addPyUdfPath(File file) {
getPyUdfFile().add(file);
}
public static void addOtherPlugins(File file) {
public 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 Set<File> getUdfFile() {
return UDF_PATH_CONTEXT;
}
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<>());
}
return OTHER_PLUGINS_PATH_CONTEXT.get();
public Set<File> getPyUdfFile() {
return PYTHON_UDF_FILE;
}
public static void clear() {
UDF_PATH_CONTEXT.remove();
OTHER_PLUGINS_PATH_CONTEXT.remove();
public Set<File> getOtherPluginsFiles() {
return OTHER_PLUGINS_PATH_CONTEXT;
}
}
......@@ -26,6 +26,7 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
......@@ -89,6 +90,10 @@ public class URLUtils {
* @param files URL对应的文件对象
* @return URL
*/
public static URL[] getURLs(List<File> files) {
return getURLs(files.stream().filter(File::exists).toArray(File[]::new));
}
public static URL[] getURLs(Set<File> files) {
return getURLs(files.stream().filter(File::exists).toArray(File[]::new));
}
......
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -29,7 +31,7 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/
public class AppBatchExecutor extends Executor {
public AppBatchExecutor(ExecutorConfig executorConfig) {
public AppBatchExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
......@@ -37,11 +39,11 @@ public class AppBatchExecutor extends Executor {
} else {
this.environment = StreamExecutionEnvironment.createLocalEnvironment();
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.createBatch(environment);
}
}
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -29,7 +31,7 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/
public class AppStreamExecutor extends Executor {
public AppStreamExecutor(ExecutorConfig executorConfig) {
public AppStreamExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
......@@ -37,11 +39,11 @@ public class AppStreamExecutor extends Executor {
} else {
this.environment = StreamExecutionEnvironment.getExecutionEnvironment();
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
return CustomTableEnvironmentImpl.create(environment);
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.create(environment, classLoader);
}
}
......@@ -20,8 +20,8 @@
package org.dinky.executor;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.data.model.LineageRel;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.interceptor.FlinkInterceptor;
......@@ -31,7 +31,6 @@ import org.dinky.utils.KerberosUtil;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.core.execution.JobClient;
......@@ -50,11 +49,9 @@ import org.apache.flink.table.api.TableResult;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -85,12 +82,19 @@ public abstract class Executor {
// The config of Dinky executor.
protected ExecutorConfig executorConfig;
protected DinkyClassLoader dinkyClassLoader;
// Flink configuration, such as set rest.port = 8086
protected Map<String, Object> setConfig = new HashMap<>();
// Dinky variable manager
protected VariableManager variableManager = new VariableManager();
// return dinkyClassLoader
public DinkyClassLoader getDinkyClassLoader() {
return dinkyClassLoader;
}
public VariableManager getVariableManager() {
return variableManager;
}
......@@ -127,13 +131,13 @@ public abstract class Executor {
return getTableConfig().getLocalTimeZone().getId();
}
protected void init() {
protected void init(DinkyClassLoader classLoader) {
this.dinkyClassLoader = classLoader;
if (executorConfig.isValidParallelism()) {
environment.setParallelism(executorConfig.getParallelism());
}
tableEnvironment = createCustomTableEnvironment();
tableEnvironment = createCustomTableEnvironment(classLoader);
CustomTableEnvironmentContext.set(tableEnvironment);
tableEnvironment.injectParser(
new CustomParserImpl(tableEnvironment.getPlanner().getParser()));
......@@ -158,7 +162,7 @@ public abstract class Executor {
ReflectUtil.setFieldValue(environment, "userClassloader", contextClassLoader);
}
abstract CustomTableEnvironment createCustomTableEnvironment();
abstract CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader);
public String pretreatStatement(String statement) {
return FlinkInterceptor.pretreatStatement(this, statement);
......@@ -192,7 +196,8 @@ public abstract class Executor {
}
public void initUDF(String... udfFilePath) {
DinkyClassLoaderContextHolder.get().addURL(udfFilePath);
List<File> jarFiles = DinkyClassLoader.getJarFiles(udfFilePath, null);
dinkyClassLoader.addURLs(jarFiles);
}
public void initPyUDF(String executable, String... udfPyFilePath) {
......@@ -219,20 +224,6 @@ public abstract class Executor {
addJar(Arrays.stream(jarPath).map(URLUtil::getURL).map(URL::toString).toArray(String[]::new));
}
public void addJar(Collection<File> jarPath) {
addJar(jarPath.stream().map(URLUtil::getURL).map(URL::toString).toArray(String[]::new));
}
public <T> void updateConfiguration(ConfigOption<T> configOption, T value) {
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
configuration.set(configOption, value);
}
public <T> void updateConfiguration(Consumer<Configuration> configurationConsumer) {
Configuration configuration = tableEnvironment.getConfig().getConfiguration();
configurationConsumer.accept(configuration);
}
public SqlExplainResult explainSqlRecord(String statement, ExplainDetail... extraDetails) {
statement = pretreatStatement(statement);
if (Asserts.isNotNullString(statement) && !pretreatExecute(statement).isNoExecute()) {
......
......@@ -19,6 +19,10 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import java.lang.ref.WeakReference;
/**
* ExecutorFactory
*
......@@ -30,38 +34,38 @@ public final class ExecutorFactory {
private ExecutorFactory() {}
public static Executor getDefaultExecutor() {
return new LocalStreamExecutor(ExecutorConfig.DEFAULT);
return new LocalStreamExecutor(ExecutorConfig.DEFAULT, new WeakReference<>(DinkyClassLoader.build()).get());
}
public static Executor buildExecutor(ExecutorConfig executorConfig) {
public static Executor buildExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
if (executorConfig.isRemote()) {
return buildRemoteExecutor(executorConfig);
return buildRemoteExecutor(executorConfig, classLoader);
} else {
return buildLocalExecutor(executorConfig);
return buildLocalExecutor(executorConfig, classLoader);
}
}
public static Executor buildLocalExecutor(ExecutorConfig executorConfig) {
public static Executor buildLocalExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
if (executorConfig.isUseBatchModel()) {
return new LocalBatchExecutor(executorConfig);
return new LocalBatchExecutor(executorConfig, classLoader);
} else {
return new LocalStreamExecutor(executorConfig);
return new LocalStreamExecutor(executorConfig, classLoader);
}
}
public static Executor buildAppStreamExecutor(ExecutorConfig executorConfig) {
public static Executor buildAppStreamExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
if (executorConfig.isUseBatchModel()) {
return new AppBatchExecutor(executorConfig);
return new AppBatchExecutor(executorConfig, classLoader);
} else {
return new AppStreamExecutor(executorConfig);
return new AppStreamExecutor(executorConfig, classLoader);
}
}
public static Executor buildRemoteExecutor(ExecutorConfig executorConfig) {
public static Executor buildRemoteExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
if (executorConfig.isUseBatchModel()) {
return new RemoteBatchExecutor(executorConfig);
return new RemoteBatchExecutor(executorConfig, classLoader);
} else {
return new RemoteStreamExecutor(executorConfig);
return new RemoteStreamExecutor(executorConfig, classLoader);
}
}
}
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.configuration.RestOptions;
......@@ -36,7 +38,7 @@ import cn.hutool.core.io.FileUtil;
*/
public class LocalBatchExecutor extends Executor {
public LocalBatchExecutor(ExecutorConfig executorConfig) {
public LocalBatchExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidJarFiles()) {
executorConfig
......@@ -56,11 +58,11 @@ public class LocalBatchExecutor extends Executor {
} else {
this.environment = StreamExecutionEnvironment.createLocalEnvironment();
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.createBatch(environment);
}
}
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.configuration.RestOptions;
......@@ -36,7 +38,7 @@ import cn.hutool.core.io.FileUtil;
*/
public class LocalStreamExecutor extends Executor {
public LocalStreamExecutor(ExecutorConfig executorConfig) {
public LocalStreamExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidJarFiles()) {
executorConfig
......@@ -56,11 +58,11 @@ public class LocalStreamExecutor extends Executor {
} else {
this.environment = StreamExecutionEnvironment.createLocalEnvironment();
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
return CustomTableEnvironmentImpl.create(environment);
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.create(environment, classLoader);
}
}
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -29,7 +31,7 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/
public class RemoteBatchExecutor extends Executor {
public RemoteBatchExecutor(ExecutorConfig executorConfig) {
public RemoteBatchExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
......@@ -39,11 +41,11 @@ public class RemoteBatchExecutor extends Executor {
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
executorConfig.getHost(), executorConfig.getPort(), executorConfig.getJarFiles());
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.createBatch(environment);
}
}
......@@ -19,6 +19,8 @@
package org.dinky.executor;
import org.dinky.classloader.DinkyClassLoader;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
......@@ -29,7 +31,7 @@ import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
*/
public class RemoteStreamExecutor extends Executor {
public RemoteStreamExecutor(ExecutorConfig executorConfig) {
public RemoteStreamExecutor(ExecutorConfig executorConfig, DinkyClassLoader classLoader) {
this.executorConfig = executorConfig;
if (executorConfig.isValidConfig()) {
Configuration configuration = Configuration.fromMap(executorConfig.getConfig());
......@@ -39,11 +41,11 @@ public class RemoteStreamExecutor extends Executor {
this.environment = StreamExecutionEnvironment.createRemoteEnvironment(
executorConfig.getHost(), executorConfig.getPort(), executorConfig.getJarFiles());
}
init();
init(classLoader);
}
@Override
CustomTableEnvironment createCustomTableEnvironment() {
return CustomTableEnvironmentImpl.create(environment);
CustomTableEnvironment createCustomTableEnvironment(ClassLoader classLoader) {
return CustomTableEnvironmentImpl.create(environment, classLoader);
}
}
......@@ -20,9 +20,8 @@
package org.dinky.explainer;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.model.LineageRel;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.result.ExplainResult;
......@@ -76,6 +75,7 @@ public class Explainer {
private boolean useStatementSet;
private String sqlSeparator = FlinkSQLConstant.SEPARATOR;
private ObjectMapper mapper = new ObjectMapper();
private JobManager jobManager;
public Explainer(Executor executor, boolean useStatementSet) {
this.executor = executor;
......@@ -83,22 +83,24 @@ public class Explainer {
init();
}
public Explainer(Executor executor, boolean useStatementSet, String sqlSeparator) {
public Explainer(Executor executor, boolean useStatementSet, String sqlSeparator, JobManager jobManager) {
this.executor = executor;
this.useStatementSet = useStatementSet;
this.sqlSeparator = sqlSeparator;
this.jobManager = jobManager;
}
public void init() {
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
}
public static Explainer build(Executor executor, boolean useStatementSet, String sqlSeparator) {
return new Explainer(executor, useStatementSet, sqlSeparator);
public static Explainer build(
Executor executor, boolean useStatementSet, String sqlSeparator, JobManager jobManager) {
return new Explainer(executor, useStatementSet, sqlSeparator, jobManager);
}
public Explainer initialize(JobManager jobManager, JobConfig config, String statement) {
DinkyClassLoaderUtil.initClassLoader(config);
public Explainer initialize(JobConfig config, String statement) {
DinkyClassLoaderUtil.initClassLoader(config, jobManager.getDinkyClassLoader());
String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement), sqlSeparator);
List<UDF> udfs = parseUDFFromStatements(statements);
jobManager.setJobParam(new JobParam(udfs));
......@@ -123,9 +125,11 @@ public class Explainer {
}
SqlType operationType = Operations.getOperationType(statement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParseStrategy.getAllFilePath(statement).forEach(FlinkUdfPathContextHolder::addOtherPlugins);
DinkyClassLoaderContextHolder.get()
.addURL(URLUtils.getURLs(FlinkUdfPathContextHolder.getOtherPluginsFiles()));
AddJarSqlParseStrategy.getAllFilePath(statement)
.forEach(t -> jobManager.getUdfPathContextHolder().addOtherPlugins(t));
((DinkyClassLoader) executor.getCustomTableEnvironment().getUserClassLoader())
.addURLs(URLUtils.getURLs(
jobManager.getUdfPathContextHolder().getOtherPluginsFiles()));
} else if (operationType.equals(SqlType.ADD_JAR)) {
Configuration combinationConfig = getCombinationConfig();
FileSystem.initialize(combinationConfig, null);
......@@ -157,7 +161,7 @@ public class Explainer {
PrintStatementExplainer.getCreateStatement(tableName, host, port), SqlType.CTAS));
}
} else {
UDF udf = UDFUtil.toUDF(statement);
UDF udf = UDFUtil.toUDF(statement, jobManager.getDinkyClassLoader());
if (Asserts.isNotNull(udf)) {
udfList.add(udf);
}
......@@ -184,7 +188,7 @@ public class Explainer {
if (statement.isEmpty()) {
continue;
}
UDF udf = UDFUtil.toUDF(statement);
UDF udf = UDFUtil.toUDF(statement, jobManager.getDinkyClassLoader());
if (Asserts.isNotNull(udf)) {
udfList.add(udf);
}
......@@ -379,7 +383,7 @@ public class Explainer {
.parallelism(1)
.configJson(executor.getTableConfig().getConfiguration().toMap())
.build();
this.initialize(JobManager.buildPlanMode(jobConfig), jobConfig, statement);
this.initialize(jobConfig, statement);
List<LineageRel> lineageRelList = new ArrayList<>();
for (String item : SqlUtil.getStatements(statement, sqlSeparator)) {
......
......@@ -87,7 +87,7 @@ public class Job {
this.useGateway = useGateway;
}
public static Job init(
public static Job build(
GatewayType type,
JobConfig jobConfig,
ExecutorConfig executorConfig,
......@@ -98,7 +98,6 @@ public class Job {
if (!useGateway) {
job.setJobManagerAddress(executorConfig.getJobManagerAddress());
}
JobContextHolder.setJob(job);
return job;
}
......
......@@ -43,7 +43,7 @@ public abstract class JobBuilder {
this.useStatementSet = jobManager.isUseStatementSet();
this.useGateway = jobManager.isUseGateway();
this.sqlSeparator = jobManager.getSqlSeparator();
this.job = JobContextHolder.getJob();
this.job = jobManager.getJob();
}
public abstract void run() throws Exception;
......
/*
*
* 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.job;
/**
* JobContextHolder
*
* @since 2021/6/26 23:29
*/
public class JobContextHolder {
private static final ThreadLocal<Job> CONTEXT = new ThreadLocal<>();
public static void setJob(Job job) {
CONTEXT.set(job);
}
public static Job getJob() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
}
......@@ -30,7 +30,7 @@ import java.util.ServiceLoader;
*/
public interface JobHandler {
boolean init();
boolean init(Job job);
boolean ready();
......
......@@ -21,6 +21,7 @@ package org.dinky.job;
import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.constant.FlinkSQLConstant;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.FlinkUdfPathContextHolder;
......@@ -37,9 +38,9 @@ import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult;
import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorConfig;
import org.dinky.executor.ExecutorContext;
import org.dinky.executor.ExecutorFactory;
import org.dinky.explainer.Explainer;
import org.dinky.function.util.UDFUtil;
import org.dinky.gateway.Gateway;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.GatewayConfig;
......@@ -74,6 +75,7 @@ import org.apache.flink.streaming.api.graph.StreamGraph;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.yarn.configuration.YarnConfigOptions;
import java.lang.ref.WeakReference;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;
......@@ -98,6 +100,8 @@ public class JobManager {
private JobParam jobParam = null;
private String currentSql = "";
private final WeakReference<DinkyClassLoader> dinkyClassLoader = new WeakReference<>(DinkyClassLoader.build());
private Job job;
public JobManager() {}
......@@ -149,6 +153,21 @@ public class JobManager {
return useGateway;
}
// return dinkyclassloader
public DinkyClassLoader getDinkyClassLoader() {
return dinkyClassLoader.get();
}
// return udfPathContextHolder
public FlinkUdfPathContextHolder getUdfPathContextHolder() {
return getDinkyClassLoader().getUdfPathContextHolder();
}
// return job
public Job getJob() {
return job;
}
private JobManager(JobConfig config) {
this.config = config;
}
......@@ -178,12 +197,11 @@ public class JobManager {
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
executorConfig = config.getExecutorSetting();
executorConfig.setPlan(isPlanMode);
executor = ExecutorFactory.buildExecutor(executorConfig);
ExecutorContext.setExecutor(executor);
executor = ExecutorFactory.buildExecutor(executorConfig, getDinkyClassLoader());
}
private boolean ready() {
return handler.init();
return handler.init(job);
}
private boolean success() {
......@@ -195,23 +213,22 @@ public class JobManager {
}
public boolean close() {
JobContextHolder.clear();
CustomTableEnvironmentContext.clear();
RowLevelPermissionsContext.clear();
FlinkUdfPathContextHolder.clear();
ExecutorContext.clear();
return true;
}
public ObjectNode getJarStreamGraphJson(String statement) {
StreamGraph streamGraph = JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement);
StreamGraph streamGraph =
JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement, getDinkyClassLoader());
return JsonUtils.parseObject(JsonPlanGenerator.generatePlan(streamGraph.getJobGraph()));
}
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeJarSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
StreamGraph streamGraph = JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement);
job = Job.build(runMode, config, executorConfig, executor, statement, useGateway);
StreamGraph streamGraph =
JobJarStreamGraphBuilder.build(this).getJarStreamGraph(statement, getDinkyClassLoader());
try {
if (!useGateway) {
executor.getStreamExecutionEnvironment().executeAsync(streamGraph);
......@@ -219,7 +236,7 @@ public class JobManager {
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar(getUdfPathContextHolder());
} else {
streamGraph.setJobName(config.getJobName());
JobGraph jobGraph = streamGraph.getJobGraph();
......@@ -260,11 +277,11 @@ public class JobManager {
@ProcessStep(type = ProcessStepType.SUBMIT_EXECUTE)
public JobResult executeSql(String statement) throws Exception {
Job job = Job.init(runMode, config, executorConfig, executor, statement, useGateway);
job = Job.build(runMode, config, executorConfig, executor, statement, useGateway);
ready();
DinkyClassLoaderUtil.initClassLoader(config);
jobParam = Explainer.build(executor, useStatementSet, sqlSeparator)
DinkyClassLoaderUtil.initClassLoader(config, getDinkyClassLoader());
jobParam = Explainer.build(executor, useStatementSet, sqlSeparator, this)
.pretreatStatements(SqlUtil.getStatements(statement, sqlSeparator));
try {
// step 1: init udf
......@@ -330,20 +347,20 @@ public class JobManager {
}
public ExplainResult explainSql(String statement) {
return Explainer.build(executor, useStatementSet, sqlSeparator)
.initialize(this, config, statement)
return Explainer.build(executor, useStatementSet, sqlSeparator, this)
.initialize(config, statement)
.explainSql(statement);
}
public ObjectNode getStreamGraph(String statement) {
return Explainer.build(executor, useStatementSet, sqlSeparator)
.initialize(this, config, statement)
return Explainer.build(executor, useStatementSet, sqlSeparator, this)
.initialize(config, statement)
.getStreamGraph(statement);
}
public String getJobPlanJson(String statement) {
return Explainer.build(executor, useStatementSet, sqlSeparator)
.initialize(this, config, statement)
return Explainer.build(executor, useStatementSet, sqlSeparator, this)
.initialize(config, statement)
.getJobPlanInfo(statement)
.getJsonPlan();
}
......@@ -389,45 +406,7 @@ public class JobManager {
}
public static GatewayResult deploySessionCluster(GatewayConfig gatewayConfig) {
return Gateway.build(gatewayConfig).deployCluster();
}
@Deprecated
public JobResult executeJar() {
// TODO 改为ProcessStep注释
Job job = Job.init(runMode, config, executorConfig, executor, null, useGateway);
ready();
try {
GatewayResult gatewayResult =
Gateway.build(config.getGatewayConfig()).submitJar();
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
job.setEndTime(LocalDateTime.now());
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
success();
} else {
job.setError(gatewayResult.getError());
job.setStatus(Job.JobStatus.FAILED);
failed();
}
} catch (Exception e) {
String error = LogUtil.getError(
"Exception in executing Jar:\n"
+ config.getGatewayConfig().getAppConfig().getUserJarPath(),
e);
job.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED);
job.setError(error);
failed();
log.error(error);
} finally {
close();
}
return job.getJobResult();
return Gateway.build(gatewayConfig).deployCluster(UDFUtil.createFlinkUdfPathContextHolder());
}
public static TestResult testGateway(GatewayConfig gatewayConfig) {
......
......@@ -66,7 +66,8 @@ public class JobExecuteBuilder extends JobBuilder {
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
gatewayResult = Gateway.build(config.getGatewayConfig())
.submitJar(executor.getDinkyClassLoader().getUdfPathContextHolder());
} else {
StreamGraph streamGraph = executor.getStreamGraph();
streamGraph.setJobName(config.getJobName());
......
......@@ -19,7 +19,7 @@
package org.dinky.job.builder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.data.exception.DinkyException;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
......@@ -33,6 +33,9 @@ import org.dinky.utils.SqlUtil;
import org.apache.flink.streaming.api.graph.StreamGraph;
import java.io.File;
import java.util.Set;
import cn.hutool.core.lang.Assert;
/**
......@@ -52,12 +55,11 @@ public class JobJarStreamGraphBuilder extends JobBuilder {
@Override
public void run() throws Exception {}
public StreamGraph getJarStreamGraph(String statement) {
DinkyClassLoaderUtil.initClassLoader(config);
public StreamGraph getJarStreamGraph(String statement, DinkyClassLoader dinkyClassLoader) {
DinkyClassLoaderUtil.initClassLoader(config, dinkyClassLoader);
String[] statements = SqlUtil.getStatements(statement, sqlSeparator);
ExecuteJarOperation executeJarOperation = null;
for (int i = 0; i < statements.length; i++) {
String sql = statements[i];
for (String sql : statements) {
String sqlStatement = executor.pretreatStatement(sql);
if (ExecuteJarParseStrategy.INSTANCE.match(sqlStatement)) {
executeJarOperation = new ExecuteJarOperation(sqlStatement);
......@@ -65,13 +67,9 @@ public class JobJarStreamGraphBuilder extends JobBuilder {
}
SqlType operationType = Operations.getOperationType(sqlStatement);
if (operationType.equals(SqlType.ADD)) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
if (runMode.isApplicationMode()) {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement)
.forEach(FlinkUdfPathContextHolder::addOtherPlugins);
} else {
AddJarSqlParseStrategy.getAllFilePath(sqlStatement).forEach(executor::addJar);
}
Set<File> files = AddJarSqlParseStrategy.getAllFilePath(sqlStatement);
files.forEach(executor::addJar);
files.forEach(jobManager.getUdfPathContextHolder()::addOtherPlugins);
}
}
Assert.notNull(executeJarOperation, () -> new DinkyException("Not found execute jar operation."));
......
......@@ -200,7 +200,8 @@ public class JobTransBuilder extends JobBuilder {
if (runMode.isApplicationMode()) {
// Application mode need to submit dinky-app.jar that in the hdfs or image.
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
gatewayResult = Gateway.build(config.getGatewayConfig())
.submitJar(executor.getDinkyClassLoader().getUdfPathContextHolder());
} else {
JobGraph jobGraph = executor.getJobGraphFromInserts(inserts);
// Perjob mode need to set savepoint restore path, when recovery from savepoint.
......
......@@ -24,7 +24,6 @@ import static org.dinky.function.util.UDFUtil.SESSION;
import static org.dinky.function.util.UDFUtil.YARN;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil;
......@@ -35,6 +34,7 @@ import org.dinky.utils.URLUtils;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
......@@ -70,9 +70,10 @@ public class JobUDFBuilder extends JobBuilder {
taskId = -RandomUtil.randomInt(0, 1000);
}
// 1. Obtain the path of the jar package and inject it into the remote environment
Set<File> jarFiles = FlinkUdfPathContextHolder.getUdfFile();
List<File> jarFiles =
new ArrayList<>(jobManager.getUdfPathContextHolder().getUdfFile());
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
Set<File> otherPluginsFiles = jobManager.getUdfPathContextHolder().getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
List<File> udfJars = Arrays.stream(UDFUtil.initJavaUDF(udfList, runMode, taskId))
......@@ -93,15 +94,16 @@ public class JobUDFBuilder extends JobBuilder {
udfList, runMode, config.getTaskId(), executor.getTableConfig().getConfiguration());
executor.initUDF(jarPaths);
if (ArrayUtil.isNotEmpty(pyPaths)) {
for (String pyPath : pyPaths) {
if (StrUtil.isNotBlank(pyPath)) {
FlinkUdfPathContextHolder.addPyUdfPath(new File(pyPath));
jobManager.getUdfPathContextHolder().addPyUdfPath(new File(pyPath));
}
}
}
Set<File> pyUdfFile = FlinkUdfPathContextHolder.getPyUdfFile();
Set<File> pyUdfFile = jobManager.getUdfPathContextHolder().getPyUdfFile();
executor.initPyUDF(
SystemConfiguration.getInstances().getPythonHome(),
pyUdfFile.stream().map(File::getAbsolutePath).toArray(String[]::new));
......@@ -112,7 +114,7 @@ public class JobUDFBuilder extends JobBuilder {
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
// 3.Write the required files for UDF
UDFUtil.writeManifest(taskId, jarList);
UDFUtil.writeManifest(taskId, jarList, jobManager.getUdfPathContextHolder());
UDFUtil.addConfigurationClsAndJars(jarList, CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
......
......@@ -20,7 +20,7 @@
package org.dinky.utils;
import org.dinky.assertion.Asserts;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.exception.DinkyException;
import org.dinky.job.JobConfig;
......@@ -34,7 +34,9 @@ import cn.hutool.core.io.FileUtil;
public class DinkyClassLoaderUtil {
public static void initClassLoader(JobConfig config) {
public static void initClassLoader(JobConfig config, DinkyClassLoader dinkyClassLoader) {
FlinkUdfPathContextHolder udfPathContextHolder = dinkyClassLoader.getUdfPathContextHolder();
if (CollUtil.isNotEmpty(config.getConfigJson())) {
String pipelineJars = config.getConfigJson().get(PipelineOptions.JARS.key());
String classpaths = config.getConfigJson().get(PipelineOptions.CLASSPATHS.key());
......@@ -46,7 +48,7 @@ public class DinkyClassLoaderUtil {
if (!file.exists()) {
throw new DinkyException("file: " + path + " not exists!");
}
FlinkUdfPathContextHolder.addUdfPath(file);
udfPathContextHolder.addUdfPath(file);
}
}
// add custom classpath
......@@ -57,13 +59,12 @@ public class DinkyClassLoaderUtil {
if (!file.exists()) {
throw new DinkyException("file: " + path + " not exists!");
}
FlinkUdfPathContextHolder.addOtherPlugins(file);
udfPathContextHolder.addOtherPlugins(file);
}
}
}
DinkyClassLoaderContextHolder.get()
.addURL(CollUtil.addAll(
FlinkUdfPathContextHolder.getUdfFile(), FlinkUdfPathContextHolder.getOtherPluginsFiles()));
dinkyClassLoader.addURLs(
CollUtil.addAll(udfPathContextHolder.getUdfFile(), udfPathContextHolder.getOtherPluginsFiles()));
}
}
......@@ -19,6 +19,7 @@
package org.dinky.interceptor;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.executor.Executor;
import org.dinky.executor.ExecutorConfig;
import org.dinky.executor.ExecutorFactory;
......@@ -49,7 +50,7 @@ public class CdcSourceTests {
.toString();
ExecutorConfig executorConfig = ExecutorConfig.DEFAULT;
Executor executor = ExecutorFactory.buildLocalExecutor(executorConfig);
Executor executor = ExecutorFactory.buildLocalExecutor(executorConfig, DinkyClassLoader.build());
executor.executeSql(statement);
executor.execute("");
}
......
......@@ -64,4 +64,14 @@ public class UdfCodePool {
public static String getGitPackage(String className) {
return GIT_POOL.get(className);
}
// return CODE_POOL
public static Map<String, UDF> getUdfCodePool() {
return CODE_POOL;
}
// return GIT_POOL
public static Map<String, String> getGitPool() {
return GIT_POOL;
}
}
......@@ -20,9 +20,9 @@
package org.dinky.function.util;
import org.dinky.assertion.Asserts;
import org.dinky.classloader.DinkyClassLoader;
import org.dinky.config.Dialect;
import org.dinky.context.CustomTableEnvironmentContext;
import org.dinky.context.DinkyClassLoaderContextHolder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.exception.DinkyException;
import org.dinky.data.model.FlinkUdfManifest;
......@@ -303,7 +303,7 @@ public class UDFUtil {
return !StrUtil.isBlank(statement) && CollUtil.isNotEmpty(ReUtil.findAll(pattern, statement, 0));
}
public static UDF toUDF(String statement) {
public static UDF toUDF(String statement, DinkyClassLoader classLoader) {
if (isUdfStatement(PATTERN, statement)) {
List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(PATTERN, statement));
String udfName = groups.get(1);
......@@ -315,10 +315,11 @@ public class UDFUtil {
return null;
}
FlinkUdfPathContextHolder udfPathContextHolder = classLoader.getUdfPathContextHolder();
if (ClassLoaderUtil.isPresent(className)) {
// 获取已经加载在java的类,对应的包路径
try {
FlinkUdfPathContextHolder.addUdfPath(FileUtil.file(DinkyClassLoaderContextHolder.get()
udfPathContextHolder.addUdfPath(FileUtil.file(classLoader
.loadClass(className)
.getProtectionDomain()
.getCodeSource()
......@@ -343,15 +344,36 @@ public class UDFUtil {
if (StrUtil.isNotBlank(gitPackage) && FileUtil.exist(gitPackage)) {
if (FileUtil.getSuffix(gitPackage).equals("jar")) {
FlinkUdfPathContextHolder.addUdfPath(new File(gitPackage));
udfPathContextHolder.addUdfPath(new File(gitPackage));
} else {
FlinkUdfPathContextHolder.addPyUdfPath(new File(gitPackage));
udfPathContextHolder.addPyUdfPath(new File(gitPackage));
}
}
}
return null;
}
// create FlinkUdfPathContextHolder from UdfCodePool
public static FlinkUdfPathContextHolder createFlinkUdfPathContextHolder() {
FlinkUdfPathContextHolder udfPathContextHolder = new FlinkUdfPathContextHolder();
UdfCodePool.getUdfCodePool().values().forEach(udf -> {
if (udf.getFunctionLanguage() == FunctionLanguage.PYTHON) {
udfPathContextHolder.addPyUdfPath(new File(udf.getCode()));
} else {
udfPathContextHolder.addUdfPath(new File(udf.getCode()));
}
});
UdfCodePool.getGitPool().values().forEach(gitPackage -> {
if (FileUtil.getSuffix(gitPackage).equals("jar")) {
udfPathContextHolder.addUdfPath(new File(gitPackage));
} else {
udfPathContextHolder.addPyUdfPath(new File(gitPackage));
}
});
return udfPathContextHolder;
}
public static List<Class<?>> getUdfClassByJar(File jarPath) {
Assert.notNull(jarPath);
......@@ -440,10 +462,11 @@ public class UDFUtil {
PipelineOptions.JARS, jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
public static void writeManifest(Integer taskId, List<URL> jarPaths) {
public static void writeManifest(
Integer taskId, List<URL> jarPaths, FlinkUdfPathContextHolder udfPathContextHolder) {
FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest();
flinkUdfManifest.setJars(jarPaths);
flinkUdfManifest.setPythonFiles(FlinkUdfPathContextHolder.getPyUdfFile().stream()
flinkUdfManifest.setPythonFiles(udfPathContextHolder.getPyUdfFile().stream()
.map(URLUtil::getURL)
.collect(Collectors.toList()));
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.JobStatus;
import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.ActionType;
......@@ -182,7 +183,7 @@ public abstract class AbstractGateway implements Gateway {
}
@Override
public GatewayResult submitJar() {
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
throw new GatewayException("Couldn't deploy Flink Cluster with User Application Jar.");
}
......@@ -207,7 +208,7 @@ public abstract class AbstractGateway implements Gateway {
}
@Override
public GatewayResult deployCluster() {
public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) {
logger.error("Could not deploy the Flink cluster");
return null;
}
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.enums.JobStatus;
import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType;
......@@ -70,7 +71,7 @@ public interface Gateway {
GatewayResult submitJobGraph(JobGraph jobGraph);
GatewayResult submitJar();
GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder);
SavePointResult savepointCluster();
......@@ -88,5 +89,5 @@ public interface Gateway {
boolean onJobFinishCallback(String status);
GatewayResult deployCluster();
GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder);
}
......@@ -20,6 +20,7 @@
package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.enums.GatewayType;
......@@ -74,7 +75,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
* @throws RuntimeException if an error occurs during submission.
*/
@Override
public GatewayResult submitJar() {
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
try {
logger.info("Start submit k8s application.");
ClusterClientProvider<String> clusterClient = deployApplication();
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult;
......@@ -43,7 +44,7 @@ public class KubernetesSessionGateway extends KubernetesGateway {
}
@Override
public GatewayResult deployCluster() {
public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) {
if (Asserts.isNull(client)) {
init();
}
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.kubernetes.operator;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.kubernetes.operator.api.FlinkDeployment;
import org.dinky.gateway.result.GatewayResult;
......@@ -50,7 +51,7 @@ public class KubetnetsApplicationOperatorGateway extends KubernetsOperatorGatewa
}
@Override
public GatewayResult submitJar() {
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
// TODO 改为ProcessStep注释
logger.info("start submit flink jar use {}", getType());
......
......@@ -57,7 +57,7 @@ public class YarnApplicationGateway extends YarnGateway {
}
@Override
public GatewayResult submitJar() {
public GatewayResult submitJar(FlinkUdfPathContextHolder udfPathContextHolder) {
if (Asserts.isNull(yarnClient)) {
init();
}
......@@ -66,9 +66,7 @@ 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(",")));
udfPathContextHolder.getPyUdfFile().stream().map(File::getName).collect(Collectors.joining(",")));
String[] userJarParas =
Asserts.isNotNull(appConfig.getUserJarParas()) ? appConfig.getUserJarParas() : new String[0];
......@@ -79,7 +77,7 @@ public class YarnApplicationGateway extends YarnGateway {
new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass());
YarnResult result = YarnResult.build(getType());
try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar()) {
try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar(udfPathContextHolder)) {
ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deployApplicationCluster(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration);
ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient();
......
......@@ -278,15 +278,15 @@ public abstract class YarnGateway extends AbstractGateway {
}
}
protected YarnClusterDescriptor createYarnClusterDescriptorWithJar() {
protected YarnClusterDescriptor createYarnClusterDescriptorWithJar(FlinkUdfPathContextHolder udfPathContextHolder) {
YarnClusterDescriptor yarnClusterDescriptor = createInitYarnClusterDescriptor();
if (Asserts.isNotNull(config.getJarPaths())) {
yarnClusterDescriptor.addShipFiles(
Arrays.stream(config.getJarPaths()).map(FileUtil::file).collect(Collectors.toList()));
yarnClusterDescriptor.addShipFiles(new ArrayList<>(FlinkUdfPathContextHolder.getPyUdfFile()));
yarnClusterDescriptor.addShipFiles(new ArrayList<>(udfPathContextHolder.getPyUdfFile()));
}
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
Set<File> otherPluginsFiles = udfPathContextHolder.getOtherPluginsFiles();
if (CollUtil.isNotEmpty(otherPluginsFiles)) {
yarnClusterDescriptor.addShipFiles(CollUtil.newArrayList(otherPluginsFiles));
......
......@@ -20,6 +20,7 @@
package org.dinky.gateway.yarn;
import org.dinky.assertion.Asserts;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.YarnResult;
......@@ -44,7 +45,7 @@ public class YarnSessionGateway extends YarnGateway {
}
@Override
public GatewayResult deployCluster() {
public GatewayResult deployCluster(FlinkUdfPathContextHolder udfPathContextHolder) {
if (Asserts.isNull(yarnClient)) {
init();
}
......@@ -53,7 +54,7 @@ public class YarnSessionGateway extends YarnGateway {
createClusterSpecificationBuilder();
YarnResult result = YarnResult.build(getType());
try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar()) {
try (YarnClusterDescriptor yarnClusterDescriptor = createYarnClusterDescriptorWithJar(udfPathContextHolder)) {
ClusterClientProvider<ApplicationId> clusterClientProvider = yarnClusterDescriptor.deploySessionCluster(
clusterSpecificationBuilder.createClusterSpecification());
ClusterClient<ApplicationId> clusterClient = clusterClientProvider.getClusterClient();
......
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