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

[Optimize ]optimize some code (#2013)

* optimize some code * optimize some code
parent 3c9c6661
......@@ -302,11 +302,6 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-invoker</artifactId>
<version>3.2.0</version>
</dependency>
</dependencies>
<build>
......
......@@ -23,11 +23,8 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import cn.hutool.system.SystemUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
......@@ -43,24 +40,7 @@ import lombok.extern.slf4j.Slf4j;
public class Dinky {
@SneakyThrows
public static void main(String[] args) {
String ipAddress = SystemUtil.getHostInfo().getAddress();
System.setProperty("ipAddr", ipAddress);
SpringApplication app = new SpringApplication(Dinky.class);
ConfigurableApplicationContext application = app.run(args);
Environment env = application.getEnvironment();
String port = env.getProperty("server.port");
System.setProperty("dinkyAddr", ipAddress + ":" + port);
log.info(
"\n----------------------------------------------------------\n\t"
+ "Application 'Dinky' is running! Access URLs:\n\t"
+ "Local: \t\thttp://localhost:{}\n\t"
+ "External: \thttp://{}:{}\n\t"
+ "Doc: \thttp://{}:{}/doc.html\n"
+ "----------------------------------------------------------",
port,
ipAddress,
port,
ipAddress,
port);
app.run(args);
}
}
......@@ -20,7 +20,9 @@
package org.dinky.common.result;
import java.io.Serializable;
import java.util.Date;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
......@@ -40,7 +42,7 @@ import lombok.Setter;
public class StepResult implements Serializable {
private Integer currentStep;
// 0.stepInfo 1.log 2.data
// 0.stepInfo 1.log 2.data 3.finish_info
private Integer type;
private Object data;
/** 2-success 1-process 0-failed */
......@@ -52,6 +54,16 @@ public class StepResult implements Serializable {
return genLog(currentStep, status, log, true);
}
public static StepResult genFinishInfo(Integer currentStep, Integer status, Date date) {
return StepResult.builder()
.type(3)
.currentStep(currentStep)
.data(DateUtil.formatDateTime(date))
.status(status)
.history(false)
.build();
}
public static StepResult genLog(
Integer currentStep, Integer status, String log, Boolean history) {
StepResult stepResult = new StepResult();
......
......@@ -87,6 +87,14 @@ public class GitController {
* @param sortList after sorter data
* @return {@link Result}<{@link Void}>
*/
// @PostMapping("/dragendSortProject")
// public Result<Void> dragendSortProject(@RequestBody Map sortList) {
// if (sortList == null) {
// return Result.failed("获取不到项目信息");
// }
// gitProjectService.dragendSortProject(sortList);
// return Result.succeed();
// }
@PostMapping("/dragendSortProject")
public Result<Void> dragendSortProject(@RequestBody Map sortList) {
if (sortList == null) {
......
......@@ -19,26 +19,20 @@
package org.dinky.controller;
import org.dinky.common.result.ProTableResult;
import org.dinky.common.result.Result;
import org.dinky.model.Configuration;
import org.dinky.model.SysConfig;
import org.dinky.service.SysConfigService;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.lang.Dict;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -55,48 +49,11 @@ public class SysConfigController {
private final SysConfigService sysConfigService;
/** 新增或者更新 */
@PutMapping
public Result<Void> saveOrUpdate(@RequestBody SysConfig sysConfig) throws Exception {
if (sysConfigService.saveOrUpdate(sysConfig)) {
return Result.succeed("新增成功");
} else {
return Result.failed("新增失败");
}
}
/** 动态查询列表 */
@PostMapping
public ProTableResult<SysConfig> listSysConfigs(@RequestBody JsonNode para) {
return sysConfigService.selectForProTable(para);
}
/** 批量删除 */
@DeleteMapping
public Result<Void> deleteMul(@RequestBody JsonNode para) {
if (para.size() > 0) {
List<Integer> error = new ArrayList<>();
for (final JsonNode item : para) {
Integer id = item.asInt();
if (!sysConfigService.removeById(id)) {
error.add(id);
}
}
if (error.size() == 0) {
return Result.succeed("删除成功");
} else {
return Result.succeed("删除部分成功,但" + error + "删除失败,共" + error.size() + "次失败。");
}
} else {
return Result.failed("请选择要删除的记录");
}
}
/** 获取指定ID的信息 */
@PostMapping("/getOneById")
public Result<SysConfig> getOneById(@RequestBody SysConfig sysConfig) throws Exception {
sysConfig = sysConfigService.getById(sysConfig.getId());
return Result.succeed(sysConfig, "获取成功");
@PostMapping("/modifyConfig")
public Result<Void> modifyConfig(@RequestBody Dict params) {
sysConfigService.updateSysConfigByKv(params.getStr("key"), params.getStr("value"));
return Result.succeed();
}
/** 获取所有配置 */
......@@ -104,11 +61,4 @@ public class SysConfigController {
public Result<Map<String, List<Configuration<?>>>> getAll() {
return Result.succeed(sysConfigService.getAll(), "获取成功");
}
/** 批量更新配置 */
@PostMapping("/updateSysConfigByJson")
public Result<Void> updateSysConfigByJson(@RequestBody JsonNode para) {
sysConfigService.updateSysConfigByJson(para);
return Result.succeed("更新配置成功");
}
}
......@@ -46,7 +46,7 @@ import lombok.Setter;
*/
@Setter
@Getter
public class SuperEntity<T extends Model<?>> extends Model<T> implements Serializable {
public class SuperEntity<T extends Model<?>> extends Model<T> {
/** 主键ID */
@TableId(value = "id", type = IdType.AUTO)
......
/*
*
* 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.init;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;
@Order(-1)
@Component
@Slf4j
public class EnvInit implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String ipAddress = SystemUtil.getHostInfo().getAddress();
System.setProperty("ipAddr", ipAddress);
ApplicationContext application = SpringUtil.getApplicationContext();
Environment env = application.getEnvironment();
String port = env.getProperty("server.port");
System.setProperty("dinkyAddr", ipAddress + ":" + port);
log.info(
"\n----------------------------------------------------------\n\t"
+ "Application 'Dinky' is running! Access URLs:\n\t"
+ "Local: \t\thttp://localhost:{}\n\t"
+ "External: \thttp://{}:{}\n\t"
+ "Doc: \thttp://{}:{}/doc.html\n"
+ "----------------------------------------------------------",
port,
ipAddress,
port,
ipAddress,
port);
}
}
......@@ -21,7 +21,6 @@ package org.dinky.model;
import org.dinky.db.annotation.Save;
import java.io.Serializable;
import java.time.LocalDateTime;
import javax.validation.constraints.NotNull;
......@@ -31,6 +30,7 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;
......@@ -43,7 +43,7 @@ import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("dinky_sys_config")
public class SysConfig implements Serializable {
public class SysConfig extends Model<SysConfig> {
private static final long serialVersionUID = 3769276772487490408L;
......@@ -62,8 +62,4 @@ public class SysConfig implements Serializable {
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
protected Serializable pkVal() {
return this.id;
}
}
......@@ -26,8 +26,6 @@ import org.dinky.model.SysConfig;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
/**
* SysConfig
*
......@@ -39,5 +37,5 @@ public interface SysConfigService extends ISuperService<SysConfig> {
void initSysConfig();
void updateSysConfigByJson(JsonNode node);
void updateSysConfigByKv(String key, String value);
}
......@@ -19,7 +19,6 @@
package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.db.service.impl.SuperServiceImpl;
import org.dinky.mapper.SysConfigMapper;
import org.dinky.model.Configuration;
......@@ -27,7 +26,7 @@ import org.dinky.model.SysConfig;
import org.dinky.model.SystemConfiguration;
import org.dinky.service.SysConfigService;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
......@@ -35,9 +34,13 @@ import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
/**
* SysConfigServiceImpl
*
......@@ -51,40 +54,42 @@ public class SysConfigServiceImpl extends SuperServiceImpl<SysConfigMapper, SysC
@Override
public Map<String, List<Configuration<?>>> getAll() {
return SystemConfiguration.getInstances().addConfiguration();
return SystemConfiguration.getInstances().getAllConfiguration();
}
@Override
public void initSysConfig() {
SystemConfiguration.getInstances()
.setConfiguration(
mapper.valueToTree(
list().stream()
.collect(
Collectors.toMap(
SysConfig::getName, SysConfig::getValue))));
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
systemConfiguration.init();
List<Configuration<?>> configurationList =
systemConfiguration.getAllConfiguration().entrySet().stream()
.flatMap(x -> x.getValue().stream())
.collect(Collectors.toList());
List<SysConfig> sysConfigList = list();
List<String> nameList =
sysConfigList.stream().map(SysConfig::getName).collect(Collectors.toList());
configurationList.stream()
.filter(x -> !nameList.contains(x.getKey()))
.map(
x -> {
SysConfig sysConfig = new SysConfig();
sysConfig.setName(x.getKey());
sysConfig.setValue(Convert.toStr(x.getDefaultValue()));
return sysConfig;
})
.forEach(Model::insertOrUpdate);
Map<String, String> configMap =
CollUtil.toMap(
sysConfigList, new HashMap<>(), SysConfig::getName, SysConfig::getValue);
systemConfiguration.setConfiguration(configMap);
}
@Override
public void updateSysConfigByJson(JsonNode node) {
if (node != null && node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> it = node.fields();
while (it.hasNext()) {
Map.Entry<String, JsonNode> entry = it.next();
String name = entry.getKey();
String value = entry.getValue().asText();
SysConfig config = getOne(new QueryWrapper<SysConfig>().eq("name", name));
SysConfig newConfig = new SysConfig();
newConfig.setValue(value);
if (Asserts.isNull(config)) {
newConfig.setName(name);
save(newConfig);
} else {
newConfig.setId(config.getId());
updateById(newConfig);
}
}
}
SystemConfiguration.getInstances().setConfiguration(node);
public void updateSysConfigByKv(String key, String value) {
SysConfig config = getOne(new QueryWrapper<SysConfig>().eq("name", key));
config.setValue(value);
config.updateById();
SystemConfiguration.getInstances().setConfiguration(MapUtil.of(key, value));
}
}
......@@ -19,6 +19,7 @@
package org.dinky.sse;
import org.dinky.common.result.StepResult;
import org.dinky.context.GitBuildContextHolder;
import org.dinky.model.GitProject;
......@@ -38,6 +39,7 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
......@@ -105,7 +107,7 @@ public abstract class StepSse {
msgId
.getAndIncrement()))
.data(msg));
} catch (IOException e) {
} catch (IllegalStateException | IOException e) {
loseLise.add(emitter);
}
});
......@@ -183,6 +185,7 @@ public abstract class StepSse {
GitProject gitProject = (GitProject) params.get("gitProject");
sendMsg(StepResult.genFinishInfo(getStep(), status ? 2 : 0, DateUtil.date()));
if (!status) {
gitProject.setBuildState(2);
close();
......
......@@ -22,6 +22,7 @@ package org.dinky.sse.git;
import org.dinky.dto.GitAnalysisJarDTO;
import org.dinky.function.util.UDFUtil;
import org.dinky.model.GitProject;
import org.dinky.process.exception.DinkyException;
import org.dinky.sse.StepSse;
import java.io.File;
......@@ -70,6 +71,13 @@ public class AnalysisUdfClassStepSse extends StepSse {
List<GitAnalysisJarDTO> dataList = new ArrayList<>();
Map<String, List<Class<?>>> udfMap = new TreeMap<>();
try {
Thread.currentThread()
.getContextClassLoader()
.loadClass("org.apache.flink.table.api.ValidationException");
} catch (ClassNotFoundException e) {
throw new DinkyException("flink dependency not found");
}
pathList.parallelStream()
.forEach(
jar -> {
......
......@@ -23,6 +23,7 @@ import org.dinky.dto.GitAnalysisJarDTO;
import org.dinky.function.util.UDFUtil;
import org.dinky.model.GitProject;
import org.dinky.model.SystemConfiguration;
import org.dinky.process.exception.DinkyException;
import org.dinky.sse.StepSse;
import java.io.File;
......@@ -53,6 +54,13 @@ public class AnalysisUdfPythonStepSse extends StepSse {
public void exec() {
File zipFile = (File) params.get("zipFile");
File projectFile = (File) params.get("projectFile");
try {
Thread.currentThread()
.getContextClassLoader()
.loadClass("org.apache.flink.table.api.ValidationException");
} catch (ClassNotFoundException e) {
throw new DinkyException("flink dependency not found");
}
List<String> pythonUdfList =
UDFUtil.getPythonUdfList(
SystemConfiguration.getInstances().getPythonHome(),
......
......@@ -90,8 +90,6 @@ public class MavenStepSse extends StepSse {
StrUtil.split(gitProject.getBuildArgs(), " "),
this::addMsg);
params.put("pom", pom);
if (!state) {
setFinish(false);
}
Assert.isTrue(state, "maven build failed");
}
}
......@@ -46,6 +46,7 @@ import java.util.stream.IntStream;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
......@@ -65,6 +66,7 @@ public final class GitProjectStepSseFactory {
cachedThreadPool.execute(headStepSse::main);
gitProject.setBuildStep(1);
gitProject.setBuildState(1);
gitProject.setLastBuild(DateUtil.date());
gitProject.updateById();
GitBuildContextHolder.addRun(gitProject.getId());
......
......@@ -23,16 +23,8 @@ import org.dinky.function.constant.PathConstant;
import org.dinky.model.SystemConfiguration;
import org.dinky.process.exception.DinkyException;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamHandler;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
......@@ -44,19 +36,34 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Slf4j
public class MavenUtil {
private static final List<String> COMMON_BIN_PATH = CollUtil.newArrayList("/usr", "/usr/local");
static final String javaExecutor =
FileUtil.file(
FileUtil.file(SystemUtil.getJavaRuntimeInfo().getHomeDir())
.getParentFile(),
"/bin/java")
.getAbsolutePath();
// /home/zackyoung/.jdks/corretto-1.8.0_372/bin/java
// -Dmaven.multiModuleProjectDirectory=/home/zackyoung/IdeaProjects/dinky-quickstart-java
// -Djansi.passthrough=true -Dmaven.home=/usr/share/maven
// -Dclassworlds.conf=/usr/share/maven/bin/m2.conf -Dfile.encoding=UTF-8 -classpath
// /usr/share/maven/boot/plexus-classworlds-2.x.jar org.codehaus.classworlds.Launcher
// --update-snapshots -s /home/zackyoung/settings2.xml
// -Dmaven.repo.local=/home/zackyoung/.m2/repository -DskipTests=true package
private static final TemplateEngine ENGINE =
new FreemarkerEngine(
new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
......@@ -83,81 +90,67 @@ public class MavenUtil {
.orElseThrow(
() -> new DinkyException("Please set the environment variable:MAVEN_HOME"));
InvocationRequest request = new DefaultInvocationRequest();
request.addArg("-DskipTests=true");
Opt.ofEmptyAble(args).ifPresent(c -> CollUtil.removeBlank(args).forEach(request::addArg));
String localRepositoryDirectory;
if (StrUtil.isBlank(setting)) {
repositoryDir = Opt.ofBlankAble(repositoryDir).orElse("/usr/local/resp");
localRepositoryDirectory = Opt.ofBlankAble(repositoryDir).orElse("/usr/local/resp");
// 设置仓库地址
request.setLocalRepositoryDirectory(new File(repositoryDir));
} else {
request.setGlobalSettingsFile(new File(setting));
Opt.ofBlankAble(repositoryDir)
.ifPresent(x -> request.setLocalRepositoryDirectory(new File(x)));
}
// 设置pom文件路径
request.setPomFile(new File(pom));
// 执行的maven命令
request.setGoals(goals);
request.setMavenHome(new File(mavenHome));
try {
FileUtil.touch(logFile);
// 日志处理
PrintStream out = new PrintStream(logFile);
PrintStreamHandler printStreamHandler =
new PrintStreamHandler(out, true) {
@Override
public void consumeLine(String line) {
// 2023-04-21 18:24:37.613 INFO -
line = DateUtil.date().toMsStr() + " - " + line;
if (consumer != null) {
consumer.accept(line);
}
super.consumeLine(line);
}
};
request.setOutputHandler(printStreamHandler);
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
localRepositoryDirectory = repositoryDir;
}
String mavenCommandLine =
getMavenCommandLine(pom, mavenHome, localRepositoryDirectory, setting, goals, args);
int waitValue =
RuntimeUtils.run(
mavenCommandLine,
s -> {
s = DateUtil.date().toMsStr() + " - " + s;
consumer.accept(s);
FileUtil.writeUtf8String(s, logFile);
},
log::error);
return waitValue == 0;
}
Invoker invoker = new DefaultInvoker();
try {
// 判断是否执行成功
return invoker.execute(request).getExitCode() == 0;
} catch (MavenInvocationException e) {
e.printStackTrace();
return false;
}
/**
* /usr/bin/java
* -Dmaven.multiModuleProjectDirectory=/home/zackyoung/IdeaProjects/dinky-quickstart-java
* -Djansi.passthrough=true -Dmaven.home=/usr/share/maven
* -Dclassworlds.conf=/usr/share/maven/bin/m2.conf -Dfile.encoding=UTF-8 -classpath
* /usr/share/maven/boot/plexus-classworlds-2.x.jar org.codehaus.classworlds.Launcher
* --update-snapshots -s /home/zackyoung/settings2.xml
* -Dmaven.repo.local=/home/zackyoung/.m2/repository -DskipTests=true package
*
* @return
*/
public static String getMavenCommandLine(
String projectDir,
String mavenHome,
String repositoryDir,
String settingsPath,
List<String> goals,
List<String> args) {
List<String> commandLine = new LinkedList<>();
commandLine.add(javaExecutor);
commandLine.add("-Dfile.encoding=UTF-8");
commandLine.add("-Dmaven.multiModuleProjectDirectory=" + projectDir);
commandLine.add("-Dmaven.home=" + mavenHome);
Opt.ofBlankAble(repositoryDir)
.ifPresent(x -> commandLine.add("-Dmaven.repo.local=" + repositoryDir));
commandLine.add("-Dclassworlds.conf=" + mavenHome + "/bin/m2.conf");
commandLine.add(
"-classpath "
+ mavenHome
+ "/boot/plexus-classworlds-2.x.jar org.codehaus.classworlds.Launcher");
commandLine.add("-s " + settingsPath);
commandLine.add("-f " + projectDir);
commandLine.add(StrUtil.join(" ", args));
commandLine.add(StrUtil.join(" ", goals));
return StrUtil.join(" ", commandLine);
}
public static String getMavenVersion() {
String mavenHome = getMavenHome();
InvocationRequest request = new DefaultInvocationRequest();
request.setMavenHome(new File(mavenHome));
request.addArg("-v");
List<String> msg = new LinkedList<>();
List<String> errMsg = new LinkedList<>();
request.setOutputHandler(msg::add);
request.setErrorHandler(errMsg::add);
Invoker invoker = new DefaultInvoker();
try {
int exitCode = invoker.execute(request).getExitCode();
if (exitCode != 0) {
throw new RuntimeException(String.join("\n", errMsg));
}
} catch (MavenInvocationException e) {
throw new RuntimeException(e);
}
return StrUtil.join("\n", msg);
return RuntimeUtil.execForStr(getMavenHome() + "/bin/mvn -v");
}
public static String getMavenHome() {
......@@ -165,11 +158,14 @@ public class MavenUtil {
if (StrUtil.isNotBlank(mavenHome)) {
return mavenHome;
}
if (SystemUtil.getOsInfo().isLinux() || SystemUtil.getOsInfo().isMac()) {
for (String path : COMMON_BIN_PATH) {
if (FileUtil.exist(path + "/bin/mvn")) {
return path;
}
String searchCmd = SystemUtil.getOsInfo().isWindows() ? "where" : "which";
mavenHome = RuntimeUtil.execForStr(searchCmd + " mvn").trim();
if (StrUtil.isNotBlank(mavenHome)) {
try {
return new File(mavenHome).toPath().toRealPath().getParent().getParent().toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return null;
......@@ -214,6 +210,7 @@ public class MavenUtil {
} else if (StrUtil.isBlank(mavenSettings)) {
Dict render =
Dict.create()
.set("tmpDir", PathConstant.TMP_PATH)
.set("repositoryUrl", systemConfiguration.getMavenRepository())
.set("repositoryUser", systemConfiguration.getMavenRepositoryUser())
.set(
......
/*
*
* 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.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import cn.hutool.core.lang.Opt;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RuntimeUtils {
static final List<Process> RUNNING = new CopyOnWriteArrayList<>();
public static void run(String shell) {
run(shell, log::info, log::error);
}
public static int run(
String shell, Consumer<String> outputConsumer, Consumer<String> errorConsumer) {
Process process;
int waitValue = 1;
try {
process = Runtime.getRuntime().exec(shell);
RUNNING.add(process);
new Thread(
() -> {
InputStream inputStream = process.getInputStream();
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String line;
try {
while ((line = reader.readLine()) != null) {
if (outputConsumer != null) {
outputConsumer.accept(line);
}
}
reader.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
})
.start();
waitValue = process.waitFor();
RUNNING.remove(process);
if (waitValue != 0) {
LineNumberReader lineNumberReader =
new LineNumberReader(new InputStreamReader(process.getErrorStream()));
String errMsg = lineNumberReader.lines().collect(Collectors.joining("\n"));
Opt.ofNullable(errorConsumer).ifPresent(x -> x.accept(errMsg));
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return waitValue;
}
}
......@@ -27,7 +27,7 @@ under the License.
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<localRepository>./../../maven/m2</localRepository>
<localRepository>${tmpDir}maven/m2</localRepository>
<servers>
<server>
......
......@@ -21,6 +21,7 @@ package org.dinky.model;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import com.fasterxml.jackson.annotation.JsonIgnore;
......@@ -34,6 +35,7 @@ import lombok.Getter;
public class Configuration<T> {
private final String key;
@JsonIgnore private final transient Class<T> type;
private transient Function<T, T> desensitizedHandler = null;
private final String frontType;
private String note;
......@@ -52,6 +54,10 @@ public class Configuration<T> {
this.value = type.isInstance(value) ? (T) value : Convert.convert(getType(), value);
}
public void setDesensitizedHandler(Function<T, T> desensitizedHandler) {
this.desensitizedHandler = desensitizedHandler;
}
public Configuration(String key, Class<T> type, String note, T defaultValue) {
this.key = key;
this.type = type;
......
......@@ -27,8 +27,6 @@ import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
......@@ -61,7 +59,6 @@ public class SystemConfiguration {
f -> f.getType() == Configuration.class))
.map(f -> (Configuration<?>) ReflectUtil.getFieldValue(systemConfiguration, f))
.collect(Collectors.toList());
private Configuration<Boolean> useRestAPI =
key("flink.settings.useRestAPI")
.booleanType()
......@@ -97,7 +94,7 @@ public class SystemConfiguration {
.note("Maven private server authentication username");
private Configuration<String> mavenRepositoryPassword =
key("maven.settings.repositoryUser")
key("maven.settings.repositoryPassword")
.stringType()
.defaultValue("")
.note("Maven Central Repository Auth Password");
......@@ -136,11 +133,20 @@ public class SystemConfiguration {
.defaultValue("Dinky")
.note("The project name specified in DolphinScheduler, case insensitive");
public void setConfiguration(JsonNode jsonNode) {
public void init() {
if (StrUtil.isBlank(dinkyAddr.getDefaultValue())) {
ReflectUtil.setFieldValue(dinkyAddr, "defaultValue", System.getProperty("dinkyAddr"));
}
}
public void setConfiguration(Map<String, String> configMap) {
CONFIGURATION_LIST.forEach(
item -> {
final JsonNode value = jsonNode.get(item.getKey());
if (value == null || value.isNull()) {
if (!configMap.containsKey(item.getKey())) {
return;
}
final String value = configMap.get(item.getKey());
if (StrUtil.isBlank(value)) {
item.setValue(item.getDefaultValue());
return;
}
......@@ -151,7 +157,7 @@ public class SystemConfiguration {
c -> Opt.ofNullable(this.initMethod).ifPresent(x -> x.accept(c)));
}
public Map<String, List<Configuration<?>>> addConfiguration() {
public Map<String, List<Configuration<?>>> getAllConfiguration() {
Map<String, List<Configuration<?>>> data = new TreeMap<>();
for (Configuration<?> item : CONFIGURATION_LIST) {
final String name = item.getKey();
......
......@@ -43,10 +43,7 @@ import org.apache.flink.table.functions.UserDefinedFunction;
import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
......@@ -57,7 +54,6 @@ 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;
......@@ -76,6 +72,7 @@ import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ClassUtil;
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.crypto.digest.MD5;
import cn.hutool.extra.template.TemplateConfig;
......@@ -441,13 +438,11 @@ public class UDFUtil {
e.printStackTrace();
}
}
System.out.println(successUdfList);
return successUdfList;
}
private static List<String> execPyAndGetUdfNameList(
String pyPath, String pyFile, String checkPyFile) {
Process process;
try {
// 运行Python3脚本的命令,换成自己的即可
String shell =
......@@ -457,22 +452,9 @@ public class UDFUtil {
Opt.ofBlankAble(pyPath).orElse("python3"),
pyFile,
checkPyFile));
process = Runtime.getRuntime().exec(shell);
if (process.waitFor() != 0) {
LineNumberReader lineNumberReader =
new LineNumberReader(new InputStreamReader(process.getErrorStream()));
String errMsg = lineNumberReader.lines().collect(Collectors.joining("\n"));
throw new DinkyException(errMsg);
}
InputStreamReader ir = new InputStreamReader(process.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String result = input.readLine();
input.close();
ir.close();
return StrUtil.split(result, ",");
} catch (IOException | InterruptedException e) {
return StrUtil.split(RuntimeUtil.execForStr(shell), ",");
} catch (Exception e) {
throw new DinkyException(e);
}
}
......
......@@ -94,7 +94,7 @@ export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
if (type === 0) {
if (execNum === 1) {
logList={}
logList = {}
}
execNum++;
let parseResultData = JSON.parse(data); // parse data
......@@ -135,11 +135,14 @@ export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
logList[currentStep].push(data)
setLog(logList[currentStep]?.join("\n"))
}
}
if (type === 2) {
} else if (type === 2) {
showDataStep = currentStep;
showData = JSON.parse(data);
}else if (type===3){
stepArray[currentStep].description=data;
return
}
if (currentStep >= globalCurrentStep) {
setCurrentStep(currentStep);
setPercent(parseInt(String(100 / stepNum * currentStep)));
......
......@@ -52,3 +52,8 @@ update dinky_database set `type` = 'SQLServer' where `type` = 'SqlServer';
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`, `order_line`) VALUES (1, 1, 'java-udf', 'https://github.com/zackyoungh/dinky-quickstart-java.git', 'master', NULL, NULL, NULL, NULL, '-P flink-1.14', 1, 1, NULL, NULL, 0, 0, 1, '[]', 1);
INSERT INTO `dinky_git_project` (`id`, `tenant_id`, `name`, `url`, `branch`, `username`, `password`, `private_key`, `pom`, `build_args`, `code_type`, `type`, `last_build`, `description`, `build_state`, `build_step`, `enabled`, `udf_class_map_list`, `order_line`) VALUES (2, 1, 'python-udf', 'https://github.com/zackyoungh/dinky-quickstart-python.git', 'master', NULL, NULL, NULL, NULL, '', 2, 1, NULL, NULL, 0, 0, 1, '[]',2);
UPDATE `dinky_sys_config` SET `name` = 'flink.settings.useRestAPI' where `name` = 'useRestAPI';
UPDATE `dinky_sys_config` SET `name` = 'flink.settings.sqlSeparator' where `name` = 'sqlSeparator';
UPDATE `dinky_sys_config` SET `name` = 'flink.settings.jobIdWait' where `name` = 'jobIdWait';
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