Unverified Commit 5c23aaf8 authored by ZackYoung's avatar ZackYoung Committed by GitHub

[Feature][git] support python analysis udf (#1951)

* add python sse * feat: add official `add jar` sql syntax, and rename custom `add jar` to `add customJar` (#1927) * feat: add official add jar sql syntax * Spotless Apply * refact Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * refactor: add log add reduce code Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> * Spotless Apply * fix: unit test Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * feat: add configure combination initialize Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> * Spotless Apply * fix: adapter 1.13 * spotless * fix: configure import * Spotless Apply * fix: flink 1.14 adaptically * Spotless Apply --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com> * Add error show modal (#1948) * [Feature][dinky-web] support git ci/cd web (#1941) * added git project * 实现 git(ci/cd) 的web一些功能点 * added some note * delete some code * format code * add python sse * add python sse * Update front-end display * Update front-end display * Update front-end display * fix dinky-web build * fix dinky-web build --------- Signed-off-by: 's avatarLicho <lecho.sun@gmail.com> Signed-off-by: 's avatarlicho <lecho.sun@gmail.com> Co-authored-by: 's avatarLicho <lecho.sun@gmail.com> Co-authored-by: 's avatarleechor <leechor@users.noreply.github.com> Co-authored-by: 's avatargaoyan <34333571+gaoyan1998@users.noreply.github.com> Co-authored-by: 's avatarzhu-mingye <934230207@qq.com>
parent f8438c78
...@@ -38,19 +38,57 @@ import lombok.Setter; ...@@ -38,19 +38,57 @@ import lombok.Setter;
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
public class StepResult implements Serializable { public class StepResult implements Serializable {
/** message type (1-stepInfo 2-log) */
private Integer type;
private Integer currentStep; private Integer currentStep;
// 0.stepInfo 1.log 2.data
private Integer type;
private Object data; private Object data;
/** 0-fail , 1-process , 2-success */ /** 2-success 1-process 0-failed */
private Integer status; private Integer status;
public static StepResult getStepInfo(Integer currentStep, Object data) { private Boolean history;
public static StepResult genHistoryLog(Integer currentStep, Integer status, String log) {
return genLog(currentStep, status, log, true);
}
public static StepResult genLog(
Integer currentStep, Integer status, String log, Boolean history) {
StepResult stepResult = new StepResult();
stepResult.setHistory(history);
stepResult.setData(log);
stepResult.setType(1);
stepResult.setCurrentStep(currentStep);
stepResult.setStatus(status);
return stepResult;
}
public static StepResult getStepInfo(Integer currentStep, Integer status, Object data) {
return StepResult.builder() return StepResult.builder()
.type(1) .type(0)
.currentStep(currentStep) .currentStep(currentStep)
.data(JSONUtil.toJsonStr(data)) .data(JSONUtil.toJsonStr(data))
.status(status)
.build();
}
public static StepResult getLog(Integer currentStep, Integer status, String data) {
return StepResult.builder()
.type(1)
.currentStep(currentStep)
.data(data)
.status(status)
.history(false)
.build();
}
public static StepResult getData(Integer currentStep, Integer status, String data) {
return StepResult.builder()
.type(2)
.currentStep(currentStep)
.data(data)
.status(status)
.history(true)
.build(); .build();
} }
......
...@@ -74,7 +74,7 @@ public class MybatisPlusConfig { ...@@ -74,7 +74,7 @@ public class MybatisPlusConfig {
"dinky_savepoints", "dinky_savepoints",
"dinky_task", "dinky_task",
"dinky_task_statement", "dinky_task_statement",
"dinky_git_project", // "dinky_git_project",
"dinky_task_version"); "dinky_task_version");
@Bean @Bean
......
...@@ -25,6 +25,7 @@ import org.dinky.dto.GitProjectDTO; ...@@ -25,6 +25,7 @@ import org.dinky.dto.GitProjectDTO;
import org.dinky.dto.TreeNodeDTO; import org.dinky.dto.TreeNodeDTO;
import org.dinky.model.GitProject; import org.dinky.model.GitProject;
import org.dinky.service.GitProjectService; import org.dinky.service.GitProjectService;
import org.dinky.sse.SseEmitterUTF8;
import org.dinky.utils.GitProjectStepSseFactory; import org.dinky.utils.GitProjectStepSseFactory;
import org.dinky.utils.GitRepository; import org.dinky.utils.GitRepository;
import org.dinky.utils.MessageResolverUtils; import org.dinky.utils.MessageResolverUtils;
...@@ -35,6 +36,7 @@ import java.util.concurrent.TimeUnit; ...@@ -35,6 +36,7 @@ import java.util.concurrent.TimeUnit;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
...@@ -167,8 +169,9 @@ public class GitController { ...@@ -167,8 +169,9 @@ public class GitController {
* @return {@link Result} of {@link Void} * @return {@link Result} of {@link Void}
*/ */
@GetMapping(path = "/build-step-logs", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @GetMapping(path = "/build-step-logs", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
@CrossOrigin("*")
public SseEmitter buildStepLogs(@RequestParam("id") Integer id) { public SseEmitter buildStepLogs(@RequestParam("id") Integer id) {
SseEmitter emitter = new SseEmitter(TimeUnit.MINUTES.toMillis(30)); SseEmitter emitter = new SseEmitterUTF8(TimeUnit.MINUTES.toMillis(30));
GitProject gitProject = gitProjectService.getById(id); GitProject gitProject = gitProjectService.getById(id);
Dict params = new Dict(); Dict params = new Dict();
File logDir = File logDir =
......
...@@ -43,7 +43,5 @@ public class DoneStepSse extends StepSse { ...@@ -43,7 +43,5 @@ public class DoneStepSse extends StepSse {
} }
@Override @Override
public void exec() { public void exec() {}
addFileMsgLog("finished");
}
} }
/*
*
* 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.sse;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
public class SseEmitterUTF8 extends SseEmitter {
public SseEmitterUTF8(Long timeout) {
super(timeout);
}
@Override
protected void extendResponse(ServerHttpResponse outputMessage) {
super.extendResponse(outputMessage);
HttpHeaders headers = outputMessage.getHeaders();
headers.setContentType(new MediaType(MediaType.TEXT_EVENT_STREAM, StandardCharsets.UTF_8));
}
}
...@@ -113,13 +113,18 @@ public abstract class StepSse { ...@@ -113,13 +113,18 @@ public abstract class StepSse {
} }
public synchronized void addFileMsg(Object msg) { public synchronized void addFileMsg(Object msg) {
FileUtil.appendString(Convert.toStr(msg), getLogFile(), StandardCharsets.UTF_8); FileUtil.appendUtf8String(Convert.toStr(msg), getLogFile());
}
public synchronized void addFileMsgCusLog(String msg) {
String content = "\n============= " + Convert.toStr(msg) + " =============\n";
addMsg(content);
FileUtil.appendUtf8String(content, getLogFile());
} }
public synchronized void addFileMsgLog(String msg) { public synchronized void addFileMsgLog(String msg) {
String content = "============= " + Convert.toStr(msg) + " =============\n"; addMsg(msg);
msgList.add(content); FileUtil.appendUtf8String(msg, getLogFile());
FileUtil.appendString(content, getLogFile(), StandardCharsets.UTF_8);
} }
public synchronized void addFileLog(List<?> data) { public synchronized void addFileLog(List<?> data) {
...@@ -132,11 +137,11 @@ public abstract class StepSse { ...@@ -132,11 +137,11 @@ public abstract class StepSse {
return new File(logDir, getStep() + ".log"); return new File(logDir, getStep() + ".log");
} }
public void sendSync() { public synchronized void sendSync() {
if (CollUtil.isNotEmpty(msgList)) { if (CollUtil.isNotEmpty(msgList)) {
sendMsg(getLogObj(msgList)); sendMsg(getLogObj(msgList));
msgList.clear();
} }
msgList.clear();
} }
public void send() { public void send() {
...@@ -157,10 +162,11 @@ public abstract class StepSse { ...@@ -157,10 +162,11 @@ public abstract class StepSse {
} }
}); });
try { try {
addFileMsgCusLog("step " + getStep() + ": " + name + " start");
exec(); exec();
setFinish(true); setFinish(true);
} catch (Exception e) { } catch (Exception e) {
addMsg(ExceptionUtil.stacktraceToString(e)); addFileMsgLog(ExceptionUtil.stacktraceToString(e));
send(); send();
setFinish(false); setFinish(false);
} }
...@@ -168,6 +174,9 @@ public abstract class StepSse { ...@@ -168,6 +174,9 @@ public abstract class StepSse {
public void setFinish(boolean status) { public void setFinish(boolean status) {
this.status = status ? 2 : 0; this.status = status ? 2 : 0;
addFileMsgCusLog(
"step " + getStep() + ": " + name + " " + (status ? "finished" : "failed"));
sendSync(); sendSync();
sendMsg(getEndLog()); sendMsg(getEndLog());
...@@ -202,6 +211,8 @@ public abstract class StepSse { ...@@ -202,6 +211,8 @@ public abstract class StepSse {
e.printStackTrace(); e.printStackTrace();
} }
}); });
// Manual GC is required here to release file IO(此处需要手动GC,释放文件IO)
System.gc();
} }
public int getStep() { public int getStep() {
...@@ -225,18 +236,20 @@ public abstract class StepSse { ...@@ -225,18 +236,20 @@ public abstract class StepSse {
// "status":1 # 2完成 1进行中 0失败 // "status":1 # 2完成 1进行中 0失败
// //
// } // }
Object dataResult =
(data instanceof List) ? StrUtil.join("\n", data) : JSONUtil.toJsonStr(data);
return Dict.create() return Dict.create()
.set("type", 2) .set("type", 1)
.set("currentStep", getStep()) .set("currentStep", getStep())
.set("resultType", 1) .set("resultType", 1)
.set("data", JSONUtil.toJsonStr(data)) .set("data", dataResult)
.set("currentStepName", name) .set("currentStepName", name)
.set("status", status); .set("status", status);
} }
protected Dict getLog(String data) { protected Dict getLog(String data) {
return Dict.create() return Dict.create()
.set("type", 2) .set("type", 1)
.set("currentStep", getStep()) .set("currentStep", getStep())
.set("resultType", 1) .set("resultType", 1)
.set("data", data) .set("data", data)
...@@ -250,7 +263,7 @@ public abstract class StepSse { ...@@ -250,7 +263,7 @@ public abstract class StepSse {
protected Dict getEndLog() { protected Dict getEndLog() {
return Dict.create() return Dict.create()
.set("type", 3) .set("type", 1)
.set("currentStep", getStep()) .set("currentStep", getStep())
.set("resultType", 1) .set("resultType", 1)
.set("currentStepName", name) .set("currentStepName", name)
...@@ -268,7 +281,7 @@ public abstract class StepSse { ...@@ -268,7 +281,7 @@ public abstract class StepSse {
} }
public void getStatus(int step, int status, List<Dict> data) { public void getStatus(int step, int status, List<Dict> data) {
Dict result = new Dict().set("step", getStep()).set("name", name); Dict result = new Dict().set("step", getStep()).set("name", name).set("status", -1);
if (getStep() <= step) { if (getStep() <= step) {
Instant instant = Instant instant =
FileUtil.getAttributes(getLogFile().toPath(), true).creationTime().toInstant(); FileUtil.getAttributes(getLogFile().toPath(), true).creationTime().toInstant();
...@@ -278,7 +291,7 @@ public abstract class StepSse { ...@@ -278,7 +291,7 @@ public abstract class StepSse {
new DateTime(instant).toString(DatePattern.NORM_DATETIME_PATTERN)) new DateTime(instant).toString(DatePattern.NORM_DATETIME_PATTERN))
.set("status", getStep() < step ? 2 : status); .set("status", getStep() < step ? 2 : status);
} else { } else {
result.set("startTime", null).set("status", null); result.set("startTime", null);
} }
data.add(result); data.add(result);
if (nexStepSse != null) { if (nexStepSse != null) {
......
...@@ -32,6 +32,21 @@ import lombok.Setter; ...@@ -32,6 +32,21 @@ import lombok.Setter;
@Getter @Getter
public class StepState implements Serializable { public class StepState implements Serializable {
private Integer currentStep; private Integer currentStep;
// 1.log 2.data
private Integer type;
private Object content;
/** 2-success 1-process 0-failed */ /** 2-success 1-process 0-failed */
private Integer status; private Integer status;
private Boolean history;
public static StepState genHistoryLog(Integer currentStep, Integer status, String log) {
StepState stepState = new StepState();
stepState.setHistory(true);
stepState.setContent(log);
stepState.setType(1);
stepState.setCurrentStep(currentStep);
stepState.setStatus(status);
return stepState;
}
} }
...@@ -85,6 +85,7 @@ public class AnalysisUdfClassStepSse extends StepSse { ...@@ -85,6 +85,7 @@ public class AnalysisUdfClassStepSse extends StepSse {
v.stream().map(Class::getName).collect(Collectors.toList())); v.stream().map(Class::getName).collect(Collectors.toList()));
dataList.add(gitAnalysisJarDTO); dataList.add(gitAnalysisJarDTO);
}); });
String data = JSONUtil.toJsonStr(dataList); String data = JSONUtil.toJsonStr(dataList);
sendMsg(getList(null).set("data", data)); sendMsg(getList(null).set("data", data));
......
/*
*
* 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.sse.git;
import org.dinky.dto.GitAnalysisJarDTO;
import org.dinky.function.data.model.Env;
import org.dinky.function.util.UDFUtil;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
public class AnalysisUdfPythonStepSse extends StepSse {
public AnalysisUdfPythonStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("analysis udf", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
File zipFile = (File) params.get("zipFile");
File projectFile = (File) params.get("projectFile");
List<String> pythonUdfList =
UDFUtil.getPythonUdfList(Env.getPath(), projectFile.getAbsolutePath());
GitAnalysisJarDTO gitAnalysisJarDTO = new GitAnalysisJarDTO();
gitAnalysisJarDTO.setJarPath(zipFile.getAbsolutePath());
gitAnalysisJarDTO.setClassList(pythonUdfList);
List<GitAnalysisJarDTO> dataList = CollUtil.newArrayList(gitAnalysisJarDTO);
String data = JSONUtil.toJsonStr(dataList);
sendMsg(getList(null).set("data", data));
FileUtil.appendString(data, getLogFile(), StandardCharsets.UTF_8);
// write result
GitProject gitProject = (GitProject) params.get("gitProject");
gitProject.setUdfClassMapList(data);
gitProject.updateById();
}
}
...@@ -19,9 +19,7 @@ ...@@ -19,9 +19,7 @@
package org.dinky.sse.git; package org.dinky.sse.git;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse; import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository;
import org.dinky.utils.MavenUtil; import org.dinky.utils.MavenUtil;
import java.io.File; import java.io.File;
...@@ -32,9 +30,7 @@ import java.util.stream.Collectors; ...@@ -32,9 +30,7 @@ import java.util.stream.Collectors;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
/** /**
* @author ZackYoung * @author ZackYoung
...@@ -54,20 +50,11 @@ public class GetJarsStepSse extends StepSse { ...@@ -54,20 +50,11 @@ public class GetJarsStepSse extends StepSse {
@Override @Override
public void exec() { public void exec() {
GitProject gitProject = (GitProject) params.get("gitProject"); List<File> jars = MavenUtil.getJars((File) params.get("pom"));
String pom =
Opt.ofBlankAble(gitProject.getPom())
.orElse(
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()),
gitProject.getBranch())
.getAbsolutePath());
List<File> jars = MavenUtil.getJars(new File(pom));
List<String> pathList = List<String> pathList =
jars.stream().map(File::getAbsolutePath).collect(Collectors.toList()); jars.stream().map(File::getAbsolutePath).collect(Collectors.toList());
addFileLog(pathList); addFileMsg(pathList);
params.put("jarPath", pathList); params.put("jarPath", pathList);
} }
......
...@@ -50,12 +50,11 @@ public class GitCloneStepSse extends StepSse { ...@@ -50,12 +50,11 @@ public class GitCloneStepSse extends StepSse {
@Override @Override
public void exec() { public void exec() {
addFileMsgLog("git clone start");
GitProject gitProject = (GitProject) params.get("gitProject"); GitProject gitProject = (GitProject) params.get("gitProject");
GitRepository gitRepository = GitRepository gitRepository =
new GitRepository(BeanUtil.toBean(gitProject, GitProjectDTO.class)); new GitRepository(BeanUtil.toBean(gitProject, GitProjectDTO.class));
gitRepository.cloneAndPull(gitProject.getName(), gitProject.getBranch()); gitRepository.cloneAndPull(
addFileMsgLog("git clone finish"); gitProject.getName(), gitProject.getBranch(), getLogFile(), this::addMsg);
} }
} }
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.sse.git; package org.dinky.sse.git;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse; import org.dinky.sse.StepSse;
import org.dinky.utils.MavenUtil; import org.dinky.utils.MavenUtil;
...@@ -52,6 +53,17 @@ public class HeadStepSse extends StepSse { ...@@ -52,6 +53,17 @@ public class HeadStepSse extends StepSse {
} }
private void checkEnv() { private void checkEnv() {
GitProject gitProject = (GitProject) params.get("gitProject");
switch (gitProject.getCodeType()) {
case 1:
checkJava();
break;
case 2:
checkPython();
}
}
private void checkJava() {
String mavenHome = MavenUtil.getMavenHome(); String mavenHome = MavenUtil.getMavenHome();
if (StrUtil.isBlank(mavenHome)) { if (StrUtil.isBlank(mavenHome)) {
...@@ -59,6 +71,9 @@ public class HeadStepSse extends StepSse { ...@@ -59,6 +71,9 @@ public class HeadStepSse extends StepSse {
setFinish(false); setFinish(false);
} }
String mavenVersionMsg = MavenUtil.getMavenVersion(); String mavenVersionMsg = MavenUtil.getMavenVersion();
mavenVersionMsg += "\n Your Maven Home is: " + mavenHome;
addFileMsgLog(mavenVersionMsg); addFileMsgLog(mavenVersionMsg);
} }
private void checkPython() {}
} }
...@@ -24,7 +24,10 @@ import org.dinky.sse.StepSse; ...@@ -24,7 +24,10 @@ import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository; import org.dinky.utils.GitRepository;
import org.dinky.utils.MavenUtil; import org.dinky.utils.MavenUtil;
import java.io.File;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
...@@ -32,8 +35,8 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; ...@@ -32,8 +35,8 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
/** /**
...@@ -55,23 +58,38 @@ public class MavenStepSse extends StepSse { ...@@ -55,23 +58,38 @@ public class MavenStepSse extends StepSse {
@Override @Override
public void exec() { public void exec() {
GitProject gitProject = (GitProject) params.get("gitProject"); GitProject gitProject = (GitProject) params.get("gitProject");
String pom = File pom =
Opt.ofBlankAble(gitProject.getPom()) FileUtil.file(
.orElse( GitRepository.getProjectDir(gitProject.getName()), gitProject.getBranch());
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()), File buildDir =
gitProject.getBranch()) FileUtil.mkdir(
.getAbsolutePath()); new File(
GitRepository.getProjectBuildDir(gitProject.getName()),
gitProject.getBranch()));
Arrays.stream(
Objects.requireNonNull(
pom.listFiles(pathname -> !".git".equals(pathname.getName()))))
.forEach(f -> FileUtil.copy(f, buildDir, true));
pom = buildDir;
if (StrUtil.isNotBlank(gitProject.getPom())) {
pom = new File(pom, gitProject.getPom());
}
Assert.isTrue(pom.exists(), "pom not exists!");
boolean state = boolean state =
MavenUtil.build( MavenUtil.build(
null, MavenUtil.getMavenSettingsPath(),
pom, pom.getAbsolutePath(),
null, null,
null, null,
getLogFile().getAbsolutePath(), getLogFile().getAbsolutePath(),
CollUtil.newArrayList("clean", "package"), CollUtil.newArrayList("clean", "package"),
StrUtil.split(gitProject.getBuildArgs(), " "), StrUtil.split(gitProject.getBuildArgs(), " "),
this::addMsg); this::addMsg);
params.put("pom", pom);
if (!state) { if (!state) {
setFinish(false); setFinish(false);
} }
......
/*
*
* 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.sse.git;
import org.dinky.model.GitProject;
import org.dinky.sse.StepSse;
import org.dinky.utils.GitRepository;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ZipUtil;
public class PythonZipStepSse extends StepSse {
public PythonZipStepSse(
int sleep,
List<SseEmitter> emitterList,
Dict params,
AtomicInteger msgId,
AtomicInteger stepAtomic,
ExecutorService cachedThreadPool) {
super("build python zip", sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
}
@Override
public void exec() {
GitProject gitProject = (GitProject) params.get("gitProject");
File file =
FileUtil.file(
GitRepository.getProjectDir(gitProject.getName()), gitProject.getBranch());
File zipFile = ZipUtil.zip(file);
addFileMsgLog("ZipFile Path is: " + zipFile);
params.put("zipFile", zipFile);
params.put("projectFile", file);
}
}
...@@ -25,13 +25,15 @@ import org.dinky.process.exception.DinkyException; ...@@ -25,13 +25,15 @@ import org.dinky.process.exception.DinkyException;
import org.dinky.sse.DoneStepSse; import org.dinky.sse.DoneStepSse;
import org.dinky.sse.StepSse; import org.dinky.sse.StepSse;
import org.dinky.sse.git.AnalysisUdfClassStepSse; import org.dinky.sse.git.AnalysisUdfClassStepSse;
import org.dinky.sse.git.AnalysisUdfPythonStepSse;
import org.dinky.sse.git.GetJarsStepSse; import org.dinky.sse.git.GetJarsStepSse;
import org.dinky.sse.git.GitCloneStepSse; import org.dinky.sse.git.GitCloneStepSse;
import org.dinky.sse.git.HeadStepSse; import org.dinky.sse.git.HeadStepSse;
import org.dinky.sse.git.MavenStepSse; import org.dinky.sse.git.MavenStepSse;
import org.dinky.sse.git.PythonZipStepSse;
import java.io.File; import java.io.File;
import java.nio.charset.StandardCharsets; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -39,19 +41,18 @@ import java.util.concurrent.ConcurrentHashMap; ...@@ -39,19 +41,18 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
/** /**
* @author ZackYoung * @author ZackYoung
* @since 0.8.0 * @since 0.8.0
*/ */
public final class GitProjectStepSseFactory { public final class GitProjectStepSseFactory {
private static Map<Integer, List<SseEmitter>> sseEmitterMap = new ConcurrentHashMap<>(); private static Map<Integer, List<SseEmitter>> sseEmitterMap = new ConcurrentHashMap<>();
private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); private static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
...@@ -61,6 +62,9 @@ public final class GitProjectStepSseFactory { ...@@ -61,6 +62,9 @@ public final class GitProjectStepSseFactory {
StepSse headStepSse = getHeadStepPlan(gitProject.getCodeType(), sleep, emitterList, params); StepSse headStepSse = getHeadStepPlan(gitProject.getCodeType(), sleep, emitterList, params);
cachedThreadPool.execute(headStepSse::main); cachedThreadPool.execute(headStepSse::main);
gitProject.setBuildStep(1);
gitProject.setBuildState(1);
gitProject.updateById();
sseEmitterMap.put(gitProject.getId(), emitterList); sseEmitterMap.put(gitProject.getId(), emitterList);
} }
...@@ -70,57 +74,82 @@ public final class GitProjectStepSseFactory { ...@@ -70,57 +74,82 @@ public final class GitProjectStepSseFactory {
AtomicInteger msgId = new AtomicInteger(1); AtomicInteger msgId = new AtomicInteger(1);
AtomicInteger stepAtomic = new AtomicInteger(1); AtomicInteger stepAtomic = new AtomicInteger(1);
if (codeType.equals(1)) { HeadStepSse headStepSse =
HeadStepSse headStepSse = new HeadStepSse(sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
new HeadStepSse( GitCloneStepSse gitCloneStepSse =
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); new GitCloneStepSse(
GitCloneStepSse gitCloneStepSse = sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
new GitCloneStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); DoneStepSse doneStepSse =
MavenStepSse mavenStepSse = new DoneStepSse(sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
new MavenStepSse( headStepSse.setNexStepSse(gitCloneStepSse);
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); switch (codeType) {
GetJarsStepSse getJarsStepSse = case 1:
new GetJarsStepSse( MavenStepSse mavenStepSse =
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); new MavenStepSse(
AnalysisUdfClassStepSse analysisUdfClassStepSse = sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
new AnalysisUdfClassStepSse( GetJarsStepSse getJarsStepSse =
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); new GetJarsStepSse(
DoneStepSse doneStepSse = sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
new DoneStepSse( AnalysisUdfClassStepSse analysisUdfClassStepSse =
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool); new AnalysisUdfClassStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
headStepSse.setNexStepSse(gitCloneStepSse); gitCloneStepSse.setNexStepSse(mavenStepSse);
gitCloneStepSse.setNexStepSse(mavenStepSse); mavenStepSse.setNexStepSse(getJarsStepSse);
mavenStepSse.setNexStepSse(getJarsStepSse); getJarsStepSse.setNexStepSse(analysisUdfClassStepSse);
getJarsStepSse.setNexStepSse(analysisUdfClassStepSse); analysisUdfClassStepSse.setNexStepSse(doneStepSse);
analysisUdfClassStepSse.setNexStepSse(doneStepSse); return headStepSse;
return headStepSse; case 2:
} else { PythonZipStepSse pythonZipStepSse =
throw new DinkyException("only support java!"); new PythonZipStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
AnalysisUdfPythonStepSse analysisUdfPythonStepSse =
new AnalysisUdfPythonStepSse(
sleep, emitterList, params, msgId, stepAtomic, cachedThreadPool);
gitCloneStepSse.setNexStepSse(pythonZipStepSse);
pythonZipStepSse.setNexStepSse(analysisUdfPythonStepSse);
analysisUdfPythonStepSse.setNexStepSse(doneStepSse);
return headStepSse;
default:
throw new DinkyException("only support Java & Python!");
} }
} }
public static void observe(SseEmitter emitter, GitProject gitProject, Dict params) { public static void observe(SseEmitter emitter, GitProject gitProject, Dict params) {
List<Dict> dataList = new ArrayList<>(); List<Dict> dataList = new ArrayList<>();
Integer state = gitProject.getExecState(); Integer state = gitProject.getExecState();
Integer step = gitProject.getBuildStep(); Integer step = gitProject.getBuildStep();
getHeadStepPlan(gitProject.getCodeType(), 0, null, params).getStatus(step, state, dataList); getHeadStepPlan(gitProject.getCodeType(), 0, null, params).getStatus(step, state, dataList);
try { try {
emitter.send(SseEmitter.event().data(StepResult.getStepInfo(step, dataList))); emitter.send(
SseEmitter.event()
.data(
StepResult.getStepInfo(
step, gitProject.getBuildState(), dataList)));
if (gitProject.getBuildState() == 3) {
StepResult data =
StepResult.getData(
gitProject.getCodeType().equals(1) ? 5 : 4,
state,
gitProject.getUdfClassMapList());
emitter.send(SseEmitter.event().data(data));
}
File logDir = getLogDir(gitProject.getName(), gitProject.getBranch()); File logDir = getLogDir(gitProject.getName(), gitProject.getBranch());
List<String> msgList = IntStream.range(1, step + 1)
FileUtil.readLines(new File(logDir, step + ".log"), StandardCharsets.UTF_8); .forEach(
StepResult stepResult = s -> {
StepResult.builder() String log = FileUtil.readUtf8String(new File(logDir, s + ".log"));
.currentStep(step) StepResult stepResult =
.status(state) StepResult.genLog(s, step == s ? state : 2, log, step != s);
.data(StrUtil.join("\n", msgList)) try {
.type(2) emitter.send(SseEmitter.event().data(stepResult));
.build(); } catch (IOException e) {
emitter.send(SseEmitter.event().id("2").data(stepResult)); e.printStackTrace();
}
});
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -24,9 +24,10 @@ import org.dinky.function.constant.PathConstant; ...@@ -24,9 +24,10 @@ import org.dinky.function.constant.PathConstant;
import org.dinky.process.exception.DinkyException; import org.dinky.process.exception.DinkyException;
import java.io.File; import java.io.File;
import java.io.PrintWriter; import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer;
import org.eclipse.jgit.api.CloneCommand; import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.Git;
...@@ -49,6 +50,7 @@ import com.jcraft.jsch.Session; ...@@ -49,6 +50,7 @@ import com.jcraft.jsch.Session;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil; import cn.hutool.http.HttpUtil;
...@@ -64,7 +66,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -64,7 +66,7 @@ import lombok.extern.slf4j.Slf4j;
public class GitRepository { public class GitRepository {
private static final String BRANCH_PREFIX = "refs/heads/"; private static final String BRANCH_PREFIX = "refs/heads/";
/** 匹配 ssh格式 git 地址 */ /** 匹配 ssh格式 git 地址 */
private static final String SSH_REGEX = "^git@[\\w.]+:[\\w\\.||-]+/(\\w)+\\.git$"; private static final String SSH_REGEX = "^git@[\\w\\.]+:([\\w_-]+)/(.*?)\\.git$";
private String url; private String url;
private String username; private String username;
...@@ -79,7 +81,11 @@ public class GitRepository { ...@@ -79,7 +81,11 @@ public class GitRepository {
} }
public File cloneAndPull(String projectName, String branch) { public File cloneAndPull(String projectName, String branch) {
return cloneAndPull(projectName, branch, null, null);
}
public File cloneAndPull(
String projectName, String branch, File logFile, Consumer<String> consumer) {
List<String> branchList = getBranchList(); List<String> branchList = getBranchList();
if (!branchList.contains(branch)) { if (!branchList.contains(branch)) {
throw new DinkyException( throw new DinkyException(
...@@ -112,9 +118,22 @@ public class GitRepository { ...@@ -112,9 +118,22 @@ public class GitRepository {
.findGitDir() .findGitDir()
.build(); .build();
git = new Git(repository); git = new Git(repository);
git.pull() git.pull()
.setProgressMonitor(new TextProgressMonitor(new PrintWriter(System.out))) .setProgressMonitor(
new TextProgressMonitor(
new StringWriter() {
@Override
public void write(String str) {
if (logFile != null) {
FileUtil.appendUtf8String(str, logFile);
}
if (consumer != null) {
consumer.accept(str);
}
System.out.println(str);
super.write(str);
}
}))
.call(); .call();
git.close(); git.close();
} else { } else {
...@@ -131,6 +150,10 @@ public class GitRepository { ...@@ -131,6 +150,10 @@ public class GitRepository {
return FileUtil.file(PathConstant.TMP_PATH, "git", projectName); return FileUtil.file(PathConstant.TMP_PATH, "git", projectName);
} }
public static File getProjectBuildDir(String projectName) {
return FileUtil.file(PathConstant.TMP_PATH, "git_build", projectName);
}
/** /**
* 获取分支列表(提供拼音排序) * 获取分支列表(提供拼音排序)
* *
...@@ -187,6 +210,9 @@ public class GitRepository { ...@@ -187,6 +210,9 @@ public class GitRepository {
*/ */
private <T extends TransportCommand<T, ?>> T initCommand(T command) { private <T extends TransportCommand<T, ?>> T initCommand(T command) {
if (isSshGitUrl(url)) { if (isSshGitUrl(url)) {
Assert.notBlank(privateKey, "The private key address cannot be empty.");
Assert.isTrue(FileUtil.exist(privateKey), "The private key address does not exist.");
TransportConfigCallback sshSessionFactory = TransportConfigCallback sshSessionFactory =
getTransportConfigCallback(privateKey, password); getTransportConfigCallback(privateKey, password);
command.setTransportConfigCallback(sshSessionFactory); command.setTransportConfigCallback(sshSessionFactory);
......
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
package org.dinky.utils; package org.dinky.utils;
import org.dinky.function.constant.PathConstant;
import org.dinky.model.SystemConfiguration;
import org.dinky.process.exception.DinkyException; import org.dinky.process.exception.DinkyException;
import org.apache.maven.shared.invoker.DefaultInvocationRequest; import org.apache.maven.shared.invoker.DefaultInvocationRequest;
...@@ -40,8 +42,12 @@ import cn.hutool.core.collection.CollUtil; ...@@ -40,8 +42,12 @@ import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil; 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 cn.hutool.system.SystemUtil;
/** /**
...@@ -51,6 +57,9 @@ import cn.hutool.system.SystemUtil; ...@@ -51,6 +57,9 @@ import cn.hutool.system.SystemUtil;
public class MavenUtil { public class MavenUtil {
private static final List<String> COMMON_BIN_PATH = CollUtil.newArrayList("/usr", "/usr/local"); private static final List<String> COMMON_BIN_PATH = CollUtil.newArrayList("/usr", "/usr/local");
private static final TemplateEngine ENGINE =
new FreemarkerEngine(
new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
public static boolean build(String setting, String pom, String logFile, List<String> args) { public static boolean build(String setting, String pom, String logFile, List<String> args) {
return build( return build(
...@@ -134,12 +143,17 @@ public class MavenUtil { ...@@ -134,12 +143,17 @@ public class MavenUtil {
request.addArg("-v"); request.addArg("-v");
List<String> msg = new LinkedList<>(); List<String> msg = new LinkedList<>();
List<String> errMsg = new LinkedList<>();
request.setOutputHandler(msg::add); request.setOutputHandler(msg::add);
request.setErrorHandler(errMsg::add);
Invoker invoker = new DefaultInvoker(); Invoker invoker = new DefaultInvoker();
try { try {
invoker.execute(request); int exitCode = invoker.execute(request).getExitCode();
if (exitCode != 0) {
throw new RuntimeException(String.join("\n", errMsg));
}
} catch (MavenInvocationException e) { } catch (MavenInvocationException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
...@@ -191,4 +205,27 @@ public class MavenUtil { ...@@ -191,4 +205,27 @@ public class MavenUtil {
} }
} }
} }
public static String getMavenSettingsPath() {
SystemConfiguration systemConfiguration = SystemConfiguration.getInstances();
String mavenSettings = systemConfiguration.getMavenSettings();
if (StrUtil.isNotBlank(mavenSettings) && !FileUtil.isFile(mavenSettings)) {
throw new DinkyException("settings file is not exists,path: " + mavenSettings);
} else if (StrUtil.isBlank(mavenSettings)) {
Dict render =
Dict.create()
.set("repositoryUrl", systemConfiguration.getMavenRepository())
.set("repositoryUser", systemConfiguration.getMavenRepositoryUser())
.set(
"repositoryPassword",
systemConfiguration.getMavenRepositoryPassword());
String content = ENGINE.getTemplate("settings.xml").render(render);
File file =
FileUtil.writeUtf8String(
content,
FileUtil.file(PathConstant.TMP_PATH, "maven", "conf", "settings.xml"));
return file.getAbsolutePath();
}
return mavenSettings;
}
} }
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<localRepository>./../../maven/m2</localRepository>
<servers>
<server>
<id>dinky_mirror</id>
<username>${repositoryUser}</username>
<password>${repositoryPassword}</password>
</server>
</servers>
<mirrors>
<mirror>
<id>dinky_mirror</id>
<mirrorOf>central</mirrorOf>
<name>dink custom mirror</name>
<url>${repositoryUrl}</url>
<blocked>false</blocked>
</mirror>
</mirrors>
</settings>
/*
*
* 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 org.dinky.function.util.UDFUtil;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.junit.Ignore;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* @author ZackYoung
* @since 0.8.0
*/
@Disabled("This is local test!")
public class MavenUtilTests {
@Test
@Ignore
public void build() {
MavenUtil.build(
null,
"/Users/zackyoung/companyProjects/api-monitor/pom.xml",
"/usr/local/",
"/Users/zackyoung/.m2/repository",
"/Users/zackyoung/projects/ideaProjects/dlink/dinky-admin/tmp/git/build.log",
Arrays.asList("package"),
null,
null);
}
@Test
@Ignore
public void cloneAndBuild() {
String branch = "master";
File gitFile = new File("/Users/zackyoung/Desktop/test/git/api-monitor/" + branch);
String logFile = "/Users/zackyoung/Desktop/test/git/api-monitor/" + branch + "_log/3.log";
File pom = new File(gitFile, "pom.xml");
MavenUtil.build(
"/Volumes/文档及虚拟机/company/数宜信/OpenApi/settings2.xml",
pom.getAbsolutePath(),
logFile,
null);
}
@Test
@Ignore
public void getJars() {
String branch = "master";
File gitFile = new File("/Users/zackyoung/Desktop/test/git/api-monitor/" + branch);
String logFile = "/Users/zackyoung/Desktop/test/git/api-monitor/" + branch + "_log/3.log";
File pom = new File(gitFile, "pom.xml");
List<File> jars = MavenUtil.getJars(pom);
System.out.println(jars);
jars.parallelStream()
.forEach(
jar -> {
List<Class<?>> udfClassByJar = UDFUtil.getUdfClassByJar(jar);
System.out.println(udfClassByJar);
});
}
@Test
@Ignore
public void getVersion() {
System.out.println(MavenUtil.getMavenVersion());
}
@Test
@Ignore
public void getSettings() {
System.out.println(MavenUtil.getMavenSettingsPath());
}
}
...@@ -44,7 +44,11 @@ public class SystemConfiguration { ...@@ -44,7 +44,11 @@ public class SystemConfiguration {
Lists.newArrayList( Lists.newArrayList(
systemConfiguration.useRestAPI, systemConfiguration.useRestAPI,
systemConfiguration.sqlSeparator, systemConfiguration.sqlSeparator,
systemConfiguration.jobIdWait); systemConfiguration.jobIdWait,
systemConfiguration.mavenSettings,
systemConfiguration.mavenRepository,
systemConfiguration.mavenRepositoryUser,
systemConfiguration.mavenRepositoryPassword);
private Configuration useRestAPI = private Configuration useRestAPI =
new Configuration( new Configuration(
...@@ -64,6 +68,38 @@ public class SystemConfiguration { ...@@ -64,6 +68,38 @@ public class SystemConfiguration {
30, 30,
"提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)"); "提交 Application 或 PerJob 任务时获取 Job ID 的最大等待时间(秒)");
private Configuration mavenSettings =
new Configuration(
"mavenSettings",
"Maven Settings 文件路径",
ValueType.STRING,
"",
"Maven Settings File Path");
private Configuration mavenRepository =
new Configuration(
"mavenRepository",
"Maven Central Repository",
ValueType.STRING,
"https://maven.aliyun.com/nexus/content/repositories/central",
"Maven private server address");
private Configuration mavenRepositoryUser =
new Configuration(
"mavenRepositoryUser",
"Maven Central Repository Auth User",
ValueType.STRING,
"",
"Maven private server authentication username");
private Configuration mavenRepositoryPassword =
new Configuration(
"mavenRepositoryPassword",
"Maven Central Repository Auth Password",
ValueType.STRING,
"",
"Maven private server authentication password");
public void setConfiguration(JsonNode jsonNode) { public void setConfiguration(JsonNode jsonNode) {
CONFIGURATION_LIST.stream() CONFIGURATION_LIST.stream()
.filter(t -> jsonNode.has(t.getName())) .filter(t -> jsonNode.has(t.getName()))
...@@ -121,6 +157,22 @@ public class SystemConfiguration { ...@@ -121,6 +157,22 @@ public class SystemConfiguration {
this.jobIdWait.setValue(jobIdWait); this.jobIdWait.setValue(jobIdWait);
} }
public String getMavenSettings() {
return (String) mavenSettings.getValue();
}
public String getMavenRepository() {
return (String) mavenRepository.getValue();
}
public String getMavenRepositoryUser() {
return (String) mavenRepositoryUser.getValue();
}
public String getMavenRepositoryPassword() {
return (String) mavenRepositoryPassword.getValue();
}
enum ValueType { enum ValueType {
STRING, STRING,
INT, INT,
......
...@@ -34,14 +34,19 @@ import org.dinky.pool.ClassEntity; ...@@ -34,14 +34,19 @@ import org.dinky.pool.ClassEntity;
import org.dinky.pool.ClassPool; import org.dinky.pool.ClassPool;
import org.dinky.process.exception.DinkyException; import org.dinky.process.exception.DinkyException;
import org.apache.flink.client.python.PythonFunctionFactory;
import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.python.PythonOptions;
import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.catalog.FunctionLanguage;
import org.apache.flink.table.functions.UserDefinedFunction; import org.apache.flink.table.functions.UserDefinedFunction;
import org.apache.flink.table.functions.UserDefinedFunctionHelper; import org.apache.flink.table.functions.UserDefinedFunctionHelper;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
...@@ -52,6 +57,7 @@ import java.util.Map; ...@@ -52,6 +57,7 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -59,6 +65,7 @@ import org.slf4j.LoggerFactory; ...@@ -59,6 +65,7 @@ import org.slf4j.LoggerFactory;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.ClassScanner; import cn.hutool.core.lang.ClassScanner;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
...@@ -262,7 +269,7 @@ public class UDFUtil { ...@@ -262,7 +269,7 @@ public class UDFUtil {
* 得到udf版本和构建jar * 得到udf版本和构建jar
* *
* @param codeList 代码列表 * @param codeList 代码列表
* @return {@link java.lang.String} * @return {@link String}
*/ */
@Deprecated @Deprecated
public static String getUdfFileAndBuildJar(List<UDF> codeList) { public static String getUdfFileAndBuildJar(List<UDF> codeList) {
...@@ -391,8 +398,73 @@ public class UDFUtil { ...@@ -391,8 +398,73 @@ public class UDFUtil {
} catch (ValidationException e) { } catch (ValidationException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
return classList; return classList;
} }
public static List<String> getPythonUdfList(String pythonPath, String udfFile) {
File checkFile = new File(PathConstant.TMP_PATH, "getPyFuncList.py");
if (!checkFile.exists()) {
FileUtil.writeUtf8String(ResourceUtil.readUtf8Str("getPyFuncList.py"), checkFile);
}
List<String> udfNameList =
execPyAndGetUdfNameList(pythonPath, checkFile.getAbsolutePath(), udfFile);
List<String> successUdfList = new ArrayList<>();
if (CollUtil.isEmpty(udfNameList)) {
return new ArrayList<>();
}
for (String udfName : udfNameList) {
if (StrUtil.isBlank(udfName)) {
continue;
}
Configuration configuration = new Configuration();
configuration.set(PythonOptions.PYTHON_FILES, udfFile + ".zip");
configuration.set(PythonOptions.PYTHON_CLIENT_EXECUTABLE, pythonPath);
configuration.set(PythonOptions.PYTHON_EXECUTABLE, pythonPath);
System.out.println(udfName);
try {
PythonFunctionFactory.getPythonFunction(udfName, configuration, null);
successUdfList.add(udfName);
} catch (Exception e) {
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 =
StrUtil.join(
" ",
Arrays.asList(
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) {
throw new DinkyException(e);
}
}
} }
import importlib
import sys
import platform
import pyflink
# import ast
# from pathlib import Path
# from typing import Callable, AnyStr
# notFuncName: list = ["__call__", "eval"]
# udfNameList: list = []
# is_udf: Callable[[AnyStr], bool] = lambda func: isinstance(getattr(importlib.import_module(path.stem), func),
# pyflink.table.udf.UserDefinedFunctionWrapper)
#
# # filePath: str = sys.argv[1]
# # if str is None:
# # raise Exception("请输入文件路径")
# # path = Path(filePath)
# # if path.parent.name != "":
# # sys.path.append(path.parent.__str__())
# with open(filePath, 'r', encoding='utf8') as f:
# tree = ast.parse(f.read())
#
# for node in ast.walk(tree):
# if isinstance(node, ast.FunctionDef):
# try:
# if node.args.args[0].arg == "self":
# continue
# except Exception as e:
# pass
# if notFuncName.__contains__(node.name):
# continue
#
# if not is_udf(node.name):
# continue
# udfNameList.append(node.name)
#
# try:
# if isinstance(node.targets[0], ast.Name) and is_udf(node.targets[0].id):
# udfNameList.append(node.targets[0].id)
# except Exception as e:
# pass
import os
if len(sys.argv) < 2:
raise Exception("Please enter the file path")
project_path: str = sys.argv[1]
udf_name_list = set()
def list_modules(root_dir):
"""返回给定目录下所有模块和子模块的名称"""
modules = []
for dirpath, _, filenames in os.walk(root_dir):
for filename in filenames:
if filename.endswith(".py"):
p_ = project_path.replace(os.sep, ".")
module_name = os.path.splitext(os.path.join(dirpath, filename))[0].replace(os.sep, ".").replace(
p_ + ".", "")
modules.append(module_name.replace(root_dir, ""))
return modules
if __name__ == '__main__':
modules = list_modules(project_path)
sys.path.append(project_path)
for module_name in modules:
try:
module = importlib.import_module(module_name)
for m in dir(module):
if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):
udf_name_list.add(module.__name__ + "." + m)
except Exception as e:
pass
print(str.join(",", udf_name_list))
# import pkgutil
# for _, module_name, _ in pkgutil.walk_packages([""]):
# if module_name == os.path.splitext(os.path.basename(__file__))[0]:
# continue
# try:
# print(module_name)
# module = importlib.import_module(module_name)
# for m in dir(module):
# if isinstance(getattr(module, m), pyflink.table.udf.UserDefinedFunctionWrapper):
# udfNameList.add(module.__name__ + "." + m)
#
# except Exception as e:
# pass
#
# print(str.join(",", udfNameList))
...@@ -22,11 +22,25 @@ package org.dinky.function.util; ...@@ -22,11 +22,25 @@ package org.dinky.function.util;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.dinky.process.exception.DinkyException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Function; import java.util.function.Function;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.junit.Ignore;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
class UDFUtilTest { class UDFUtilTest {
@Test @Test
...@@ -54,4 +68,45 @@ class UDFUtilTest { ...@@ -54,4 +68,45 @@ class UDFUtilTest {
c.apply( c.apply(
"create tempOrary system function a as abc using jar 'path', jar 'path/2'")); "create tempOrary system function a as abc using jar 'path', jar 'path/2'"));
} }
@Test
@Ignore
@Disabled("this is local test!")
void pythonTest() throws ExecutionException {
String pythonPath = "python";
String udfFile = "C:\\project\\companyProjects\\dinky-quickstart-python\\udtf.py";
List<String> pythonUdfList = UDFUtil.getPythonUdfList(pythonPath, udfFile);
}
private List<String> execPyAndGetUdfNameList(String pyPath, String pyFile, String checkPyFile) {
Process process;
try {
// 运行Python3脚本的命令,换成自己的即可
String shell =
StrUtil.join(
" ",
Arrays.asList(
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) {
throw new DinkyException(e);
}
}
} }
...@@ -43,6 +43,7 @@ export default defineConfig({ ...@@ -43,6 +43,7 @@ export default defineConfig({
* @doc https://umijs.org/docs/api/config#hash * @doc https://umijs.org/docs/api/config#hash
*/ */
hash: true, hash: true,
esbuildMinifyIIFE: true,
history: { history: {
type: 'hash', type: 'hash',
}, },
...@@ -51,9 +52,9 @@ export default defineConfig({ ...@@ -51,9 +52,9 @@ export default defineConfig({
* @description 设置 ie11 不一定完美兼容,需要检查自己使用的所有依赖 * @description 设置 ie11 不一定完美兼容,需要检查自己使用的所有依赖
* @doc https://umijs.org/docs/api/config#targets * @doc https://umijs.org/docs/api/config#targets
*/ */
targets: { // targets: {
ie: 11, // ie: 11,
}, // },
/** /**
* @name 路由的配置,不在路由中引入的文件不会编译 * @name 路由的配置,不在路由中引入的文件不会编译
* @description 只支持 path,component,routes,redirect,wrappers,title 的配置 * @description 只支持 path,component,routes,redirect,wrappers,title 的配置
......
...@@ -77,6 +77,7 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -77,6 +77,7 @@ const CodeShow = (props: CodeShowFormProps) => {
const {ScrollType} = editor; const {ScrollType} = editor;
const [scrollBeyondLastLine] = useState<boolean>(options.scrollBeyondLastLine);
const [loading, setLoading] = useState<boolean>(false); const [loading, setLoading] = useState<boolean>(false);
const [stopping, setStopping] = useState<boolean>(false); const [stopping, setStopping] = useState<boolean>(false);
...@@ -164,6 +165,16 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -164,6 +165,16 @@ const CodeShow = (props: CodeShowFormProps) => {
setEditorRef(editor); setEditorRef(editor);
editor.layout(); editor.layout();
editor.focus(); editor.focus();
if (scrollBeyondLastLine){
editor.onDidChangeModelContent(()=>{
const lineCount = editor.getModel()?.getLineCount() as number;
if (lineCount>20){
editor.revealLine(lineCount);
}else {
editor.revealLine(1);
}
});
}
}; };
...@@ -205,6 +216,7 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -205,6 +216,7 @@ const CodeShow = (props: CodeShowFormProps) => {
fixedOverflowWidgets: true, fixedOverflowWidgets: true,
autoClosingDelete: "always", autoClosingDelete: "always",
lineNumbers, lineNumbers,
}} }}
editorDidMount={editorDidMount} editorDidMount={editorDidMount}
theme={theme ? theme : convertCodeEditTheme()} theme={theme ? theme : convertCodeEditTheme()}
......
...@@ -28,134 +28,85 @@ import {GitProject} from "@/types/RegCenter/data"; ...@@ -28,134 +28,85 @@ import {GitProject} from "@/types/RegCenter/data";
import {processColor} from "@/pages/RegCenter/GitProject/constans"; import {processColor} from "@/pages/RegCenter/GitProject/constans";
import JarShow from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow"; import JarShow from "@/pages/RegCenter/GitProject/components/BuildSteps/JarShow";
import {BuildStepsState} from "@/pages/RegCenter/GitProject/components/BuildSteps"; import {BuildStepsState} from "@/pages/RegCenter/GitProject/components/BuildSteps";
import {JsonArray} from "type-fest";
export type BuildMsgData = { export type BuildMsgData = {
type: number; // // 1 是log 2是部分状态 type: number; // // 1 是log 2是部分状态
currentStep: number; // 1:check env 2:git clone 3:maven build 4:get jars 5:analysis udf class currentStep: number; // 1:check env 2:git clone 3:maven build 4:get jars 5:analysis udf class
data: any; // if resultType is 1, data is log, else data is jar list or class list data: any; // if resultType is 1, data is log, else data is jar list or class list
status: number; // 2:finish 1:running 0:fail status: number; // 2:finish 1:running 0:fail
resultType?: number; // 1:log 2: jar list or class list resultType?: number; // 1:log 2: jar list or class list
log: string;
showList: boolean;
} }
type BuildStepsProps = { type BuildStepsProps = {
values: Partial<GitProject>; values: Partial<GitProject>;
steps: any[]; steps: any[];
currentDataMsg: any; currentDataMsg: any;
percent: number; percent: number;
currentStep: number; currentStep: number;
log: string;
showList: boolean;
} }
export const AutoSteps: React.FC<BuildStepsProps> = (props) => { export const AutoSteps: React.FC<BuildStepsProps> = (props) => {
const { const {
values, steps, values, steps,
currentDataMsg, percent, currentStep currentDataMsg, percent, currentStep, log,showList
} = props; } = props;
/**
/** * state
* state */
*/ const {token} = theme.useToken();
const {token} = theme.useToken();
const [currentStepStatus, setCurrentStepStatus] = useState<number>(currentStep); useEffect(() => {
const [currentPercent, seCurrenttPercent] = useState<number>(percent); }, []);
/** const contentStyle: React.CSSProperties = {
* 自动完成 lineHeight: "300px",
* 前提:sse发送的结果中得步骤值===当前步骤值,且sse返回数据的状态是 finish // textAlign: "center",
*/ color: token.colorTextTertiary,
const autoFinish = async () => { backgroundColor: token.colorFillAlter,
// status // 0是失败 1是进行中 2 完成 borderRadius: token.borderRadiusLG,
await SuccessMessageAsync(l("rc.gp.buildSuccess")); border: `1px dashed ${token.colorBorder}`,
}; marginTop: 16,
};
/**
* next step return <>
*/ <Steps status={"wait"}
const nextStep = () => { size={"small"}
// console.log("next step"); onChange={(current) => current}
setCurrentStepStatus(currentStepStatus + 1); type={"navigation"} responsive={true}
seCurrenttPercent(currentPercent + 20); current={currentStep-1} items={steps} percent={percent} initial={0}/>
<Progress percent={percent} strokeColor={processColor}/>
}; <div style={contentStyle}>
{
/** // if resultType is 1, data is log, else data is jar list or class list
* prev step !showList ?
*/ <CodeShow height={"50vh"} code={log || ""} language={"java"} options={{scrollBeyondLastLine: true}}
const prevStep = () => { showFloatButton={true}/>
setCurrentStepStatus(currentStepStatus - 1); :
<JarShow step={currentStep} data={log}/>
seCurrenttPercent(currentPercent - 20); }
</div>
}; {/*<div style={{marginTop: 24}}>*/}
{/* {currentStepStatus < steps.length - 1 && (*/}
console.log("哈哈哈哈", currentStepStatus); {/* <Button type="primary" onClick={() => nextStep()}>*/}
{/* {l("button.next")}*/}
/** {/* </Button>*/}
* 自动步进 {/* )}*/}
* 前提:sse发送的结果中得步骤值===当前步骤值,且sse返回数据的状态是 finish {/* {currentStepStatus > 0 && (*/}
*/ {/* <Button style={{margin: "0 8px"}} onClick={() => prevStep()}>*/}
const autoIncrementSteps = async () => { {/* {l("button.prev")}*/}
// console.log("autoIncrementSteps", currentStepStatus, currentDataMsg?.currentStep) {/* </Button>*/}
let currentItem = steps.at(currentDataMsg?.currentStep - 1); {/* )}*/}
{/*</div>*/}
await SuccessMessageAsync(currentItem.title); </>;
// console.log("autoIncrementSteps")
// status // 0是失败 1是进行中 2 完成
if ((currentDataMsg?.currentStep || 0) - 1 === currentStepStatus && currentDataMsg?.status === 2) {
await nextStep();
if ((currentDataMsg?.currentStep || 0) - 1 === 5 && currentStepStatus === 5 && currentDataMsg.status === 2) {
await autoFinish();
}
}
};
useEffect(() => {
autoIncrementSteps();
}, [currentStepStatus, currentDataMsg, currentPercent]);
const contentStyle: React.CSSProperties = {
lineHeight: "300px",
textAlign: "center",
color: token.colorTextTertiary,
backgroundColor: token.colorFillAlter,
borderRadius: token.borderRadiusLG,
border: `1px dashed ${token.colorBorder}`,
marginTop: 16,
};
return <>
<Steps status={"wait"}
size={"small"}
onChange={(current) => setCurrentStepStatus(current)}
type={"navigation"} responsive={true}
current={currentStepStatus} items={steps} percent={currentPercent} initial={0}/>
<Progress percent={percent} strokeColor={processColor}/>
<div style={contentStyle}>
{
// if resultType is 1, data is log, else data is jar list or class list
// currentDataMsg?.resultType === 1 ?
<CodeShow height={"50vh"} code={currentDataMsg?.data || ""} language={"java"}/>
// :
// <JarShow step={currentStepStatus} data={currentDataMsg?.data}/>
}
</div>
{/*<div style={{marginTop: 24}}>*/}
{/* {currentStepStatus < steps.length - 1 && (*/}
{/* <Button type="primary" onClick={() => nextStep()}>*/}
{/* {l("button.next")}*/}
{/* </Button>*/}
{/* )}*/}
{/* {currentStepStatus > 0 && (*/}
{/* <Button style={{margin: "0 8px"}} onClick={() => prevStep()}>*/}
{/* {l("button.prev")}*/}
{/* </Button>*/}
{/* )}*/}
{/*</div>*/}
</>;
}; };
...@@ -82,16 +82,16 @@ const ClassList: React.FC<ClassListProps> = (props) => { ...@@ -82,16 +82,16 @@ const ClassList: React.FC<ClassListProps> = (props) => {
columns={columns} columns={columns}
toolBarRender={false} toolBarRender={false}
showHeader={false} showHeader={false}
dataSource={JSON.parse(JSON.stringify(jarAndClassesList)) as BuildJarList[]} dataSource={jarAndClassesList as BuildJarList[]}
search={false} search={false}
rowKey="jarPath" rowKey="jarPath"
pagination={false} pagination={false}
// expandable={{ expandable={{
// expandRowByClick: true, expandRowByClick: true,
// expandedRowRender: record => { expandedRowRender: record => {
// return <List split className={"child-list"}>{buildExpandableList(record.classList)}</List>; return <List split className={"child-list"}>{buildExpandableList(record.classList)}</List>;
// } }
// }} }}
/> />
</>; </>;
}; };
......
...@@ -46,9 +46,10 @@ const JarShow: React.FC<JarShowProps> = (props) => { ...@@ -46,9 +46,10 @@ const JarShow: React.FC<JarShowProps> = (props) => {
return <> return <>
{ {
step === 4 ? <ClassList jarAndClassesList={resultData}/>
<JarList jarList={resultData}/> : // step === 4 ?
step === 5 ? <ClassList jarAndClassesList={resultData}/> : <Empty image={Empty.PRESENTED_IMAGE_DEFAULT}/> // <JarList jarList={resultData}/> :
// step === 5 ? <ClassList jarAndClassesList={resultData}/> : <Empty image={Empty.PRESENTED_IMAGE_DEFAULT}/>
} }
</>; </>;
}; };
......
...@@ -102,21 +102,16 @@ export const PythonSteps = [ ...@@ -102,21 +102,16 @@ export const PythonSteps = [
}, },
{ {
key: 3, key: 3,
title: l("rc.gp.build.step.3"),
status: "wait",
},
{
key: 4,
title: l("rc.gp.build.step.4"), title: l("rc.gp.build.step.4"),
status: "wait", status: "wait",
}, },
{ {
key: 5, key: 4,
title: l("rc.gp.build.step.5"), title: l("rc.gp.build.step.5"),
status: "wait", status: "wait",
}, },
{ {
key: 6, key: 5,
title: l("rc.gp.build.step.6"), title: l("rc.gp.build.step.6"),
status: "wait", status: "wait",
}, },
......
...@@ -25,157 +25,198 @@ import {l} from "@/utils/intl"; ...@@ -25,157 +25,198 @@ import {l} from "@/utils/intl";
import {AutoSteps, BuildMsgData} from "@/pages/RegCenter/GitProject/components/BuildSteps/AutoSteps"; import {AutoSteps, BuildMsgData} from "@/pages/RegCenter/GitProject/components/BuildSteps/AutoSteps";
import {JavaSteps, PythonSteps} from "@/pages/RegCenter/GitProject/components/BuildSteps/constants"; import {JavaSteps, PythonSteps} from "@/pages/RegCenter/GitProject/components/BuildSteps/constants";
import {API_CONSTANTS} from "@/services/constants"; import {API_CONSTANTS} from "@/services/constants";
import Exception from "@@/plugin-layout/Exception";
import integer from "async-validator/dist-types/validator/integer";
import proxy from "../../../../../../config/proxy";
/** /**
* props * props
*/ */
type BuildStepsProps = { type BuildStepsProps = {
onCancel: (flag?: boolean) => void; onCancel: (flag?: boolean) => void;
modalVisible: boolean; modalVisible: boolean;
values: Partial<GitProject>; values: Partial<GitProject>;
}; };
export type BuildStepsState = { export type BuildStepsState = {
key: number; key: number;
title: string; title: string;
status: string; status: string;
description: string; description: string;
disabled: boolean; disabled: boolean;
onClick: () => void; onClick: () => void;
} }
export const BuildSteps: React.FC<BuildStepsProps> = (props) => { export const BuildSteps: React.FC<BuildStepsProps> = (props) => {
/** /**
* extract props * extract props
*/ */
const { const {
onCancel: handleModalVisible, onCancel: handleModalVisible,
modalVisible, modalVisible,
values, values,
} = props; } = props;
let [logList, setLogList] = useState<Record<number, string[]>>({});
const [log, setLog] = useState<string>("");
const [currentStep, setCurrentStep] = useState<number>(values.buildStep || 0);
const [percent, setPercent] = useState<number>(0); const [currentStep, setCurrentStep] = useState<number>(0);
const [currentDataMsg, setCurrentDataMsg] = useState<BuildMsgData>(); const [showList, setShowList] = useState<boolean>(false);
const [eventSource, setEventSource] = useState<EventSource>(); const [percent, setPercent] = useState<number>(0);
const [buildSteps, setBuildSteps] = useState<Partial<any[]>>([]); const [currentDataMsg, setCurrentDataMsg] = useState<BuildMsgData>();
const [steps , handleSteps] = useState<Partial<BuildStepsState[]>>([]); const [buildSteps, setBuildSteps] = useState<Partial<any[]>>([]);
const [steps, handleSteps] = useState<BuildStepsState[]>([]);
const buildStepList = () => {
if (values.codeType === 1) { // if code type is java then build java steps const buildStepList = () => {
setBuildSteps(JavaSteps); if (values.codeType === 1) { // if code type is java then build java steps
} else { setBuildSteps(JavaSteps);
setBuildSteps(PythonSteps); } else {
} setBuildSteps(PythonSteps);
};
const renderStatus = (status: number) => {
let statusTemp = "";
if (status === 0) {
statusTemp = "error";
} else if (status === 1) {
statusTemp = "process";
} else if (status === 2) {
statusTemp = "finish";
} else {
statusTemp = "wait";
}
return statusTemp;
} }
};
const renderTitle = (step: number) => {
return l("rc.gp.build.step." + step);
const renderStatus = (status: number) => {
let statusTemp = "";
if (status === 0) {
statusTemp = "error";
} else if (status === 1) {
statusTemp = "process";
} else if (status === 2) {
statusTemp = "finish";
} else {
statusTemp = "wait";
} }
return statusTemp;
}
const renderTitle = (step: number) => {
return (values.codeType === 1 ? JavaSteps : PythonSteps)[step - 1].title;
}
// const [data, error] = useSSE(() => { useEffect(() => {
// return fetch("https://myapi.example.com").then((res) => res.json()); if (values.buildStep === 0) {
// }, []); setPercent(0);
setCurrentStep(0);
}
useEffect(() => { const {REACT_APP_ENV = 'dev'} = process.env;
if (values.buildStep === 0) { // @ts-ignore
setPercent(0); const url = proxy[REACT_APP_ENV]["/api/"].target || ""
setCurrentStep(0); // 这里不要代理。sse使用代理会变成同步
// const eventSource = new EventSource("http://127.0.0.1:8888" + API_CONSTANTS.GIT_PROJECT_BUILD_STEP_LOGS + "?id=" + values.id);
const eventSource = new EventSource(url + API_CONSTANTS.GIT_PROJECT_BUILD_STEP_LOGS + "?id=" + values.id);
buildStepList();
let stepArray: BuildStepsState[] = [];
let globalCurrentStep: number = 0;
let execNum: number = 0;
let stepNum: number = 1;
let showDataStep = -1;
let showData = "";
//sse listen event message
eventSource.onmessage = e => {
try {
// type // 1是总状态 2是log 3是部分状态
// status // 0是失败 1是进行中 2 完成
let resultMsg = JSON.parse(e.data);
const {currentStep, type, data, status, history} = resultMsg;
if (type === 0) {
if (execNum === 1) {
logList = {};
}
execNum++;
let a1 = JSON.parse(data);
stepNum = a1.length;
setPercent(parseInt(String(100 / stepNum * currentStep)));
setCurrentStep(currentStep);
stepArray = a1.map((item: any) => {
return {
key: item.step,
title: renderTitle(item.step),
status: renderStatus(item.status),
description: item.startTime,
disabled: item.status === -1 || status === 1,
onClick: () => {
if (item.status !== -1 && status !== 1) {
if (item.step === showDataStep) {
setShowList(true)
setLog(showData)
} else {
setShowList(false)
setLog(logList[item.step]?.join("\n"))
}
setCurrentStep(item.step)
}
}
};
})
globalCurrentStep = currentStep;
handleSteps(stepArray);
} }
const eventSource = new EventSource(API_CONSTANTS.GIT_PROJECT_BUILD_STEP_LOGS + "?id=" + values.id); if (type !== 0) {
if (type === 1) {
setEventSource(eventSource); if (logList[currentStep] === undefined) {
logList[currentStep] = []
buildStepList();
//sse listen event message
eventSource.onmessage = e => {
// type // 1是总状态 2是log 3是部分状态
// status // 0是失败 1是进行中 2 完成
let resultMsg = JSON.parse(e.data);
if (resultMsg.type === 1) {
// {
// key: 1,
// title: l("rc.gp.build.step.1"),
// status: "wait",
// },
console.log(resultMsg)
const {currentStep,data} = resultMsg;
setCurrentStep(currentStep);
setPercent((currentStep * 20) - 20);
let a1 = JSON.parse(data);
const nnn = a1.map((item: any) => {
return {
key: item.step,
title: renderTitle(item.step),
status: renderStatus(item.status),
description: item.startTime,
disabled: item.status === 2,
onClick: () => {
console.log(item,111111111)
}
};
})
handleSteps(nnn);
} }
if (resultMsg.type !== 1) { if (data !== undefined) {
setCurrentDataMsg(resultMsg); logList[currentStep].push(data)
console.log(resultMsg,'msg') setLog(logList[currentStep]?.join("\n"))
if (resultMsg.status === 2 && resultMsg.currentStep === 6) {
eventSource.close();
console.log("build success --- close")
}
} }
}; }
if (type === 2) {
showDataStep = currentStep;
return () => { showData = JSON.parse(data);
}
if (currentStep >= globalCurrentStep) {
setCurrentStep(currentStep);
setPercent(parseInt(String(100 / stepNum * currentStep)));
stepArray[currentStep - 1].status = renderStatus(status)
}
setCurrentDataMsg(resultMsg);
if ((status === 2 || status === 0) && history === false) {
eventSource.close(); eventSource.close();
console.log("build success --- close")
}
} }
} catch (e) {
console.error(e)
eventSource.close();
}
};
}, [values])
const handleCancel = () => { return () => {
handleModalVisible(); eventSource.close();
eventSource?.close();
} }
}, [])
return <>
<Modal const handleCancel = () => {
title={l("rc.gp.build")} handleModalVisible();
width={"85%"} }
open={modalVisible}
maskClosable={false}
onCancel={() => handleCancel()} return <>
okButtonProps={{style: {display: "none"}}} <Modal
> title={l("rc.gp.build")}
<AutoSteps steps={steps} currentDataMsg={currentDataMsg} percent={percent} currentStep={currentStep} width={"85%"}
values={values}/> open={true}
</Modal> maskClosable={false}
</>; onCancel={() => handleCancel()}
okButtonProps={{style: {display: "none"}}}
>
<AutoSteps steps={steps} currentDataMsg={currentDataMsg} percent={percent} currentStep={currentStep}
values={values} log={log} showList={showList}/>
</Modal>
</>;
}; };
...@@ -119,6 +119,7 @@ const ProjectProTable: React.FC = () => { ...@@ -119,6 +119,7 @@ const ProjectProTable: React.FC = () => {
await executeAndCallback(async () => { await executeAndCallback(async () => {
const result = await handlePutDataByParams(API_CONSTANTS.GIT_PROJECT_BUILD, l("rc.gp.building"), {id: value.id}); const result = await handlePutDataByParams(API_CONSTANTS.GIT_PROJECT_BUILD, l("rc.gp.building"), {id: value.id});
if (result) { if (result) {
setFormValues(value);
handleBuildVisible(true); handleBuildVisible(true);
// todo : build success, set build modal visible and set build steps // todo : build success, set build modal visible and set build steps
} }
...@@ -303,7 +304,9 @@ const ProjectProTable: React.FC = () => { ...@@ -303,7 +304,9 @@ const ProjectProTable: React.FC = () => {
{buildModalVisible && <BuildSteps onCancel={handleCancel} modalVisible={buildModalVisible} {buildModalVisible && <BuildSteps onCancel={handleCancel} modalVisible={buildModalVisible}
values={formValues}/>} values={formValues}/>}
{/* show build log modal */} {/* show build log modal */}
{logModalVisible && <ShowLog modalVisible={logModalVisible} onCancel={handleCancel} values={formValues}/>} {/*{logModalVisible && <ShowLog modalVisible={logModalVisible} onCancel={handleCancel} values={formValues}/>}*/}
{logModalVisible && <BuildSteps onCancel={handleCancel} modalVisible={buildModalVisible}
values={formValues}/>}
{/* show code tree modal */} {/* show code tree modal */}
<CodeTree modalVisible={codeTreeModalVisible} onCancel={handleCancel} values={formValues}/> <CodeTree modalVisible={codeTreeModalVisible} onCancel={handleCancel} values={formValues}/>
</>; </>;
......
...@@ -1052,28 +1052,29 @@ SET FOREIGN_KEY_CHECKS = 1; ...@@ -1052,28 +1052,29 @@ SET FOREIGN_KEY_CHECKS = 1;
-- ---------------------------- -- ----------------------------
DROP TABLE IF EXISTS `dinky_git_project`; DROP TABLE IF EXISTS `dinky_git_project`;
CREATE TABLE `dinky_git_project` ( CREATE TABLE `dinky_git_project` (
`id` bigint(20) NOT NULL AUTO_INCREMENT, `id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) NOT NULL, `tenant_id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL, `name` varchar(255) NOT NULL,
`url` varchar(1000) NOT NULL, `url` varchar(1000) NOT NULL,
`branch` varchar(1000) NOT NULL, `branch` varchar(1000) NOT NULL,
`username` varchar(255) DEFAULT NULL, `username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL,
`private_key` varchar(255) DEFAULT NULL COMMENT 'keypath', `private_key` varchar(255) DEFAULT NULL COMMENT 'keypath',
`pom` varchar(255) DEFAULT NULL, `pom` varchar(255) DEFAULT NULL,
`build_args` varchar(255) DEFAULT NULL, `build_args` varchar(255) DEFAULT NULL,
`code_type` tinyint(4) DEFAULT NULL COMMENT 'code type(1-java,2-python)', `code_type` tinyint(4) DEFAULT NULL COMMENT 'code type(1-java,2-python)',
`type` tinyint(4) NOT NULL COMMENT '1-http ,2-ssh', `type` tinyint(4) NOT NULL COMMENT '1-http ,2-ssh',
`last_build` datetime DEFAULT NULL, `last_build` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL, `description` varchar(255) DEFAULT NULL,
`build_state` tinyint(2) NOT NULL DEFAULT '0' COMMENT '0-notStart 1-process 2-failed 3-success', `build_state` tinyint(2) NOT NULL DEFAULT '0' COMMENT '0-notStart 1-process 2-failed 3-success',
`build_step` tinyint(2) NOT NULL DEFAULT '0', `build_step` tinyint(2) NOT NULL DEFAULT '0',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0-disable 1-enable', `enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0-disable 1-enable',
`udf_class_map_list` text COMMENT 'scan udf class', `udf_class_map_list` text COMMENT 'scan udf class',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time', `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time',
PRIMARY KEY (`id`) USING BTREE, PRIMARY KEY (`id`) USING BTREE,
KEY `tenant_id` (`tenant_id`) USING BTREE KEY `tenant_id` (`tenant_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4; ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
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`, `create_time`, `update_time`) 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, 1, 0, 1, '', '2023-04-26 15:10:13', '2023-04-26 15:10:43'); 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`) 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, 1, 0, 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`) VALUES (2, 1, 'python-udf', 'https://github.com/zackyoungh/dinky-quickstart-python.git', 'master', NULL, NULL, NULL, NULL, '', 2, 1, NULL, NULL, 1, 0, 1, '');
...@@ -78,3 +78,27 @@ ALTER TABLE dinky_cluster_configuration DROP COLUMN `alias`; ...@@ -78,3 +78,27 @@ ALTER TABLE dinky_cluster_configuration DROP COLUMN `alias`;
ALTER TABLE dinky_task_version DROP COLUMN `alias`; ALTER TABLE dinky_task_version DROP COLUMN `alias`;
ALTER TABLE dinky_task DROP COLUMN `alias`; ALTER TABLE dinky_task DROP COLUMN `alias`;
ALTER TABLE dinky_jar DROP COLUMN `alias`; ALTER TABLE dinky_jar DROP COLUMN `alias`;
CREATE TABLE `dinky_git_project` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) NOT NULL,
`name` varchar(255) NOT NULL,
`url` varchar(1000) NOT NULL,
`branch` varchar(1000) NOT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`private_key` varchar(255) DEFAULT NULL COMMENT 'keypath',
`pom` varchar(255) DEFAULT NULL,
`build_args` varchar(255) DEFAULT NULL,
`code_type` tinyint(4) DEFAULT NULL COMMENT 'code type(1-java,2-python)',
`type` tinyint(4) NOT NULL COMMENT '1-http ,2-ssh',
`last_build` datetime DEFAULT NULL,
`description` varchar(255) DEFAULT NULL,
`build_state` tinyint(2) NOT NULL DEFAULT '0' COMMENT '0-notStart 1-process 2-failed 3-success',
`build_step` tinyint(2) NOT NULL DEFAULT '0',
`enabled` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0-disable 1-enable',
`udf_class_map_list` text COMMENT 'scan udf class',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'create time',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'update time',
PRIMARY KEY (`id`) USING BTREE,
KEY `tenant_id` (`tenant_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
\ No newline at end of file
...@@ -48,4 +48,7 @@ alter table dinky_udf modify column `source_code` longtext; ...@@ -48,4 +48,7 @@ alter table dinky_udf modify column `source_code` longtext;
-- change data source of type -- change data source of type
update dinky_data_source set `type` = 'MySQL' where `type` = 'Mysql'; update dinky_data_source set `type` = 'MySQL' where `type` = 'Mysql';
update dinky_data_source set `type` = 'PostgreSQL' where `type` = 'PostgreSql'; update dinky_data_source set `type` = 'PostgreSQL' where `type` = 'PostgreSql';
update dinky_data_source set `type` = 'SQLServer' where `type` = 'SqlServer'; update dinky_data_source set `type` = 'SQLServer' where `type` = 'SqlServer';
\ No newline at end of file
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`) 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, 1, 0, 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`) VALUES (2, 1, 'python-udf', 'https://github.com/zackyoungh/dinky-quickstart-python.git', 'master', NULL, NULL, NULL, NULL, '', 2, 1, NULL, NULL, 1, 0, 1, '');
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