Unverified Commit 26aa980e authored by gaoyan's avatar gaoyan Committed by GitHub

[featrue]add backend kill process (#3511)

parent c64ac69e
...@@ -74,6 +74,25 @@ public class ConsoleContextHolder { ...@@ -74,6 +74,25 @@ public class ConsoleContextHolder {
return new ArrayList<>(logPross.values()); return new ArrayList<>(logPross.values());
} }
public synchronized ProcessEntity killProcess(String processName) {
ProcessEntity process = logPross.get(processName);
if (process == null) {
return getProcess(processName);
}
finishedProcess(processName, ProcessStatus.CANCELED, null);
ThreadGroup group = Thread.currentThread().getThreadGroup();
Thread[] threads = new Thread[group.activeCount()];
group.enumerate(threads);
for (Thread t : threads) {
if (t.getId() == process.getThreadId()) {
t.interrupt();
return process;
}
}
return getProcess(processName);
}
public ProcessEntity getProcess(String processName) { public ProcessEntity getProcess(String processName) {
if (logPross.containsKey(processName)) { if (logPross.containsKey(processName)) {
return logPross.get(processName); return logPross.get(processName);
...@@ -81,7 +100,11 @@ public class ConsoleContextHolder { ...@@ -81,7 +100,11 @@ public class ConsoleContextHolder {
try { try {
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName); String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName);
String string = FileUtil.readString(filePath, StandardCharsets.UTF_8); String string = FileUtil.readString(filePath, StandardCharsets.UTF_8);
return JSONObject.parseObject(string, ProcessEntity.class); ProcessEntity process = JSONObject.parseObject(string, ProcessEntity.class);
if (process.getStatus().isActiveStatus()) {
process.setStatus(ProcessStatus.UNKNOWN);
}
return process;
} catch (Exception e) { } catch (Exception e) {
log.warn("Get process {} failed, maybe not exits", processName); log.warn("Get process {} failed, maybe not exits", processName);
return null; return null;
...@@ -138,7 +161,7 @@ public class ConsoleContextHolder { ...@@ -138,7 +161,7 @@ public class ConsoleContextHolder {
* @param processName process name * @param processName process name
* @throws RuntimeException Throws an exception if the process already exists * @throws RuntimeException Throws an exception if the process already exists
*/ */
public void registerProcess(ProcessType type, String processName) throws RuntimeException { public synchronized void registerProcess(ProcessType type, String processName) throws RuntimeException {
if (logPross.containsKey(processName)) { if (logPross.containsKey(processName)) {
throw new BusException(Status.PROCESS_REGISTER_EXITS); throw new BusException(Status.PROCESS_REGISTER_EXITS);
} }
...@@ -150,6 +173,7 @@ public class ConsoleContextHolder { ...@@ -150,6 +173,7 @@ public class ConsoleContextHolder {
.title(type.getValue()) .title(type.getValue())
.startTime(LocalDateTime.now()) .startTime(LocalDateTime.now())
.children(new CopyOnWriteArrayList<>()) .children(new CopyOnWriteArrayList<>())
.threadId(Thread.currentThread().getId())
.build(); .build();
logPross.put(processName, entity); logPross.put(processName, entity);
appendLog(processName, null, "Start Process:" + processName, true); appendLog(processName, null, "Start Process:" + processName, true);
...@@ -202,24 +226,32 @@ public class ConsoleContextHolder { ...@@ -202,24 +226,32 @@ public class ConsoleContextHolder {
* @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 synchronized void finishedProcess(String processName, ProcessStatus status, Throwable e) {
ProcessEntity process = logPross.remove(processName); ProcessEntity process = logPross.get(processName);
if (process == null) { try {
return; process.setStatus(status);
} process.setEndTime(LocalDateTime.now());
process.setStatus(status); process.setTime(Duration.between(process.getStartTime(), process.getEndTime())
process.setEndTime(LocalDateTime.now()); .toMillis());
process.setTime( if (e != null) {
Duration.between(process.getStartTime(), process.getEndTime()).toMillis()); appendLog(processName, null, LogUtil.getError(e.getCause()), true);
if (e != null) { }
appendLog(processName, null, LogUtil.getError(e.getCause()), true); String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName);
} if (FileUtil.exist(filePath)) {
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), processName); Assert.isTrue(FileUtil.del(filePath));
if (FileUtil.exist(filePath)) { }
Assert.isTrue(FileUtil.del(filePath)); FileUtil.writeUtf8String(JSONObject.toJSONString(process), filePath);
appendLog(
processName,
null,
StrFormatter.format("Process {} exit with status:{}", processName, status),
true);
} catch (Exception ex) {
appendLog(processName, null, LogUtil.getError(ex.getCause()), true);
log.error("finishedProcess error", ex);
} finally {
logPross.remove(processName);
} }
FileUtil.writeUtf8String(JSONObject.toJSONString(process), filePath);
appendLog(processName, null, StrFormatter.format("Process {} exit with status:{}", processName, status), true);
} }
/** /**
......
...@@ -85,4 +85,12 @@ public class ProcessController { ...@@ -85,4 +85,12 @@ public class ProcessController {
} }
return Result.succeed(Status.PROCESS_CLEAR_LOG_SUCCESS); return Result.succeed(Status.PROCESS_CLEAR_LOG_SUCCESS);
} }
@GetMapping("/killProcess")
@ApiOperation("killProcess ")
@ApiImplicitParam(name = "processName", value = "process name", dataType = "ProcessEntity")
public Result<ProcessEntity> stopProcess(@RequestParam String processName) {
ProcessEntity process = ConsoleContextHolder.getInstances().killProcess(processName);
return Result.succeed(process);
}
} }
...@@ -50,6 +50,7 @@ public class ProcessEntity { ...@@ -50,6 +50,7 @@ public class ProcessEntity {
private long time; private long time;
private ProcessStepEntity lastUpdateStep; private ProcessStepEntity lastUpdateStep;
private CopyOnWriteArrayList<ProcessStepEntity> children; private CopyOnWriteArrayList<ProcessStepEntity> children;
private long threadId;
public void appendLog(String str) { public void appendLog(String str) {
log.append(str).append(CommonConstant.LineSep); log.append(str).append(CommonConstant.LineSep);
......
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
"dependencies": { "dependencies": {
"@andrewray/react-multi-split-pane": "^0.3.5", "@andrewray/react-multi-split-pane": "^0.3.5",
"@ant-design/charts": "^2.1.1", "@ant-design/charts": "^2.1.1",
"@ant-design/icons": "^5.2.6", "@ant-design/icons": "^5.3.7",
"@ant-design/pro-components": "^2.6.43", "@ant-design/pro-components": "^2.6.43",
"@ant-design/pro-layout": "^7.17.16", "@ant-design/pro-layout": "^7.17.16",
"@ant-design/pro-table": "^3.13.11", "@ant-design/pro-table": "^3.13.11",
......
...@@ -49,6 +49,7 @@ export type CodeShowFormProps = { ...@@ -49,6 +49,7 @@ export type CodeShowFormProps = {
enableAutoScroll?: boolean; enableAutoScroll?: boolean;
style?: CSSProperties; style?: CSSProperties;
clearContent?: () => void; clearContent?: () => void;
btnExtraContent?: any;
}; };
const CodeShow = (props: CodeShowFormProps) => { const CodeShow = (props: CodeShowFormProps) => {
...@@ -78,7 +79,8 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -78,7 +79,8 @@ const CodeShow = (props: CodeShowFormProps) => {
fullScreenBtn = false, fullScreenBtn = false,
enableMiniMap = false, enableMiniMap = false,
enableAutoScroll = false, enableAutoScroll = false,
clearContent clearContent,
btnExtraContent
} = props; } = props;
const { ScrollType } = editor; const { ScrollType } = editor;
...@@ -208,7 +210,8 @@ const CodeShow = (props: CodeShowFormProps) => { ...@@ -208,7 +210,8 @@ const CodeShow = (props: CodeShowFormProps) => {
handleDownScroll, handleDownScroll,
handleDownloadLog, handleDownloadLog,
handleWrap, handleWrap,
clearContent clearContent,
btnExtraContent
}; };
/** /**
......
...@@ -52,6 +52,7 @@ type EditFloatBtnProps = { ...@@ -52,6 +52,7 @@ type EditFloatBtnProps = {
handleDownloadLog?: () => string; // download log callback handleDownloadLog?: () => string; // download log callback
handleWrap?: () => void; // wrap callback handleWrap?: () => void; // wrap callback
clearContent?: () => void; // clear content callback clearContent?: () => void; // clear content callback
btnExtraContent?: any; //custom content
}; };
const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => { const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => {
/** /**
...@@ -71,7 +72,8 @@ const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => { ...@@ -71,7 +72,8 @@ const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => {
handleDownScroll, handleDownScroll,
handleDownloadLog, handleDownloadLog,
handleWrap, handleWrap,
clearContent clearContent,
btnExtraContent
} = props; } = props;
/** /**
...@@ -102,6 +104,7 @@ const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => { ...@@ -102,6 +104,7 @@ const EditorFloatBtn: React.FC<EditFloatBtnProps> = (props) => {
)} )}
</> </>
)} )}
{btnExtraContent && <>{btnExtraContent}</>}
{clearContent && ( {clearContent && (
<CircleBtn <CircleBtn
icon={<ClearOutlined twoToneColor={'red'} />} icon={<ClearOutlined twoToneColor={'red'} />}
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
* *
*/ */
import { LoadingBtn } from '@/components/CallBackButton/LoadingBtn';
import CodeShow from '@/components/CustomEditor/CodeShow'; import CodeShow from '@/components/CustomEditor/CodeShow';
import { SseData } from '@/models/Sse'; import { SseData } from '@/models/Sse';
import { DataStudioTabsItemType, StateType, VIEW } from '@/pages/DataStudio/model'; import { DataStudioTabsItemType, StateType, VIEW } from '@/pages/DataStudio/model';
...@@ -28,7 +29,7 @@ import { parseMilliSecondStr } from '@/utils/function'; ...@@ -28,7 +29,7 @@ import { parseMilliSecondStr } from '@/utils/function';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
import { SplitPane } from '@andrewray/react-multi-split-pane'; import { SplitPane } from '@andrewray/react-multi-split-pane';
import { Pane } from '@andrewray/react-multi-split-pane/dist/lib/Pane'; import { Pane } from '@andrewray/react-multi-split-pane/dist/lib/Pane';
import { CheckOutlined, CloseCircleFilled, LoadingOutlined } from '@ant-design/icons'; import { CheckOutlined, CloseCircleFilled, LoadingOutlined, XFilled } from '@ant-design/icons';
import { connect, useModel, useRequest } from '@umijs/max'; import { connect, useModel, useRequest } from '@umijs/max';
import { Empty, Space, Typography } from 'antd'; import { Empty, Space, Typography } from 'antd';
import { DataNode } from 'antd/es/tree'; import { DataNode } from 'antd/es/tree';
...@@ -102,6 +103,11 @@ const ConsoleContent = (props: ConsoleProps) => { ...@@ -102,6 +103,11 @@ const ConsoleContent = (props: ConsoleProps) => {
{ url: API_CONSTANTS.PROCESS_LOG, params: { processName: process } }, { url: API_CONSTANTS.PROCESS_LOG, params: { processName: process } },
{ onSuccess: async (res) => onUpdate(res) } { onSuccess: async (res) => onUpdate(res) }
); );
const killProcess = useRequest(
{ url: API_CONSTANTS.KILL_PROCESS, params: { processName: process } },
{ onSuccess: async (res) => onUpdate(res) }
);
useEffect(() => subscribeTopic([topic], (data: SseData) => onUpdate(data?.data)), []); useEffect(() => subscribeTopic([topic], (data: SseData) => onUpdate(data?.data)), []);
const onSelect = ( const onSelect = (
_selectedKeys: Key[], _selectedKeys: Key[],
...@@ -195,6 +201,17 @@ const ConsoleContent = (props: ConsoleProps) => { ...@@ -195,6 +201,17 @@ const ConsoleContent = (props: ConsoleProps) => {
); );
if (boolean) run(); if (boolean) run();
}} }}
btnExtraContent={
<LoadingBtn
key={'kill-process'}
click={async () => await killProcess.run()}
icon={
<XFilled
style={{ color: processNode?.status === JobStatus.RUNNING ? 'red' : 'gray' }}
/>
}
/>
}
/> />
</Pane> </Pane>
</SplitPane> </SplitPane>
......
...@@ -186,6 +186,7 @@ export enum API_CONSTANTS { ...@@ -186,6 +186,7 @@ export enum API_CONSTANTS {
// ------------------------------------ system process ------------------------------------ // ------------------------------------ system process ------------------------------------
PROCESS_LIST = '/api/process/listAllProcess', PROCESS_LIST = '/api/process/listAllProcess',
PROCESS_LOG = '/api/process/getProcess', PROCESS_LOG = '/api/process/getProcess',
KILL_PROCESS = '/api/process/killProcess',
PROCESS_LOG_CLEAR = '/api/process/clearProcessLog', PROCESS_LOG_CLEAR = '/api/process/clearProcessLog',
/** ------------------------------------------------ Devops center ------------------------------------ */ /** ------------------------------------------------ Devops center ------------------------------------ */
......
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