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;
import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessStepType;
import org.dinky.process.enums.ProcessType;
import org.dinky.process.model.ProcessStepEntity;
import org.apache.http.util.TextUtils;
......@@ -39,6 +40,7 @@ import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import cn.hutool.core.text.StrFormatter;
import lombok.extern.slf4j.Slf4j;
@Aspect
......@@ -46,8 +48,8 @@ import lombok.extern.slf4j.Slf4j;
@Component
public class ProcessAspect {
public static String PROCESS_NAME = "name";
public static String PROCESS_STEP = "step";
public static String PROCESS_NAME = "PROCESS_NAME";
public static String PROCESS_STEP = "PROCESS_STEP";
public ConsoleContextHolder contextHolder = ConsoleContextHolder.getInstances();
/**
......@@ -59,7 +61,7 @@ public class ProcessAspect {
Object result;
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();
contextHolder.registerProcess(type, name);
MDC.put(PROCESS_NAME, name);
......@@ -97,14 +99,15 @@ public class ProcessAspect {
// Record the current step and restore it after the execution is completed
String parentStep = MDC.get(PROCESS_STEP);
ProcessStepType processStepType = processStep.type();
MDC.put(PROCESS_STEP, processStepType.getValue());
contextHolder.registerProcessStep(processStepType, MDC.get(PROCESS_NAME), parentStep);
ProcessStepEntity step = 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 {
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) {
contextHolder.finishedStep(MDC.get(PROCESS_NAME), processStepType, ProcessStatus.FAILED, e);
contextHolder.finishedStep(MDC.get(PROCESS_NAME), step, ProcessStatus.FAILED, e);
throw e;
} finally {
// If a parent step exists, it is restored after the execution is complete
......
......@@ -21,6 +21,7 @@ package org.dinky.controller;
import org.dinky.context.ConsoleContextHolder;
import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result;
import org.dinky.process.model.ProcessEntity;
import org.springframework.web.bind.annotation.GetMapping;
......@@ -62,4 +63,11 @@ public class ProcessController {
.data(ConsoleContextHolder.getInstances().list())
.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;
import org.dinky.aop.ProcessAspect;
import org.dinky.context.ConsoleContextHolder;
import org.dinky.process.enums.ProcessStepType;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.Layout;
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.config.Property;
import org.apache.logging.log4j.core.config.plugins.Plugin;
......@@ -51,6 +51,10 @@ public class LogSseAppender extends AbstractAppender {
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,
* set in {@link ProcessAspect} If contextData contains PROCESS_NAME and PROCESS_STEP,
......@@ -63,9 +67,9 @@ public class LogSseAppender extends AbstractAppender {
if (contextData.containsKey(ProcessAspect.PROCESS_NAME)
&& contextData.containsKey(ProcessAspect.PROCESS_STEP)) {
String processName = contextData.getValue(ProcessAspect.PROCESS_NAME);
String processStep = contextData.getValue(ProcessAspect.PROCESS_STEP);
ConsoleContextHolder.getInstances()
.appendLog(processName, ProcessStepType.get(processStep), event.toString());
String processStepPid = contextData.getValue(ProcessAspect.PROCESS_STEP);
String log = getStringLayout().toSerializable(event);
ConsoleContextHolder.getInstances().appendLog(processName, processStepPid, log);
}
}
......
......@@ -61,7 +61,7 @@
<!--这个是输出日志的格式,如果对里面的参数不理解,可以去看我的这篇文章,网址是:“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} %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>
</appenders>
......
......@@ -24,7 +24,7 @@ import org.dinky.process.enums.ProcessStatus;
import org.dinky.process.enums.ProcessType;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import lombok.AllArgsConstructor;
import lombok.Builder;
......@@ -40,22 +40,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
public class ProcessEntity {
private String pid;
private String name;
private String key;
private String title;
private StringBuilder log;
private StringBuilder errLog;
private ProcessType type;
private ProcessStatus status;
private LocalDateTime startTime;
private LocalDateTime endTime;
private long time;
private LinkedHashMap<String, ProcessStep> stepsMap;
private ProcessStepEntity lastUpdateStep;
private LinkedList<ProcessStepEntity> children;
public void appendLog(String str) {
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;
import org.dinky.process.enums.ProcessStepType;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import lombok.AllArgsConstructor;
import lombok.Builder;
......@@ -40,23 +40,18 @@ import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ProcessStep {
private String name;
private ProcessStatus stepStatus;
public class ProcessStepEntity {
private String key;
private String title;
private ProcessStatus status;
private ProcessStepType type;
private LocalDateTime startTime;
private LocalDateTime endTime;
private long time;
private StringBuilder log = new StringBuilder();
private StringBuilder errLog = new StringBuilder();
private LinkedHashMap<String, ProcessStep> childStepsMap;
private LinkedList<ProcessStepEntity> children;
public void appendLog(String str) {
log.append(str).append(CommonConstant.LineSep);
}
public void appendErrLog(String str) {
errLog.append(str).append(CommonConstant.LineSep);
}
}
......@@ -15,6 +15,7 @@ export type MovableSidebarProps = {
contentHeight?: number;
defaultSize?: Size;
visible?: boolean;
headerVisible?: boolean;
children?: React.ReactNode;
handlerMinimize?: () => void;
handlerMaxsize?: () => void;
......@@ -40,6 +41,7 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => {
minHeight,
maxHeight,
enable,
headerVisible = true,
children,
title,
contentHeight,
......@@ -68,21 +70,23 @@ const MovableSidebar: React.FC<MovableSidebarProps> = (props) => {
enable={enable}
>
<>
<div
style={{
backgroundColor: token.colorBgBase,
borderBlockColor: themeValue.borderColor
}}
className={'container-header'}
>
<div>{title}</div>
<div className={showBtn ? 'show' : 'hide'}>
<Space size={1}>
{props.btnGroup}
<CircleBtn onClick={props.handlerMinimize} icon={<MinusOutlined />} />
</Space>
{headerVisible && (
<div
style={{
backgroundColor: token.colorBgBase,
borderBlockColor: themeValue.borderColor
}}
className={'container-header'}
>
<div>{title}</div>
<div className={showBtn ? 'show' : 'hide'}>
<Space size={1}>
{props.btnGroup}
<CircleBtn onClick={props.handlerMinimize} icon={<MinusOutlined />} />
</Space>
</div>
</div>
</div>
)}
<div
style={{
height: contentHeight,
......
......@@ -18,6 +18,7 @@
*/
import { postAll } from '@/services/api';
import { ErrorMessage } from '@/utils/messages';
import { useEffect, useRef, useState } from 'react';
export type SseData = {
......@@ -55,10 +56,14 @@ export default () => {
if (eventSource) {
eventSource.onopen = () => subscribe();
eventSource.onmessage = (e) => {
const data: SseData = JSON.parse(e.data);
subscriberRef.current
.filter((sub) => sub.topic.includes(data.topic))
.forEach((sub) => sub.call(data));
try {
const data: SseData = JSON.parse(e.data);
subscriberRef.current
.filter((sub) => sub.topic.includes(data.topic))
.forEach((sub) => sub.call(data));
} catch (e: any) {
ErrorMessage(e);
}
};
}
}, [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 { Tabs } from 'antd';
import React, { useEffect } from 'react';
const Console: React.FC = (props: any) => {
const {
tabs: { panes, activeKey }
} = props;
useEffect(() => {}, []);
const tabItems = panes.map((item: TabsItemType) => ({
key: item.key,
label: <span style={{ paddingLeft: '5px' }}>{item.label}</span>,
children: <ConsoleContent tab={item} />
}));
return (
<CodeShow
code={props.console}
height={props.height - 53}
language={'kotlin'}
lineNumbers={'off'}
showFloatButton
/>
<Tabs activeKey={activeKey} size={'small'} items={tabItems} tabBarStyle={{ display: 'none' }} />
);
};
export default connect(({ Studio }: { Studio: StateType }) => ({
tabs: Studio.tabs,
height: Studio.bottomContainer.height,
console: Studio.bottomContainerContent.console
}))(Console);
export function getConsoleData() {
// return queryDataByParams('api/process/getConsoleByUserId');
}
......@@ -18,7 +18,6 @@
import { AuthorizedObject, useAccess } from '@/hooks/useAccess';
import useThemeValue from '@/hooks/useThemeValue';
import BottomContainer from '@/pages/DataStudio/BottomContainer';
import { getConsoleData } from '@/pages/DataStudio/BottomContainer/Console/service';
import FooterContainer from '@/pages/DataStudio/FooterContainer';
import { mapDispatchToProps } from '@/pages/DataStudio/function';
import SecondHeaderContainer from '@/pages/DataStudio/HeaderContainer';
......@@ -52,7 +51,6 @@ const DataStudio = (props: any) => {
saveDataBase,
saveProject,
updateToolContentHeight,
updateBottomConsole,
saveSession,
saveEnv,
updateCenterContentHeight,
......@@ -99,18 +97,16 @@ const DataStudio = (props: any) => {
const loadData = async () => {
Promise.all([
getDataBase(),
getConsoleData(),
getTaskData(),
getSessionData(),
getEnvData(),
getClusterConfigurationData()
]).then((res) => {
saveDataBase(res[0]);
updateBottomConsole(res[1]);
saveProject(res[2]);
saveSession(res[3]);
saveEnv(res[4]);
saveClusterConfiguration(res[5]);
saveProject(res[1]);
saveSession(res[2]);
saveEnv(res[3]);
saveClusterConfiguration(res[4]);
});
};
......
......@@ -212,6 +212,7 @@ export enum API_CONSTANTS {
// process list
PROCESS_LIST = '/api/process/listAllProcess',
PROCESS_LOG = '/api/process/getProcess',
// ---- devops
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