Unverified Commit 4a4859af authored by gaoyan's avatar gaoyan Committed by GitHub

[Feature][web] support web console of process list (#2425)

* Optimize the process * add console ui * formate code * formate code * comment floatButton * formate code * formate code * formate code
parent 40a814f2
...@@ -26,6 +26,7 @@ import org.dinky.process.annotations.ProcessStep; ...@@ -26,6 +26,7 @@ import org.dinky.process.annotations.ProcessStep;
import org.dinky.process.enums.ProcessStatus; import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessStepType; import org.dinky.process.enums.ProcessStepType;
import org.dinky.process.enums.ProcessType; import org.dinky.process.enums.ProcessType;
import org.dinky.process.model.ProcessStepEntity;
import org.apache.http.util.TextUtils; import org.apache.http.util.TextUtils;
...@@ -39,6 +40,7 @@ import org.aspectj.lang.reflect.MethodSignature; ...@@ -39,6 +40,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC; import org.slf4j.MDC;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Aspect @Aspect
...@@ -46,8 +48,8 @@ import lombok.extern.slf4j.Slf4j; ...@@ -46,8 +48,8 @@ import lombok.extern.slf4j.Slf4j;
@Component @Component
public class ProcessAspect { public class ProcessAspect {
public static String PROCESS_NAME = "name"; public static String PROCESS_NAME = "PROCESS_NAME";
public static String PROCESS_STEP = "step"; public static String PROCESS_STEP = "PROCESS_STEP";
public ConsoleContextHolder contextHolder = ConsoleContextHolder.getInstances(); public ConsoleContextHolder contextHolder = ConsoleContextHolder.getInstances();
/** /**
...@@ -59,7 +61,7 @@ public class ProcessAspect { ...@@ -59,7 +61,7 @@ public class ProcessAspect {
Object result; Object result;
Object processId = getProcessId(joinPoint); Object processId = getProcessId(joinPoint);
String name = executeProcess.type() + String.valueOf(processId); String name = StrFormatter.format("{}/{}", executeProcess.type().getValue(), String.valueOf(processId));
ProcessType type = executeProcess.type(); ProcessType type = executeProcess.type();
contextHolder.registerProcess(type, name); contextHolder.registerProcess(type, name);
MDC.put(PROCESS_NAME, name); MDC.put(PROCESS_NAME, name);
...@@ -97,14 +99,15 @@ public class ProcessAspect { ...@@ -97,14 +99,15 @@ public class ProcessAspect {
// Record the current step and restore it after the execution is completed // Record the current step and restore it after the execution is completed
String parentStep = MDC.get(PROCESS_STEP); String parentStep = MDC.get(PROCESS_STEP);
ProcessStepType processStepType = processStep.type(); ProcessStepType processStepType = processStep.type();
MDC.put(PROCESS_STEP, processStepType.getValue()); ProcessStepEntity step = contextHolder.registerProcessStep(processStepType, MDC.get(PROCESS_NAME), parentStep);
contextHolder.registerProcessStep(processStepType, MDC.get(PROCESS_NAME), parentStep); MDC.put(PROCESS_STEP, step.getKey());
contextHolder.appendLog(processName, step.getKey(), "Start Process Step:" + step.getType());
try { try {
result = joinPoint.proceed(); result = joinPoint.proceed();
contextHolder.finishedStep(MDC.get(PROCESS_NAME), processStepType, ProcessStatus.FINISHED, null); contextHolder.finishedStep(MDC.get(PROCESS_NAME), step, ProcessStatus.FINISHED, null);
} catch (Exception e) { } catch (Exception e) {
contextHolder.finishedStep(MDC.get(PROCESS_NAME), processStepType, ProcessStatus.FAILED, e); contextHolder.finishedStep(MDC.get(PROCESS_NAME), step, ProcessStatus.FAILED, e);
throw e; throw e;
} finally { } finally {
// If a parent step exists, it is restored after the execution is complete // If a parent step exists, it is restored after the execution is complete
......
...@@ -27,14 +27,16 @@ import org.dinky.process.enums.ProcessStepType; ...@@ -27,14 +27,16 @@ import org.dinky.process.enums.ProcessStepType;
import org.dinky.process.enums.ProcessType; import org.dinky.process.enums.ProcessType;
import org.dinky.process.exception.DinkyException; import org.dinky.process.exception.DinkyException;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.process.model.ProcessStep; import org.dinky.process.model.ProcessStepEntity;
import org.dinky.utils.LogUtil; import org.dinky.utils.LogUtil;
import org.apache.http.util.TextUtils; import org.apache.http.util.TextUtils;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
...@@ -46,6 +48,7 @@ import com.alibaba.fastjson2.JSONObject; ...@@ -46,6 +48,7 @@ import com.alibaba.fastjson2.JSONObject;
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.UUID;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -71,24 +74,40 @@ public class ConsoleContextHolder { ...@@ -71,24 +74,40 @@ public class ConsoleContextHolder {
return new ArrayList<>(logPross.values()); return new ArrayList<>(logPross.values());
} }
public ProcessEntity getProcess(String processName) {
try {
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName);
String string = FileUtil.readString(filePath, StandardCharsets.UTF_8);
return JSONObject.parseObject(string, ProcessEntity.class);
} catch (Exception e) {
log.warn("Get process {} failed, maybe not exits", processName);
return null;
}
}
/** /**
* Add log messages to specific processes and process steps. * Add log messages to specific processes and process steps.
* *
* @param processName process name * @param processName process name
* @param processStep process step type * @param stepPid process step type
* @param log messages * @param log messages
* @throws BusException Throws an exception if the process does not exist * @throws BusException Throws an exception if the process does not exist
*/ */
public void appendLog(String processName, ProcessStepType processStep, String log) { public void appendLog(String processName, String stepPid, String log) {
if (!logPross.containsKey(processName)) { if (!logPross.containsKey(processName)) {
throw new BusException(StrFormatter.format("process {} does not exist", processName)); throw new BusException(StrFormatter.format("process {} does not exist", processName));
} }
logPross.get(processName).appendLog(log); ProcessEntity process = logPross.get(processName);
ProcessStep stepNode = getStepNode(processStep.getValue(), getStepsMap(processName)); process.appendLog(log);
if (stepPid != null) {
ProcessStepEntity stepNode = getStepNode(stepPid, getStepsMap(processName));
stepNode.appendLog(log); stepNode.appendLog(log);
process.setLastUpdateStep(stepNode);
}
// /TOPIC/PROCESS_CONSOLE/FlinkSubmit/12
String topic = StrFormatter.format("{}/{}", SseTopic.PROCESS_CONSOLE.getValue(), processName); String topic = StrFormatter.format("{}/{}", SseTopic.PROCESS_CONSOLE.getValue(), processName);
CompletableFuture.runAsync(() -> { CompletableFuture.runAsync(() -> {
SseSessionContextHolder.sendTopic(topic, logPross.get(processName)); SseSessionContextHolder.sendTopic(topic, process);
}); });
} }
...@@ -104,16 +123,16 @@ public class ConsoleContextHolder { ...@@ -104,16 +123,16 @@ public class ConsoleContextHolder {
throw new BusException("Another user is running an action to suppress this request"); throw new BusException("Another user is running an action to suppress this request");
} }
ProcessEntity entity = ProcessEntity.builder() ProcessEntity entity = ProcessEntity.builder()
.pid(processName) .key(UUID.fastUUID().toString())
.log(new StringBuilder()) .log(new StringBuilder())
.errLog(new StringBuilder())
.status(ProcessStatus.INITIALIZING) .status(ProcessStatus.INITIALIZING)
.type(type) .type(type)
.name(processName) .title(processName)
.startTime(LocalDateTime.now()) .startTime(LocalDateTime.now())
.stepsMap(new LinkedHashMap<>()) .children(new LinkedList<>())
.build(); .build();
logPross.put(processName, entity); logPross.put(processName, entity);
appendLog(processName, null, "Start Process:" + processName);
} }
/** /**
...@@ -121,33 +140,34 @@ public class ConsoleContextHolder { ...@@ -121,33 +140,34 @@ public class ConsoleContextHolder {
* *
* @param type process step type * @param type process step type
* @param processName process name * @param processName process name
* @param parentStep parent step * @param parentStepPid parent step
* @throws RuntimeException Throws an exception if the process does not exist * @throws RuntimeException Throws an exception if the process does not exist
*/ */
public void registerProcessStep(ProcessStepType type, String processName, String parentStep) public ProcessStepEntity registerProcessStep(ProcessStepType type, String processName, String parentStepPid)
throws RuntimeException { throws RuntimeException {
if (!logPross.containsKey(processName)) { if (!logPross.containsKey(processName)) {
throw new BusException(StrFormatter.format("Process {} does not exist", processName)); throw new BusException(StrFormatter.format("Process {} does not exist", type));
} }
ProcessEntity process = logPross.get(processName); ProcessEntity process = logPross.get(processName);
process.setStatus(ProcessStatus.RUNNING); process.setStatus(ProcessStatus.RUNNING);
ProcessStep processStep = ProcessStep.builder() ProcessStepEntity processStepEntity = ProcessStepEntity.builder()
.stepStatus(ProcessStatus.RUNNING) .key(UUID.fastUUID().toString())
.status(ProcessStatus.RUNNING)
.startTime(LocalDateTime.now()) .startTime(LocalDateTime.now())
.type(type) .type(type)
.name(type.getDesc().getMessage()) .title(type.getDesc().getMessage())
.log(new StringBuilder()) .log(new StringBuilder())
.errLog(new StringBuilder()) .children(new LinkedList<>())
.childStepsMap(new LinkedHashMap<>())
.build(); .build();
if (TextUtils.isEmpty(parentStep)) { if (TextUtils.isEmpty(parentStepPid)) {
// parentStep为空表示为顶级节点 // parentStep为空表示为顶级节点
process.getStepsMap().put(type.getValue(), processStep); process.getChildren().add(processStepEntity);
} else { } else {
ProcessStep stepNode = getStepNode(parentStep, process.getStepsMap()); ProcessStepEntity stepNode = getStepNode(parentStepPid, process.getChildren());
stepNode.getChildStepsMap().put(type.getValue(), processStep); stepNode.getChildren().add(processStepEntity);
} }
return processStepEntity;
} }
/** /**
...@@ -156,6 +176,7 @@ public class ConsoleContextHolder { ...@@ -156,6 +176,7 @@ public class ConsoleContextHolder {
* @param processName process name * @param processName process name
* @param status Process status * @param status Process status
* @param e exception object, optional * @param e exception object, optional
*
*/ */
public void finishedProcess(String processName, ProcessStatus status, Throwable e) { public void finishedProcess(String processName, ProcessStatus status, Throwable e) {
if (!logPross.containsKey(processName)) { if (!logPross.containsKey(processName)) {
...@@ -164,15 +185,17 @@ public class ConsoleContextHolder { ...@@ -164,15 +185,17 @@ public class ConsoleContextHolder {
ProcessEntity process = logPross.get(processName); ProcessEntity process = logPross.get(processName);
process.setStatus(status); process.setStatus(status);
process.setEndTime(LocalDateTime.now()); process.setEndTime(LocalDateTime.now());
process.setTime(process.getEndTime().compareTo(process.getStartTime())); process.setTime(
Duration.between(process.getStartTime(), process.getEndTime()).toMillis());
if (e != null) { if (e != null) {
process.appendErrLog(LogUtil.getError(e)); appendLog(processName, null, LogUtil.getError(e));
} }
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), process.getName()); String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), process.getTitle());
if (FileUtil.exist(filePath)) { if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath)); Assert.isTrue(FileUtil.del(filePath));
} }
FileUtil.writeUtf8String(JSONObject.toJSONString(process), filePath); FileUtil.writeUtf8String(JSONObject.toJSONString(process), filePath);
appendLog(processName, null, StrFormatter.format("Process {} exit with status:{}", processName, status));
logPross.remove(processName); logPross.remove(processName);
} }
...@@ -180,25 +203,28 @@ public class ConsoleContextHolder { ...@@ -180,25 +203,28 @@ public class ConsoleContextHolder {
* Mark process step as completed. * Mark process step as completed.
* *
* @param processName process name * @param processName process name
* @param type process step type * @param step process step type
* @param status Process step status * @param status Process step status
* @param e exception object, optional * @param e exception object, optional
*/ */
public void finishedStep(String processName, ProcessStepType type, ProcessStatus status, Throwable e) { public void finishedStep(String processName, ProcessStepEntity step, ProcessStatus status, Throwable e) {
if (!logPross.containsKey(processName)) { if (!logPross.containsKey(processName)) {
return; return;
} }
ProcessStep processStep = getStepNode(type.getValue(), getStepsMap(processName)); step.setStatus(status);
processStep.setStepStatus(status); step.setEndTime(LocalDateTime.now());
processStep.setEndTime(LocalDateTime.now()); step.setTime(Duration.between(step.getStartTime(), step.getEndTime()).toMillis());
processStep.setTime(processStep.getEndTime().compareTo(processStep.getStartTime()));
if (e != null) { if (e != null) {
logPross.get(processName).appendErrLog(LogUtil.getError(e)); appendLog(processName, step.getKey(), LogUtil.getError(e));
} }
appendLog(
processName,
step.getKey(),
StrFormatter.format("Process Step {} exit with status:{}", step.getType(), status));
} }
private ProcessStep getStepNode(String stepType, Map<String, ProcessStep> stepsMap) { private ProcessStepEntity getStepNode(String stepPid, LinkedList<ProcessStepEntity> stepsMap) {
ProcessStep stepNode = findStepNode(stepType, stepsMap); ProcessStepEntity stepNode = findStepNode(stepPid, stepsMap);
if (stepNode != null) { if (stepNode != null) {
return stepNode; return stepNode;
} }
...@@ -206,7 +232,7 @@ public class ConsoleContextHolder { ...@@ -206,7 +232,7 @@ public class ConsoleContextHolder {
"Get Parent Node Failed, This is most likely a Dinky bug, " "Get Parent Node Failed, This is most likely a Dinky bug, "
+ "please report the following information back to the community:\nProcess:{},\nstep:{},\nprocessNam:{}", + "please report the following information back to the community:\nProcess:{},\nstep:{},\nprocessNam:{}",
JSONObject.toJSONString(logPross), JSONObject.toJSONString(logPross),
stepType, stepPid,
MDC.get(ProcessAspect.PROCESS_NAME)); MDC.get(ProcessAspect.PROCESS_NAME));
throw new DinkyException(errorStr); throw new DinkyException(errorStr);
} }
...@@ -214,12 +240,12 @@ public class ConsoleContextHolder { ...@@ -214,12 +240,12 @@ public class ConsoleContextHolder {
/** /**
* 递归查找节点 * 递归查找节点
* */ * */
private ProcessStep findStepNode(String stepType, Map<String, ProcessStep> stepsMap) { private ProcessStepEntity findStepNode(String stepPid, LinkedList<ProcessStepEntity> stepsMap) {
for (Map.Entry<String, ProcessStep> entry : stepsMap.entrySet()) { for (ProcessStepEntity processStepEntity : stepsMap) {
if (entry.getKey().equals(stepType)) { if (processStepEntity.getKey().equals(stepPid)) {
return entry.getValue(); return processStepEntity;
} else { } else {
ProcessStep stepNode = findStepNode(stepType, entry.getValue().getChildStepsMap()); ProcessStepEntity stepNode = findStepNode(stepPid, processStepEntity.getChildren());
if (stepNode != null) { if (stepNode != null) {
return stepNode; return stepNode;
} }
...@@ -228,7 +254,7 @@ public class ConsoleContextHolder { ...@@ -228,7 +254,7 @@ public class ConsoleContextHolder {
return null; return null;
} }
private Map<String, ProcessStep> getStepsMap(String processName) { private LinkedList<ProcessStepEntity> getStepsMap(String processName) {
return logPross.get(processName).getStepsMap(); return logPross.get(processName).getChildren();
} }
} }
...@@ -21,6 +21,7 @@ package org.dinky.controller; ...@@ -21,6 +21,7 @@ package org.dinky.controller;
import org.dinky.context.ConsoleContextHolder; import org.dinky.context.ConsoleContextHolder;
import org.dinky.data.result.ProTableResult; import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
...@@ -62,4 +63,11 @@ public class ProcessController { ...@@ -62,4 +63,11 @@ public class ProcessController {
.data(ConsoleContextHolder.getInstances().list()) .data(ConsoleContextHolder.getInstances().list())
.build(); .build();
} }
@GetMapping("/getProcess")
@ApiOperation("get process")
@ApiImplicitParam(name = "processName", value = "process name", dataType = "ProcessEntity")
public Result<ProcessEntity> listAllProcess(@RequestParam String processName) {
return Result.succeed(ConsoleContextHolder.getInstances().getProcess(processName));
}
} }
...@@ -21,11 +21,11 @@ package org.dinky.sse; ...@@ -21,11 +21,11 @@ package org.dinky.sse;
import org.dinky.aop.ProcessAspect; import org.dinky.aop.ProcessAspect;
import org.dinky.context.ConsoleContextHolder; import org.dinky.context.ConsoleContextHolder;
import org.dinky.process.enums.ProcessStepType;
import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout; import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.StringLayout;
import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.appender.AbstractAppender;
import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.Plugin;
...@@ -51,6 +51,10 @@ public class LogSseAppender extends AbstractAppender { ...@@ -51,6 +51,10 @@ public class LogSseAppender extends AbstractAppender {
super(name, filter, layout, ignoreExceptions, properties); super(name, filter, layout, ignoreExceptions, properties);
} }
public StringLayout getStringLayout() {
return (StringLayout) getLayout();
}
/** /**
* This method is called when a new log comes over, contextData is the data in the MDC, * This method is called when a new log comes over, contextData is the data in the MDC,
* set in {@link ProcessAspect} If contextData contains PROCESS_NAME and PROCESS_STEP, * set in {@link ProcessAspect} If contextData contains PROCESS_NAME and PROCESS_STEP,
...@@ -63,9 +67,9 @@ public class LogSseAppender extends AbstractAppender { ...@@ -63,9 +67,9 @@ public class LogSseAppender extends AbstractAppender {
if (contextData.containsKey(ProcessAspect.PROCESS_NAME) if (contextData.containsKey(ProcessAspect.PROCESS_NAME)
&& contextData.containsKey(ProcessAspect.PROCESS_STEP)) { && contextData.containsKey(ProcessAspect.PROCESS_STEP)) {
String processName = contextData.getValue(ProcessAspect.PROCESS_NAME); String processName = contextData.getValue(ProcessAspect.PROCESS_NAME);
String processStep = contextData.getValue(ProcessAspect.PROCESS_STEP); String processStepPid = contextData.getValue(ProcessAspect.PROCESS_STEP);
ConsoleContextHolder.getInstances() String log = getStringLayout().toSerializable(event);
.appendLog(processName, ProcessStepType.get(processStep), event.toString()); ConsoleContextHolder.getInstances().appendLog(processName, processStepPid, log);
} }
} }
......
...@@ -61,7 +61,7 @@ ...@@ -61,7 +61,7 @@
<!--这个是输出日志的格式,如果对里面的参数不理解,可以去看我的这篇文章,网址是:“https://blog.csdn.net/qq_42449963/article/details/104617356”--> <!--这个是输出日志的格式,如果对里面的参数不理解,可以去看我的这篇文章,网址是:“https://blog.csdn.net/qq_42449963/article/details/104617356”-->
<!--<PatternLayout pattern="[dinky] %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>--> <!--<PatternLayout pattern="[dinky] %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>-->
<PatternLayout <PatternLayout
pattern="[dinky] %d{yyyy-MM-dd HH:mm:ss.SSS} %highlight{%6p} %style{%5pid}{bright,magenta} --- [%15.15t] %style{%c{20}}{bright,cyan}: %m%n"/> pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %p [%15.15t] %c{20}(%L): %m"/>
</LogSseAppender> </LogSseAppender>
</appenders> </appenders>
......
...@@ -24,7 +24,7 @@ import org.dinky.process.enums.ProcessStatus; ...@@ -24,7 +24,7 @@ import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessType; import org.dinky.process.enums.ProcessType;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.LinkedHashMap; import java.util.LinkedList;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
...@@ -40,22 +40,18 @@ import lombok.NoArgsConstructor; ...@@ -40,22 +40,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
public class ProcessEntity { public class ProcessEntity {
private String pid; private String key;
private String name; private String title;
private StringBuilder log; private StringBuilder log;
private StringBuilder errLog;
private ProcessType type; private ProcessType type;
private ProcessStatus status; private ProcessStatus status;
private LocalDateTime startTime; private LocalDateTime startTime;
private LocalDateTime endTime; private LocalDateTime endTime;
private long time; private long time;
private LinkedHashMap<String, ProcessStep> stepsMap; private ProcessStepEntity lastUpdateStep;
private LinkedList<ProcessStepEntity> children;
public void appendLog(String str) { public void appendLog(String str) {
log.append(str).append(CommonConstant.LineSep); log.append(str).append(CommonConstant.LineSep);
} }
public void appendErrLog(String str) {
errLog.append(str).append(CommonConstant.LineSep);
}
} }
...@@ -24,7 +24,7 @@ import org.dinky.process.enums.ProcessStatus; ...@@ -24,7 +24,7 @@ import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessStepType; import org.dinky.process.enums.ProcessStepType;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.LinkedHashMap; import java.util.LinkedList;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
...@@ -40,23 +40,18 @@ import lombok.NoArgsConstructor; ...@@ -40,23 +40,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@Builder @Builder
public class ProcessStep { public class ProcessStepEntity {
private String key;
private String name; private String title;
private ProcessStatus stepStatus; private ProcessStatus status;
private ProcessStepType type; private ProcessStepType type;
private LocalDateTime startTime; private LocalDateTime startTime;
private LocalDateTime endTime; private LocalDateTime endTime;
private long time; private long time;
private StringBuilder log = new StringBuilder(); private StringBuilder log = new StringBuilder();
private StringBuilder errLog = new StringBuilder(); private LinkedList<ProcessStepEntity> children;
private LinkedHashMap<String, ProcessStep> childStepsMap;
public void appendLog(String str) { public void appendLog(String str) {
log.append(str).append(CommonConstant.LineSep); log.append(str).append(CommonConstant.LineSep);
} }
public void appendErrLog(String str) {
errLog.append(str).append(CommonConstant.LineSep);
}
} }
...@@ -15,6 +15,7 @@ export type MovableSidebarProps = { ...@@ -15,6 +15,7 @@ export type MovableSidebarProps = {
contentHeight?: number; contentHeight?: number;
defaultSize?: Size; defaultSize?: Size;
visible?: boolean; visible?: boolean;
headerVisible?: boolean;
children?: React.ReactNode; children?: React.ReactNode;
handlerMinimize?: () => void; handlerMinimize?: () => void;
handlerMaxsize?: () => void; handlerMaxsize?: () => void;
...@@ -40,6 +41,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => { ...@@ -40,6 +41,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => {
minHeight, minHeight,
maxHeight, maxHeight,
enable, enable,
headerVisible = true,
children, children,
title, title,
contentHeight, contentHeight,
...@@ -68,6 +70,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => { ...@@ -68,6 +70,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => {
enable={enable} enable={enable}
> >
<> <>
{headerVisible && (
<div <div
style={{ style={{
backgroundColor: token.colorBgBase, backgroundColor: token.colorBgBase,
...@@ -83,6 +86,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => { ...@@ -83,6 +86,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => {
</Space> </Space>
</div> </div>
</div> </div>
)}
<div <div
style={{ style={{
height: contentHeight, height: contentHeight,
......
...@@ -18,6 +18,7 @@ ...@@ -18,6 +18,7 @@
*/ */
import { postAll } from '@/services/api'; import { postAll } from '@/services/api';
import { ErrorMessage } from '@/utils/messages';
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
export type SseData = { export type SseData = {
...@@ -55,10 +56,14 @@ export default () => { ...@@ -55,10 +56,14 @@ export default () => {
if (eventSource) { if (eventSource) {
eventSource.onopen = () => subscribe(); eventSource.onopen = () => subscribe();
eventSource.onmessage = (e) => { eventSource.onmessage = (e) => {
try {
const data: SseData = JSON.parse(e.data); const data: SseData = JSON.parse(e.data);
subscriberRef.current subscriberRef.current
.filter((sub) => sub.topic.includes(data.topic)) .filter((sub) => sub.topic.includes(data.topic))
.forEach((sub) => sub.call(data)); .forEach((sub) => sub.call(data));
} catch (e: any) {
ErrorMessage(e);
}
}; };
} }
}, [eventSource]); }, [eventSource]);
......
/*
*
* 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.
*
*/
import CodeShow from '@/components/CustomEditor/CodeShow';
import MovableSidebar from '@/components/Sidebar/MovableSidebar';
import { SseData } from '@/models/Sse';
import { DataStudioTabsItemType, StateType } from '@/pages/DataStudio/model';
import { SSE_TOPIC } from '@/pages/DevOps/constants';
import { API_CONSTANTS } from '@/services/endpoints';
import { parseMilliSecondStr } from '@/utils/function';
import { connect, useModel, useRequest } from '@@/exports';
import { CheckOutlined, CloseCircleFilled, LoadingOutlined } from '@ant-design/icons';
import { Empty, Space, Typography } from 'antd';
import { DataNode } from 'antd/es/tree';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { Key, useEffect, useState } from 'react';
const { Text } = Typography;
export type ConsoleProps = {
tab: DataStudioTabsItemType;
height: number;
};
export interface ProcessStep extends DataNode {
status: string;
type: string;
startTime: string;
endTime: string;
time: number;
log: string;
lastUpdateStep: ProcessStep;
}
const ConsoleContent = (props: ConsoleProps) => {
const { tab } = props;
const [selectNode, setSelectNode] = useState<ProcessStep>();
const [processNode, setProcessNode] = useState<ProcessStep>();
const process = `FlinkSubmit/${tab.params.taskId}`;
const topic = `${SSE_TOPIC.PROCESS_CONSOLE}/${process}`;
const { subscribeTopic } = useModel('Sse', (model: any) => ({
subscribeTopic: model.subscribeTopic
}));
const onUpdate = (data: ProcessStep) => {
setProcessNode((prevState: any) => {
//如果key不一致代表重新提交了任务,清空旧状态
if (prevState && prevState.key != data.key) {
setSelectNode(undefined);
}
return data;
});
setSelectNode((prevState: any) => {
if (prevState && prevState.key == data.lastUpdateStep.key) {
//更新当前节点
return data.lastUpdateStep;
} else if (!prevState || prevState.key == data.key) {
//未选择节点状态下选择根节点
return data;
}
return prevState;
});
};
useRequest(
{ url: API_CONSTANTS.PROCESS_LOG, params: { processName: process } },
{ onSuccess: async (res) => onUpdate(res) }
);
useEffect(() => subscribeTopic([topic], (data: SseData) => onUpdate(data.data)), []);
const onSelect = (_selectedKeys: Key[], info: { node: ProcessStep }) => setSelectNode(info.node);
const renderTitle = (node: any) => {
const startDate = new Date(node.startTime);
const endDate = new Date();
const duration = node.time ? node.time : endDate.getTime() - startDate.getTime();
return (
<Space size={5}>
{node.status == 'RUNNING' && <LoadingOutlined />}
{node.status == 'FINISHED' && (
<CheckOutlined style={{ color: 'green', fontWeight: 'bold' }} />
)}
{node.status == 'FAILED' && (
<CloseCircleFilled style={{ color: 'red', fontWeight: 'bold' }} />
)}
<Text>{node.title}</Text>
<Text type={'secondary'} style={{ marginLeft: 'auto' }}>
{parseMilliSecondStr(duration)}
</Text>
</Space>
);
};
return (
<div style={{ overflow: 'hidden' }}>
<MovableSidebar
defaultSize={{
width: 300,
height: props.height - 53
}}
minWidth={20}
visible={true}
enable={{ right: true }}
headerVisible={false}
style={{ borderInlineStart: `1px`, float: 'left' }}
>
{processNode ? (
<DirectoryTree
className={'treeList'}
showIcon={false}
titleRender={renderTitle}
onSelect={onSelect}
treeData={[processNode]}
expandAction={'doubleClick'}
defaultExpandParent
defaultExpandAll
/>
) : (
<Empty />
)}
</MovableSidebar>
<div>
<CodeShow
code={selectNode?.log ? selectNode.log : ''}
height={props.height - 53}
language={'kotlin'}
lineNumbers={'off'}
//TODO 按钮显示有问题,先注释
// showFloatButton
/>
</div>
</div>
);
};
export default connect(({ Studio }: { Studio: StateType }) => ({
height: Studio.bottomContainer.height,
console: Studio.bottomContainerContent.console
}))(ConsoleContent);
import CodeShow from '@/components/CustomEditor/CodeShow'; /*
import { StateType } from '@/pages/DataStudio/model'; *
* 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.
*
*/
import ConsoleContent from '@/pages/DataStudio/BottomContainer/Console/ConsoleContent';
import { StateType, TabsItemType } from '@/pages/DataStudio/model';
import { connect } from '@@/exports'; import { connect } from '@@/exports';
import { Tabs } from 'antd';
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
const Console: React.FC = (props: any) => { const Console: React.FC = (props: any) => {
const {
tabs: { panes, activeKey }
} = props;
useEffect(() => {}, []); useEffect(() => {}, []);
const tabItems = panes.map((item: TabsItemType) => ({
key: item.key,
label: <span style={{ paddingLeft: '5px' }}>{item.label}</span>,
children: <ConsoleContent tab={item} />
}));
return ( return (
<CodeShow <Tabs activeKey={activeKey} size={'small'} items={tabItems} tabBarStyle={{ display: 'none' }} />
code={props.console}
height={props.height - 53}
language={'kotlin'}
lineNumbers={'off'}
showFloatButton
/>
); );
}; };
export default connect(({ Studio }: { Studio: StateType }) => ({ export default connect(({ Studio }: { Studio: StateType }) => ({
tabs: Studio.tabs,
height: Studio.bottomContainer.height, height: Studio.bottomContainer.height,
console: Studio.bottomContainerContent.console console: Studio.bottomContainerContent.console
}))(Console); }))(Console);
export function getConsoleData() {
// return queryDataByParams('api/process/getConsoleByUserId');
}
...@@ -18,7 +18,6 @@ ...@@ -18,7 +18,6 @@
import { AuthorizedObject, useAccess } from '@/hooks/useAccess'; import { AuthorizedObject, useAccess } from '@/hooks/useAccess';
import useThemeValue from '@/hooks/useThemeValue'; import useThemeValue from '@/hooks/useThemeValue';
import BottomContainer from '@/pages/DataStudio/BottomContainer'; import BottomContainer from '@/pages/DataStudio/BottomContainer';
import { getConsoleData } from '@/pages/DataStudio/BottomContainer/Console/service';
import FooterContainer from '@/pages/DataStudio/FooterContainer'; import FooterContainer from '@/pages/DataStudio/FooterContainer';
import { mapDispatchToProps } from '@/pages/DataStudio/function'; import { mapDispatchToProps } from '@/pages/DataStudio/function';
import SecondHeaderContainer from '@/pages/DataStudio/HeaderContainer'; import SecondHeaderContainer from '@/pages/DataStudio/HeaderContainer';
...@@ -52,7 +51,6 @@ const DataStudio = (props: any) => { ...@@ -52,7 +51,6 @@ const DataStudio = (props: any) => {
saveDataBase, saveDataBase,
saveProject, saveProject,
updateToolContentHeight, updateToolContentHeight,
updateBottomConsole,
saveSession, saveSession,
saveEnv, saveEnv,
updateCenterContentHeight, updateCenterContentHeight,
...@@ -99,18 +97,16 @@ const DataStudio = (props: any) => { ...@@ -99,18 +97,16 @@ const DataStudio = (props: any) => {
const loadData = async () => { const loadData = async () => {
Promise.all([ Promise.all([
getDataBase(), getDataBase(),
getConsoleData(),
getTaskData(), getTaskData(),
getSessionData(), getSessionData(),
getEnvData(), getEnvData(),
getClusterConfigurationData() getClusterConfigurationData()
]).then((res) => { ]).then((res) => {
saveDataBase(res[0]); saveDataBase(res[0]);
updateBottomConsole(res[1]); saveProject(res[1]);
saveProject(res[2]); saveSession(res[2]);
saveSession(res[3]); saveEnv(res[3]);
saveEnv(res[4]); saveClusterConfiguration(res[4]);
saveClusterConfiguration(res[5]);
}); });
}; };
......
...@@ -212,6 +212,7 @@ export enum API_CONSTANTS { ...@@ -212,6 +212,7 @@ export enum API_CONSTANTS {
// process list // process list
PROCESS_LIST = '/api/process/listAllProcess', PROCESS_LIST = '/api/process/listAllProcess',
PROCESS_LOG = '/api/process/getProcess',
// ---- devops // ---- devops
GET_JOB_LIST = '/api/jobInstance', GET_JOB_LIST = '/api/jobInstance',
......
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