Unverified Commit 0edde40a authored by Zzm0809's avatar Zzm0809 Committed by GitHub

[Feature] Support delete metrics layout (#2873)

* Spotless Apply * support-delete-metrics-data * Spotless Apply * modify btn position * Spotless Apply * delete unuse code * Spotless Apply --------- Co-authored-by: 's avatarZzm0809 <Zzm0809@users.noreply.github.com>
parent 2230125a
......@@ -24,6 +24,7 @@ import org.dinky.data.annotations.Log;
import org.dinky.data.dto.MetricsLayoutDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.MetricsType;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Metrics;
import org.dinky.data.result.Result;
import org.dinky.data.vo.MetricsVO;
......@@ -33,6 +34,7 @@ import org.dinky.service.MonitorService;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
......@@ -127,4 +129,14 @@ public class MonitorController {
public SseEmitter getJvmInfo() {
return monitorService.sendJvmInfo();
}
@DeleteMapping("/deleteMetricsLayout")
@ApiOperation("Delete Metrics Layout")
@ApiImplicitParam(name = "taskId", value = "taskId", required = true, dataType = "Integer")
public Result<Void> deleteMetricsLayout(@RequestParam("id") Integer taskId) {
if (monitorService.deleteMetricsLayout(taskId)) {
return Result.succeed(Status.DELETE_SUCCESS);
}
return Result.failed(Status.DELETE_FAILED);
}
}
......@@ -81,4 +81,11 @@ public interface MonitorService extends IService<Metrics> {
* @return A list of {@link Metrics} objects representing the job metrics for the specified task ID.
*/
List<Metrics> getMetricsLayoutByTaskId(Integer taskId);
/**
* Delete the metrics layout.
* @param taskId the task id
* @return if the delete is successful.
*/
boolean deleteMetricsLayout(Integer taskId);
}
......@@ -27,6 +27,7 @@ import org.dinky.data.dto.CatalogueTaskDTO;
import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Catalogue;
import org.dinky.data.model.Metrics;
import org.dinky.data.model.Task;
import org.dinky.data.model.job.History;
import org.dinky.data.model.job.JobHistory;
......@@ -39,6 +40,7 @@ import org.dinky.service.CatalogueService;
import org.dinky.service.HistoryService;
import org.dinky.service.JobHistoryService;
import org.dinky.service.JobInstanceService;
import org.dinky.service.MonitorService;
import org.dinky.service.TaskService;
import java.io.BufferedReader;
......@@ -59,6 +61,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
......@@ -80,6 +83,8 @@ public class CatalogueServiceImpl extends SuperServiceImpl<CatalogueMapper, Cata
private final JobHistoryService jobHistoryService;
private final MonitorService monitorService;
/**
* @return
*/
......@@ -448,6 +453,9 @@ public class CatalogueServiceImpl extends SuperServiceImpl<CatalogueMapper, Cata
// doing: cascade delete jobInstance && jobHistory && history && statement
// 获取 task 表中的作业
Task task = taskService.getById(catalogue.getTaskId());
// 获取 metrics 表中的监控数据
List<Metrics> metricListByTaskId = monitorService.getMetricsLayoutByTaskId(catalogue.getTaskId());
// 获取 job instance 表中的作业
List<JobInstance> jobInstanceList = jobInstanceService.list(
new LambdaQueryWrapper<JobInstance>().eq(JobInstance::getTaskId, catalogue.getTaskId()));
......@@ -471,6 +479,11 @@ public class CatalogueServiceImpl extends SuperServiceImpl<CatalogueMapper, Cata
if (task != null) {
taskService.removeById(task.getId());
}
if (CollUtil.isNotEmpty(metricListByTaskId)) {
metricListByTaskId.forEach(metrics -> monitorService.removeById(metrics.getId()));
// todo: 需要删除 paimon 中的监控数据, 但是 paimon 中没有提供删除接口
}
}
// 如果是文件夹 , 且下边没有子文件夹 , 则删除
......
......@@ -165,4 +165,18 @@ public class MonitorServiceImpl extends ServiceImpl<MetricsMapper, Metrics> impl
wrapper.lambda().eq(Metrics::getTaskId, taskId);
return this.baseMapper.selectList(wrapper);
}
/**
* Delete the metrics layout.
*
* @param taskId the task id
* @return if the delete is successful.
*/
@Override
public boolean deleteMetricsLayout(Integer taskId) {
List<Metrics> metricsList = getMetricsLayoutByTaskId(taskId);
int deleted = this.baseMapper.deleteBatchIds(
metricsList.stream().map(Metrics::getId).collect(Collectors.toList()));
return deleted > 0;
}
}
......@@ -24,7 +24,7 @@ import React from 'react';
type PopconfirmProps = {
onClick: () => void;
description: string;
description: string | React.ReactNode;
options?: any;
};
......
......@@ -17,7 +17,7 @@
*
*/
import { ChartData } from '@/pages/Metrics/Job/data';
import { ChartData } from '@/pages/Metrics/JobMetricsList/data';
import { differenceDays } from '@/utils/function';
import { Line } from '@ant-design/charts';
import { ExpandOutlined } from '@ant-design/icons';
......
......@@ -340,6 +340,8 @@ export default {
'metrics.flink.taskId': 'Dinky Job ID',
'metrics.dinky.not.open':
'Dinky Server monitoring is not enabled, please go to the Setting Center -> Global Settings -> Metrics Configuration -> Dinky JVM Monitor switch to open',
'metrics.flink.deleteConfirm':
'Are you sure to delete the monitoring data under this task? \nAttention: This operation will synchronously affect the monitoring data of the operation and maintenance center for this task!! \nPlease operate with caution, this operation is irreversible!',
/**
*
......
......@@ -329,6 +329,8 @@ export default {
'metrics.flink.taskId': 'Dinky 任务ID',
'metrics.dinky.not.open':
'暂未开启 Dinky Server 监控, 请前往 配置中心 -> 全局配置 -> Metrics 配置 -> Dinky JVM Monitor 开关 进行开启',
'metrics.flink.deleteConfirm':
'确认删除该任务下的监控数据吗? \n注意:该操作会同步影响运维中心该任务的监控数据!!\n请谨慎操作,该操作不可撤销!',
/**
*
* pages
......
......@@ -23,7 +23,7 @@ import { SseData } from '@/models/Sse';
import { SSE_TOPIC } from '@/pages/DevOps/constants';
import { JobMetricsItem, MetricsTimeFilter } from '@/pages/DevOps/JobDetail/data';
import { getMetricsData } from '@/pages/DevOps/JobDetail/srvice';
import { ChartData } from '@/pages/Metrics/Job/data';
import { ChartData } from '@/pages/Metrics/JobMetricsList/data';
import { MetricsDataType } from '@/pages/Metrics/Server/data';
import { Jobs } from '@/types/DevOps/data';
import { Empty, Row, Spin } from 'antd';
......
/*
*
* 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 { SubTask, Task } from '@/pages/Metrics/Job/data';
import { l } from '@/utils/intl';
import { SyncOutlined } from '@ant-design/icons';
import { Tag, Typography } from 'antd';
const { Paragraph } = Typography;
/**
* build flink job metrics list ( 3 level)
* @returns {{label: JSX.Element, value: string, key: string}[]}
* @param subTasks
*/
export const buildMetricsList = (subTasks: string[]) =>
subTasks.map((subTask) => {
// build label
let label = (
<div className={'tag-content'}>
<Tag icon={<SyncOutlined spin />} color={'processing'}>
{l('metrics.flink.metrics.name')}: {subTask}
</Tag>
</div>
);
return {
key: subTask,
label: label,
value: subTask
};
});
/**
* build flink job vertices list ( 2 level)
* @returns {{children: {label: JSX.Element, value: string, key: string}[], label: JSX.Element, value: string, key: string}[]}
* @param subTaskList
*/
export const buildSubTaskList = (subTaskList: SubTask[]) =>
subTaskList.map((subTask) => {
// build label
let label = (
<div className={'tag-content'}>
<Tag icon={<SyncOutlined spin />} color={'success'}>
{subTask.name}
</Tag>
</div>
);
return {
key: subTask.name,
label: label,
value: subTask.id
};
});
/**
* build running job list ( 1 level)
* @param {Task[]} metrics
* @returns {{label: JSX.Element, value: number, key: string}[]}
*/
export const buildRunningJobList = (metrics: Task[]) =>
metrics.map((item) => {
// build label
let label = (
<div className={'tag-content'}>
<Tag color={'processing'}>
{l('metrics.flink.jobId')}: {item.jid}
</Tag>
<Tag color={'success'}>
{l('metrics.flink.taskId')}: {item.id}
</Tag>
<Tag color={'success'}>
{l('metrics.flink.job.name')}: {item.name}
</Tag>
</div>
);
return {
key: item.name,
label: label,
value: item.id
};
});
/**
* render metrics chart title
* @param {string} metricsId
* @returns {JSX.Element}
*/
export const renderMetricsChartTitle = (metricsId: string, titleWidth: string | number) => {
return (
<>
<Paragraph style={{ width: titleWidth }} code ellipsis={{ tooltip: true }}>
{metricsId}
</Paragraph>
</>
);
};
/*
*
* 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 FlinkChart from '@/components/Flink/FlinkChart';
import { ChartData, JobMetrics, MetricsLayout, SubTask, Task } from '@/pages/Metrics/Job/data';
import {
buildMetricsList,
buildRunningJobList,
buildSubTaskList
} from '@/pages/Metrics/Job/function';
import { getFlinkRunTask, saveFlinkMetrics } from '@/pages/Metrics/Job/service';
import { getData } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
import { l } from '@/utils/intl';
import { ProCard, ProFormSelect } from '@ant-design/pro-components';
import { Button, Input, Row } from 'antd';
import { useEffect, useState } from 'react';
const getJobMetrics = async (job: JobMetrics) => {
const url =
API_CONSTANTS.FLINK_PROXY +
'/' +
job.url +
'/jobs/' +
job.flinkJobId +
'/vertices/' +
job.subTaskId +
'/metrics' +
'?get=' +
encodeURIComponent(job.metrics);
const json = await getData(url);
json[0].time = new Date();
return json[0] as ChartData;
};
const Job = () => {
const [metricsData, setMetricsData] = useState({
url: '',
jid: '',
flinkName: '',
selectTaskId: 0,
selectSubTask: '',
selectMetrics: [] as string[]
});
const [subTaskList, setSubTaskList] = useState<SubTask[]>([]);
const [metrics, setMetrics] = useState<string[]>([]);
const [taskData, setTaskData] = useState<Task[]>([]);
const [jobMetricsList, setJobMetricsList] = useState<JobMetrics[]>([]);
const [chartData, setChartData] = useState<Record<string, ChartData[]>>({});
const [layoutName, setLayoutName] = useState<string>('');
const [timers, setTimers] = useState<Record<string, NodeJS.Timer>>({});
useEffect(() => {
getFlinkRunTask().then((res) => {
setTaskData(res.data);
});
}, []);
useEffect(() => {
Object.keys(timers)
.filter((x) => !jobMetricsList.map((x) => x.metrics).includes(x))
// @ts-ignore
.forEach((x) => clearInterval(timers[x]));
}, [jobMetricsList]);
/**
* query flink job detail
* @param {number} id
* @returns {Promise<any>}
*/
const getFlinkTaskDetail = async (id: number) => {
return await getData(API_CONSTANTS.REFRESH_JOB_DETAIL, { id: id });
};
/**
* query flink job sub task
* @param {string} url
* @param {string} jid
* @returns {Promise<[]>}
*/
const getFlinkJobSubTask = async (url: string, jid: string) => {
const flinkJobVertices = await getData(API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid);
return flinkJobVertices.vertices as SubTask[];
};
/**
* query flink job metrics list
* @param {string} url
* @param {string} jid
* @param subTask
* @returns {Promise<string[]>}
*/
const getFlinkJobMetrics = async (url: string, jid: string, subTask: string) => {
const flinkJobMetrics = await getData(
API_CONSTANTS.FLINK_PROXY + '/' + url + '/jobs/' + jid + '/vertices/' + subTask + '/metrics'
);
return (flinkJobMetrics as any[]).map((x) => x.id as string);
};
/**
* 1 level , change running job
* @returns {Promise<void>}
* @param taskId
*/
const handleRunningJobChange = async (taskId: number) => {
// query data of flink running job
const taskDetail = await getFlinkTaskDetail(taskId);
// 解构出 flink job url , job name , job id
const {
cluster: { hosts: url },
instance: { name: flinkJobName, jid: flinkJobId }
} = taskDetail.data;
setMetricsData((prevState) => ({
...prevState,
url: url,
flinkName: flinkJobName,
jid: flinkJobId,
selectTaskId: taskId
}));
const subTasks = await getFlinkJobSubTask(url, flinkJobId);
setSubTaskList(subTasks);
};
/**
* 2 level , change subtask
* @returns {Promise<void>}
* @param subTaskName
*/
const handleSubTaskChange = async (subTaskName: string) => {
setMetricsData((prevState) => ({
...prevState,
selectSubTask: subTaskName
}));
const jobMetricsDataList = await getFlinkJobMetrics(
metricsData.url,
metricsData.jid,
subTaskName
);
setMetrics(jobMetricsDataList.sort());
};
/**
* 3 level , change metrics list
* @returns {Promise<void>}
* @param selectList
*/
const handleMetricsChange = async (selectList: string[]) => {
setMetricsData((prevState) => ({
...prevState,
selectMetrics: selectList
}));
const d: JobMetrics[] = selectList.map((item) => {
return {
taskId: metricsData.selectTaskId,
url: metricsData.url,
flinkJobId: metricsData.jid,
jobName: metricsData.flinkName,
subTaskId: metricsData.selectSubTask,
metrics: item,
layoutName: layoutName,
title: item,
showSize: '25%',
showType: 'Chart'
};
});
d.forEach((j) => {
const data: ChartData[] = [];
chartData[j.taskId + j.subTaskId + j.metrics] = data;
setChartData(chartData);
timers[j.metrics] = setInterval(() => {
getJobMetrics(j).then((res) => {
data.push(res);
});
}, 1000);
setTimers(timers);
});
setJobMetricsList(d);
};
/**
* render metrics card list
* @param {JobMetrics[]} metricsList
* @returns {JSX.Element}
*/
const renderMetricsCardList = (metricsList: JobMetrics[]) => {
return (
<>
<Row gutter={[8, 16]}>
{metricsList.map((j) => {
return (
<FlinkChart
key={j.taskId + j.subTaskId + j.metrics}
chartSize={j.showSize}
chartType={j.showType}
onChangeJobState={(chartSize, chartType) => {
j.showSize = chartSize;
j.showType = chartType;
}}
data={chartData[j.taskId + j.subTaskId + j.metrics]}
title={j.metrics}
/>
);
})}
</Row>
</>
);
};
return (
<>
<ProCard
ghost
hoverable
bordered
headerBordered
gutter={[0, 8]}
title={
<Input
placeholder='Flink Job Metrics'
onChange={(e) => setLayoutName(e.target.value)}
style={{ width: '100vh' }}
/>
}
extra={
<Button
size='middle'
onClick={() => {
const saveThisLayout = () => {
const metricsLayouts: MetricsLayout[] = jobMetricsList.map((job, index) => {
return {
layoutName: layoutName,
position: index,
metrics: job.metrics,
showSize: job.showSize,
showType: job.showType,
taskId: job.taskId,
vertices: job.subTaskId,
title: job.metrics
} as MetricsLayout;
});
saveFlinkMetrics(metricsLayouts).then((res) => {
if (res.success) {
setSubTaskList([]);
setMetrics([]);
setJobMetricsList([]);
}
});
};
saveThisLayout();
}}
>
{l('button.submit')}
</Button>
}
>
<ProFormSelect
name='job'
label={l('metrics.flink.job.name')}
placeholder={l('metrics.flink.job.placeholder')}
options={buildRunningJobList(taskData)}
fieldProps={{ onChange: (value) => handleRunningJobChange(value as number) }}
/>
{metricsData.selectTaskId !== 0 && (
<ProFormSelect
name='vertices'
label={l('metrics.flink.subTask')}
placeholder={l('metrics.flink.subTask.placeholder')}
options={buildSubTaskList(subTaskList)}
fieldProps={{ onChange: (value) => handleSubTaskChange(value as string) }}
/>
)}
{metricsData.selectSubTask !== '' && (
<ProFormSelect
name='metrics'
label={l('metrics.flink.metrics.name')}
placeholder={l('metrics.flink.metrics.placeholder')}
options={buildMetricsList(metrics)}
mode='multiple'
fieldProps={{ onChange: (value) => handleMetricsChange(value as string[]) }}
/>
)}
{/* render metrics list */}
{jobMetricsList.length > 0 && renderMetricsCardList(jobMetricsList)}
</ProCard>
</>
);
};
export default Job;
/*
*
* 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 { MetricsLayout } from '@/pages/Metrics/Job/data';
import { putDataAsArray, queryList } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
/**
* 获取 运行的 flink任务 列表
* @returns {Promise<any>}
*/
export async function getFlinkRunTask() {
return queryList(API_CONSTANTS.JOB_INSTANCE, {
filter: {},
currentPage: 1,
status: 'RUNNING',
sorter: { id: 'descend' }
});
}
export async function saveFlinkMetrics(jobList: MetricsLayout[]) {
return await putDataAsArray(API_CONSTANTS.SAVE_FLINK_METRICS, jobList);
}
......@@ -17,40 +17,13 @@
*
*/
export type JobMetrics = {
taskId: number;
flinkJobId: string;
jobName: string;
subTaskId: string;
metrics: string;
url: string;
title: string;
layoutName: string;
showType: string;
showSize: string;
};
export type Task = {
id: number;
jid: string;
name: string;
type: string;
clusterName: string;
};
export type SubTask = {
id: string;
name: string;
status: string;
parallelism: number;
};
export type ChartData = {
time: Date;
value: number | string;
};
export type MetricsLayout = {
id: number;
taskId: number;
vertices: string;
metrics: string;
......
......@@ -17,15 +17,19 @@
*
*/
import { PopconfirmDeleteBtn } from '@/components/CallBackButton/PopconfirmDeleteBtn';
import FlinkChart from '@/components/Flink/FlinkChart';
import useHookRequest from '@/hooks/useHookRequest';
import { SseData } from '@/models/Sse';
import { SSE_TOPIC } from '@/pages/DevOps/constants';
import { JobMetricsItem, MetricsTimeFilter } from '@/pages/DevOps/JobDetail/data';
import { getMetricsData } from '@/pages/DevOps/JobDetail/srvice';
import { ChartData } from '@/pages/Metrics/Job/data';
import { ChartData } from '@/pages/Metrics/JobMetricsList/data';
import { MetricsDataType } from '@/pages/Metrics/Server/data';
import { getMetricsLayout } from '@/pages/Metrics/service';
import { handleRemoveById } from '@/services/BusinessCrud';
import { API_CONSTANTS } from '@/services/endpoints';
import { l } from '@/utils/intl';
import { useModel } from '@@/exports';
import { ProCard } from '@ant-design/pro-components';
import { Empty, Row, Spin } from 'antd';
......@@ -41,7 +45,7 @@ const JobMetricsList = (props: MetricsProps) => {
const [chartDatas, setChartDatas] = useState<Record<string, ChartData[]>>({});
const [jobIds, setJobIds] = useState<string>('');
const { data } = useHookRequest<any, any>(getMetricsLayout, { defaultParams: [] });
const { data, refresh } = useHookRequest<any, any>(getMetricsLayout, { defaultParams: [] });
const dataProcess = (sourceData: Record<string, ChartData[]>, datas: MetricsDataType[]) => {
datas.forEach((item) => {
......@@ -116,7 +120,27 @@ const JobMetricsList = (props: MetricsProps) => {
data.map((lo: any) => {
return (
<Spin spinning={loading} key={`spin-${lo.layoutName}`}>
<ProCard key={lo.layoutName} title={lo.layoutName} collapsible ghost gutter={[0, 8]}>
<ProCard
key={lo.layoutName}
bordered
hoverable
title={lo.layoutName}
collapsible
ghost
gutter={[0, 8]}
subTitle={
<PopconfirmDeleteBtn
onClick={async () => {
await handleRemoveById(API_CONSTANTS.METRICS_LAYOUT_DELETE, lo.taskId, () => {
refresh();
});
}}
description={
<span className={'needWrap'}>{l('metrics.flink.deleteConfirm')}</span>
}
/>
}
>
<Row gutter={[8, 16]}>{renderFlinkChartGroup(lo.flinkJobId, lo.metrics)}</Row>
</ProCard>
</Spin>
......
......@@ -66,7 +66,7 @@ export default () => {
content={
<>
{showServer.data && (
<ProCard collapsible title={'Dinky Server'} ghost>
<ProCard collapsible title={'Dinky Server'} ghost bordered hoverable>
<Server timeRange={timeRange} />
</ProCard>
)}
......
......@@ -271,6 +271,7 @@ export enum API_CONSTANTS {
MONITOR_GET_LAST_DATA = '/api/monitor/getLastUpdateData',
MONITOR_GET_JVM_INFO = '/api/monitor/getJvmInfo',
METRICS_LAYOUT_GET_BY_NAME = '/api/monitor/getMetricsLayoutByName',
METRICS_LAYOUT_DELETE = '/api/monitor/deleteMetricsLayout',
JOB_METRICS = '/api/monitor/jobMetrics',
SAVE_FLINK_METRICS = '/api/monitor/saveFlinkMetrics/',
GET_METRICS_LAYOUT = '/api/monitor/getMetricsLayout',
......
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