Unverified Commit e38c814c authored by aiwenmo's avatar aiwenmo Committed by GitHub

[Optimization-2579][core] Optimizate JobManager (#2580)

* [Optimization-2579][core] Optimizate JobManager * optimize return --------- Co-authored-by: 's avatarwenmo <32723967+wenmo@users.noreply.github.com>
parent e32555e0
......@@ -86,4 +86,16 @@ public class SqlUtil {
}
return sql;
}
public static String addLineNumber(String input) {
String[] lines = input.split("\n");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.length; i++) {
sb.append(String.format("%-4d", i + 1));
sb.append(" ");
sb.append(lines[i]);
sb.append("\n");
}
return sb.toString();
}
}
......@@ -19,6 +19,8 @@
package org.dinky.utils;
import org.dinky.assertion.Asserts;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
......@@ -93,4 +95,12 @@ public class URLUtils {
public static String toString(URL[] urls) {
return Arrays.stream(urls).map(URL::toString).collect(Collectors.joining(","));
}
public static String formatAddress(String webURL) {
if (Asserts.isNotNullString(webURL)) {
return webURL.replaceAll("http://", "");
} else {
return "";
}
}
}
/*
*
* 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.executor;
public class ExecutorContext {
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();
}
}
......@@ -38,6 +38,7 @@ import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
import org.dinky.job.JobParam;
import org.dinky.job.StatementParam;
import org.dinky.job.builder.JobUDFBuilder;
import org.dinky.parser.SqlType;
import org.dinky.trans.Operations;
import org.dinky.trans.parse.AddJarSqlParseStrategy;
......@@ -99,7 +100,13 @@ public class Explainer {
public Explainer initialize(JobManager jobManager, JobConfig config, String statement) {
DinkyClassLoaderUtil.initClassLoader(config);
String[] statements = SqlUtil.getStatements(SqlUtil.removeNote(statement), sqlSeparator);
jobManager.initUDF(parseUDFFromStatements(statements));
List<UDF> udfs = parseUDFFromStatements(statements);
jobManager.setJobParam(new JobParam(udfs));
try {
JobUDFBuilder.build(jobManager).run();
} catch (Exception e) {
e.printStackTrace();
}
return this;
}
......
/*
*
* 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;
import org.dinky.executor.Executor;
import org.dinky.gateway.enums.GatewayType;
public abstract class JobBuilder {
protected JobManager jobManager;
protected JobConfig config;
protected JobParam jobParam;
protected GatewayType runMode;
protected Executor executor;
protected boolean useStatementSet;
protected boolean useGateway;
protected String sqlSeparator;
protected Job job;
public JobBuilder(JobManager jobManager) {
this.jobManager = jobManager;
this.config = jobManager.getConfig();
this.jobParam = jobManager.getJobParam();
this.runMode = jobManager.getRunMode();
this.executor = jobManager.getExecutor();
this.useStatementSet = jobManager.isUseStatementSet();
this.useGateway = jobManager.isUseGateway();
this.sqlSeparator = jobManager.getSqlSeparator();
this.job = JobContextHolder.getJob();
}
public abstract void run() throws Exception;
}
......@@ -37,6 +37,10 @@ public class JobParam {
private List<StatementParam> execute;
private List<UDF> udfList;
public JobParam(List<UDF> udfList) {
this.udfList = udfList;
}
public JobParam(List<StatementParam> ddl, List<StatementParam> trans) {
this.ddl = ddl;
this.trans = trans;
......
/*
*
* 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.builder;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.job.StatementParam;
import lombok.extern.slf4j.Slf4j;
/**
* JobDDLBuilder
*
*/
@Slf4j
public class JobDDLBuilder extends JobBuilder {
public JobDDLBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobDDLBuilder build(JobManager jobManager) {
return new JobDDLBuilder(jobManager);
}
@Override
public void run() throws Exception {
for (StatementParam item : jobParam.getDdl()) {
jobManager.setCurrentSql(item.getValue());
executor.executeSql(item.getValue());
}
}
}
/*
*
* 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.builder;
import org.dinky.assertion.Asserts;
import org.dinky.data.result.IResult;
import org.dinky.data.result.InsertResult;
import org.dinky.data.result.ResultBuilder;
import org.dinky.gateway.Gateway;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.job.Job;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.job.StatementParam;
import org.dinky.parser.SqlType;
import org.dinky.utils.URLUtils;
import org.apache.flink.core.execution.JobClient;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings;
import org.apache.flink.streaming.api.graph.StreamGraph;
import java.util.ArrayList;
/**
* JobExecuteBuilder
*
*/
public class JobExecuteBuilder extends JobBuilder {
public JobExecuteBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobExecuteBuilder build(JobManager jobManager) {
return new JobExecuteBuilder(jobManager);
}
@Override
public void run() throws Exception {
if (!jobParam.getExecute().isEmpty()) {
if (useGateway) {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
GatewayResult gatewayResult = null;
config.addGatewayConfig(executor.getSetConfig());
if (runMode.isApplicationMode()) {
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJar();
} else {
StreamGraph streamGraph = executor.getStreamGraph();
streamGraph.setJobName(config.getJobName());
JobGraph jobGraph = streamGraph.getJobGraph();
if (Asserts.isNotNullString(config.getSavePointPath())) {
jobGraph.setSavepointRestoreSettings(
SavepointRestoreSettings.forPath(config.getSavePointPath(), true));
}
gatewayResult = Gateway.build(config.getGatewayConfig()).submitJobGraph(jobGraph);
}
job.setResult(InsertResult.success(gatewayResult.getId()));
job.setJobId(gatewayResult.getId());
job.setJids(gatewayResult.getJids());
job.setJobManagerAddress(URLUtils.formatAddress(gatewayResult.getWebURL()));
if (gatewayResult.isSuccess()) {
job.setStatus(Job.JobStatus.SUCCESS);
} else {
job.setStatus(Job.JobStatus.FAILED);
job.setError(gatewayResult.getError());
}
} else {
for (StatementParam item : jobParam.getExecute()) {
executor.executeSql(item.getValue());
if (!useStatementSet) {
break;
}
}
JobClient jobClient = executor.executeAsync(config.getJobName());
if (Asserts.isNotNull(jobClient)) {
job.setJobId(jobClient.getJobID().toHexString());
job.setJids(new ArrayList<String>() {
{
add(job.getJobId());
}
});
}
if (config.isUseResult()) {
IResult result = ResultBuilder.build(
SqlType.EXECUTE,
job.getId().toString(),
config.getMaxRowNum(),
config.isUseChangeLog(),
config.isUseAutoCancel(),
executor.getTimeZone())
.getResult(null);
job.setResult(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.job.builder;
import org.dinky.context.FlinkUdfPathContextHolder;
import org.dinky.data.exception.DinkyException;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.parser.SqlType;
import org.dinky.trans.Operations;
import org.dinky.trans.dml.ExecuteJarOperation;
import org.dinky.trans.parse.AddJarSqlParseStrategy;
import org.dinky.trans.parse.ExecuteJarParseStrategy;
import org.dinky.utils.DinkyClassLoaderUtil;
import org.dinky.utils.SqlUtil;
import org.apache.flink.streaming.api.graph.StreamGraph;
import cn.hutool.core.lang.Assert;
/**
* JobJarStreamGraphBuilder
*
*/
public class JobJarStreamGraphBuilder extends JobBuilder {
public JobJarStreamGraphBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobJarStreamGraphBuilder build(JobManager jobManager) {
return new JobJarStreamGraphBuilder(jobManager);
}
@Override
public void run() throws Exception {}
public StreamGraph getJarStreamGraph(String statement) {
DinkyClassLoaderUtil.initClassLoader(config);
String[] statements = SqlUtil.getStatements(statement, sqlSeparator);
ExecuteJarOperation executeJarOperation = null;
for (int i = 0; i < statements.length; i++) {
String sql = statements[i];
String sqlStatement = executor.pretreatStatement(sql);
if (ExecuteJarParseStrategy.INSTANCE.match(sqlStatement)) {
executeJarOperation = new ExecuteJarOperation(sqlStatement);
break;
}
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);
}
}
}
Assert.notNull(executeJarOperation, () -> new DinkyException("Not found execute jar operation."));
return executeJarOperation.explain(executor.getCustomTableEnvironment());
}
}
/*
*
* 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.builder;
import static org.dinky.function.util.UDFUtil.GATEWAY_TYPE_MAP;
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;
import org.dinky.job.JobBuilder;
import org.dinky.job.JobManager;
import org.dinky.utils.LogUtil;
import org.dinky.utils.URLUtils;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* JobUDFBuilder
*
*/
@Slf4j
public class JobUDFBuilder extends JobBuilder {
public JobUDFBuilder(JobManager jobManager) {
super(jobManager);
}
public static JobUDFBuilder build(JobManager jobManager) {
return new JobUDFBuilder(jobManager);
}
@Override
public void run() throws Exception {
Asserts.checkNotNull(jobParam, "No executable statement.");
List<UDF> udfList = jobManager.getJobParam().getUdfList();
Integer taskId = config.getTaskId();
if (taskId == null) {
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();
Set<File> otherPluginsFiles = FlinkUdfPathContextHolder.getOtherPluginsFiles();
jarFiles.addAll(otherPluginsFiles);
List<File> udfJars = Arrays.stream(UDFUtil.initJavaUDF(udfList, runMode, taskId))
.map(File::new)
.collect(Collectors.toList());
jarFiles.addAll(udfJars);
String[] jarPaths = CollUtil.removeNull(jarFiles).stream()
.map(File::getAbsolutePath)
.toArray(String[]::new);
if (GATEWAY_TYPE_MAP.get(SESSION).contains(runMode)) {
config.setJarFiles(jarPaths);
}
// 2.Compile Python
String[] pyPaths = UDFUtil.initPythonUDF(
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));
}
}
}
Set<File> pyUdfFile = FlinkUdfPathContextHolder.getPyUdfFile();
executor.initPyUDF(
SystemConfiguration.getInstances().getPythonHome(),
pyUdfFile.stream().map(File::getAbsolutePath).toArray(String[]::new));
if (GATEWAY_TYPE_MAP.get(YARN).contains(runMode)) {
config.getGatewayConfig().setJarPaths(ArrayUtil.append(jarPaths, pyPaths));
}
try {
List<URL> jarList = CollUtil.newArrayList(URLUtils.getURLs(jarFiles));
// 3.Write the required files for UDF
UDFUtil.writeManifest(taskId, jarList);
UDFUtil.addConfigurationClsAndJars(jarList, CollUtil.newArrayList(URLUtils.getURLs(otherPluginsFiles)));
} catch (Exception e) {
log.error("add configuration failed;reason:{}", LogUtil.getError(e));
throw new RuntimeException(e);
}
log.info(StrUtil.format("A total of {} UDF have been Init.", udfList.size() + pyUdfFile.size()));
log.info("Initializing Flink UDF...Finish");
}
}
......@@ -21,9 +21,11 @@ package org.dinky.function.util;
import org.dinky.assertion.Asserts;
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;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.function.FunctionFactory;
import org.dinky.function.compiler.CustomStringJavaCompiler;
......@@ -37,6 +39,7 @@ import org.dinky.pool.ClassPool;
import org.apache.flink.client.python.PythonFunctionFactory;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.python.PythonOptions;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.FunctionLanguage;
......@@ -45,6 +48,7 @@ import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
......@@ -55,6 +59,7 @@ import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -75,10 +80,12 @@ import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine;
import cn.hutool.json.JSONUtil;
/**
* UDFUtil
......@@ -421,4 +428,27 @@ public class UDFUtil {
throw new DinkyException(e);
}
}
public static void addConfigurationClsAndJars(List<URL> jarList, List<URL> classpaths) {
Configuration configuration = (Configuration) CustomTableEnvironmentContext.get()
.getStreamExecutionEnvironment()
.getConfiguration();
configuration.set(
PipelineOptions.CLASSPATHS,
classpaths.stream().map(URL::toString).collect(Collectors.toList()));
configuration.set(
PipelineOptions.JARS, jarList.stream().map(URL::toString).collect(Collectors.toList()));
}
public static void writeManifest(Integer taskId, List<URL> jarPaths) {
FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest();
flinkUdfManifest.setJars(jarPaths);
flinkUdfManifest.setPythonFiles(FlinkUdfPathContextHolder.getPyUdfFile().stream()
.map(URLUtil::getURL)
.collect(Collectors.toList()));
FileUtil.writeUtf8String(
JSONUtil.toJsonStr(flinkUdfManifest),
PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST);
}
}
......@@ -506,7 +506,6 @@ const Model: ModelType = {
if (payload === '') {
centerContentHeight = state.centerContentHeight + (state.bottomContainer.height as number);
toolContentHeight = state.toolContentHeight + (state.bottomContainer.height as number);
console.log(2);
} else if (
state.bottomContainer.selectKey !== '' &&
payload !== state.bottomContainer.selectKey
......@@ -516,7 +515,6 @@ const Model: ModelType = {
} else {
centerContentHeight = state.centerContentHeight - (state.bottomContainer.height as number);
toolContentHeight = state.toolContentHeight - (state.bottomContainer.height as number);
console.log(3);
}
return {
......
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