Unverified Commit a2a142d8 authored by gaoyan's avatar gaoyan Committed by GitHub

fix restart error (#2899)

Co-authored-by: 's avatarZzm0809 <934230207@qq.com>
parent 87d67fa1
......@@ -48,6 +48,7 @@ import org.springframework.web.context.request.ServletRequestAttributes;
import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
/**
* WebExceptionHandler
......@@ -56,11 +57,13 @@ import cn.hutool.core.util.StrUtil;
*/
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
@Slf4j
public class WebExceptionHandler {
@ExceptionHandler
@ResponseBody
public Result<Void> busException(BusException e) {
log.error("BusException:", e);
if (StrUtil.isEmpty(e.getMsg())) {
return Result.failed(I18n.getMessage(e.getCode(), e.getMessage()));
}
......
......@@ -81,12 +81,14 @@ public interface TaskService extends ISuperService<Task> {
JobResult debugTask(TaskDTO task) throws Exception;
/**
* Restart the given task and return the job result.
*
* This class implements the TaskService interface and provides functionality to restart a task.
* It checks if the task exists and if it is not a common SQL dialect. If the job instance is not done,
* it cancels the job and triggers a savepoint if necessary.
* It then waits for the job to complete and submits the task again with the savepoint path.
* @param id The ID of the task to restart.
* @param savePointPath The path of the save point for the job execution.
* @return A {@link JobResult} object representing the result of the restarted task.
* @throws ExcuteException If there is an error restarting the task.
* @param savePointPath The savepoint path to use for restarting the task.
* @return A JobResult object containing the status of the job.
* @throws Exception If there is an error while restarting the task.
*/
JobResult restartTask(Integer id, String savePointPath) throws Exception;
......
......@@ -36,7 +36,6 @@ import org.dinky.data.enums.Status;
import org.dinky.data.exception.BusException;
import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.exception.SqlExplainExcepition;
import org.dinky.data.exception.TaskNotDoneException;
import org.dinky.data.model.Catalogue;
import org.dinky.data.model.ClusterConfiguration;
import org.dinky.data.model.ClusterInstance;
......@@ -46,6 +45,7 @@ import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Task;
import org.dinky.data.model.TaskVersion;
import org.dinky.data.model.alert.AlertGroup;
import org.dinky.data.model.ext.JobInfoDetail;
import org.dinky.data.model.ext.TaskExtConfig;
import org.dinky.data.model.home.JobModelOverview;
import org.dinky.data.model.home.JobTypeOverView;
......@@ -91,6 +91,7 @@ import org.dinky.utils.UDFUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.TextUtils;
import java.io.IOException;
import java.io.InputStreamReader;
......@@ -168,7 +169,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
}
@ProcessStep(type = ProcessStepType.SUBMIT_PRECHECK)
public TaskDTO prepareTask(TaskSubmitDto submitDto) throws TaskNotDoneException {
public TaskDTO prepareTask(TaskSubmitDto submitDto) {
TaskDTO task = this.getTaskInfoById(submitDto.getId());
log.info("Start check and config task, task:{}", task.getName());
......@@ -282,7 +283,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
try {
config.setAddress(clusterInstanceService.buildEnvironmentAddress(config));
} catch (Exception e) {
log.error("Init remote cluster error:{}", e.getMessage());
throw new BusException(e.getMessage());
}
return config;
}
......@@ -365,11 +366,46 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override
public JobResult restartTask(Integer id, String savePointPath) throws Exception {
TaskDTO task = this.getTaskInfoById(id);
boolean useSavepoint = !TextUtils.isEmpty(savePointPath);
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage());
if (!Dialect.isCommonSql(task.getDialect()) && Asserts.isNotNull(task.getJobInstanceId())) {
String status = jobInstanceService.getById(task.getJobInstanceId()).getStatus();
JobInstance jobInstance = jobInstanceService.getById(task.getJobInstanceId());
Assert.notNull(jobInstance, Status.JOB_INSTANCE_NOT_EXIST.getMessage());
String status = jobInstance.getStatus();
if (!JobStatus.isDone(status)) {
cancelTaskJob(task, true);
log.info("JobInstance [{}] status is [{}], stop it now", jobInstance.getName(), status);
JobManager jobManager = JobManager.build(buildJobConfig(task));
// If a user specifies a savepoint, the savepoint is not automatically triggered
if (useSavepoint) {
jobManager.cancelNormal(jobInstance.getJid());
} else {
log.info("stop {} with savepoint", jobInstance.getName());
SavePointResult savePointResult = savepointTaskJob(task, SavePointType.CANCEL);
// Although the return is an array, it is generally only one
for (JobInfo jobInfo : savePointResult.getJobInfos()) {
savePointPath = jobInfo.getSavePoint();
}
}
int count = 0;
while (true) {
JobInfoDetail jobInfoDetail = jobInstanceService.refreshJobInfoDetail(jobInstance.getId(), false);
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus())) {
log.info(
"JobInstance [{}] status is [{}], ready to submit Job",
jobInstance.getName(),
jobInfoDetail.getInstance().getStatus());
break;
} else if (count > 10) {
throw new BusException("stop job failed, please check job status");
}
log.warn(
"JobInstance [{}] status is [{}], wait 2s to check again",
jobInstance.getName(),
jobInfoDetail.getInstance().getStatus());
count++;
Thread.sleep(2000);
}
}
}
return submitTask(
......@@ -387,7 +423,21 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Assert.notNull(clusterInstance, Status.CLUSTER_NOT_EXIST.getMessage());
JobManager jobManager = JobManager.build(buildJobConfig(task));
return jobManager.cancel(jobInstance.getJid(), withSavePoint);
boolean isSuccess;
try {
if (withSavePoint) {
savepointTaskJob(task, SavePointType.CANCEL);
} else {
jobManager.cancelNormal(jobInstance.getJid());
}
isSuccess = true;
} catch (Exception e) {
log.warn("Stop with savcePoint failed: {}, will try normal rest api stop", e.getMessage());
isSuccess = jobManager.cancelNormal(jobInstance.getJid());
}
jobInstanceService.refreshJobInfoDetail(jobInstance.getId(), true);
return isSuccess;
}
@Override
......
......@@ -385,26 +385,6 @@ public class JobManager {
.getJsonPlan();
}
public boolean cancel(String jobId, boolean withSavePoint) {
if (useGateway && !useRestAPI) {
config.getGatewayConfig()
.setFlinkConfig(FlinkConfig.build(jobId, ActionType.CANCEL.getValue(), null, null));
Gateway.build(config.getGatewayConfig()).savepointJob();
return true;
} else if (useRestAPI && withSavePoint) {
try {
// Try to savepoint, if it fails, it will stop normally(尝试进行savepoint,如果失败,即普通停止)
savepoint(jobId, SavePointType.CANCEL, null);
return true;
} catch (Exception e) {
log.warn("Stop with savcePoint failed: {}, will try normal rest api stop", e.getMessage());
return cancelNormal(jobId);
}
} else {
return cancelNormal(jobId);
}
}
public boolean cancelNormal(String jobId) {
try {
return FlinkAPI.build(config.getAddress()).stop(jobId);
......
......@@ -24,10 +24,11 @@ const { Paragraph, Text } = Typography;
type EllipsisMiddleProps = {
maxCount: number;
children: string;
copyable?: boolean;
};
const EllipsisMiddle: React.FC<EllipsisMiddleProps> = (props) => {
const { maxCount, children } = props;
const { maxCount, children, copyable = true } = props;
let start = '';
let end;
let tip = '';
......@@ -41,7 +42,7 @@ const EllipsisMiddle: React.FC<EllipsisMiddleProps> = (props) => {
}
return (
<Tooltip title={tip}>
<Text copyable={true}>
<Text copyable={copyable}>
{start}
{end ? `......${end}` : ''}
</Text>
......
......@@ -200,11 +200,20 @@ export default {
'devops.jobinfo.recently.job.status': 'View recently saved job status information',
'devops.jobinfo.reonline': 'Re-Online',
'devops.jobinfo.restart': 'Restart',
'devops.jobinfo.restart.auto.savepoint': 'Automatically create a save point and restart',
'devops.jobinfo.restart.from.savepoint': 'Restart from the save point',
'devops.jobinfo.restart.from.savepoint.help':
'Stop the job and start from the specified save point, this option will not automatically create a save point (be sure to ensure that this path exists, otherwise the restart will fail)',
'devops.jobinfo.restart.cannot.auto.savepoint':
'The job has been stopped and Smart Restart is not available',
'devops.jobinfo.savepoint.cancel': 'Savepoint Stop',
'devops.jobinfo.savepoint.canceljob': 'Normal Stop',
'devops.jobinfo.savepoint.stop': 'Savepoint Pause',
'devops.jobinfo.savepoint.trigger': 'Savepoint Triggers',
'devops.jobinfo.smart_stop': 'Smart Stop',
'devops.jobinfo.smart_restart': 'Smart restart',
'devops.jobinfo.smart_restart.help':
'A save point is automatically created and started from a job stop during the job stop process',
'devops.jobinfo.unable.obtain.status':
'Unable to connect to Flink cluster to obtain the latest job status information',
'devops.jobinfo.version.delete': 'Delete Version',
......
......@@ -191,11 +191,18 @@ export default {
'devops.jobinfo.recently.job.status': '查看最近保存的作业状态信息',
'devops.jobinfo.reonline': '重新上线',
'devops.jobinfo.restart': '重新启动',
'devops.jobinfo.restart.auto.savepoint': '自动创建保存点并重启',
'devops.jobinfo.restart.from.savepoint': '从保存点重启',
'devops.jobinfo.restart.from.savepoint.help':
'停止作业并从指定保存点启动,此选项不会自动创建保存点(请务必保证此路径存在,否则会重启失败)',
'devops.jobinfo.restart.cannot.auto.savepoint': '作业已停止,无法使用智能重启',
'devops.jobinfo.savepoint.cancel': 'Savepoint 停止',
'devops.jobinfo.savepoint.canceljob': '普通停止',
'devops.jobinfo.savepoint.stop': 'Savepoint 暂停',
'devops.jobinfo.savepoint.trigger': 'Savepoint 触发',
'devops.jobinfo.smart_stop': '智能停止',
'devops.jobinfo.smart_restart': '智能重启',
'devops.jobinfo.smart_restart.help': '在作业停止过程中会自动创建保存点并从此保存点启动',
'devops.jobinfo.unable.obtain.status': '无法连接到 Flink 集群获取最新作业状态信息',
'devops.jobinfo.version.delete': '删除版本',
'devops.jobinfo.version.delete.sure': '确定删除此版本吗?V{version}',
......
......@@ -40,8 +40,8 @@ export function cancelTask(title: string, id: number, withSavePoint: boolean = t
return handleGetOption(API_CONSTANTS.CANCEL_JOB, title, { id, withSavePoint });
}
export function restartTask(title: string, id: number, isOnLine: boolean) {
return handleGetOption(API_CONSTANTS.RESTART_TASK, title, { id, isOnLine });
export function restartTask(id: number, savePointPath: string) {
return handleGetOption(API_CONSTANTS.RESTART_TASK, '', { id, savePointPath });
}
export function savePointTask(title: string, taskId: number, savePointType: string) {
return handleGetOption(API_CONSTANTS.SAVEPOINT, title, { taskId, savePointType });
......
......@@ -18,10 +18,8 @@
*/
import EllipsisMiddle from '@/components/Typography/EllipsisMiddle';
import { JOB_LIFE_CYCLE } from '@/pages/DevOps/constants';
import { recoveryCheckPoint } from '@/pages/DevOps/JobDetail/CheckPointsTab/components/functions';
import { JobProps } from '@/pages/DevOps/JobDetail/data';
import { getData } from '@/services/api';
import { API_CONSTANTS } from '@/services/endpoints';
import { parseByteStr, parseMilliSecondStr } from '@/utils/function';
import { l } from '@/utils/intl';
import {
......@@ -31,7 +29,7 @@ import {
SyncOutlined
} from '@ant-design/icons';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Modal, Tag } from 'antd';
import { Button, Tag } from 'antd';
import { useRef } from 'react';
export type CheckPointsDetailInfo = {
......@@ -52,38 +50,6 @@ const CheckpointTable = (props: JobProps) => {
const checkpoints = jobDetail?.jobDataDto?.checkpoints;
// const restartFromCheckpoint = useRequest((id: number, isOnLine: boolean, savePointPath: string) => (
// {
// url: API_CONSTANTS.RESTART_TASK_FROM_CHECKPOINT,
// params: {id: id, isOnLine: isOnLine, savePointPath: savePointPath}
// }
// ),
// {manual: true});
function recoveryCheckPoint(row: CheckPointsDetailInfo) {
Modal.confirm({
title: l('devops.jobinfo.ck.recovery'),
content: l('devops.jobinfo.ck.recoveryConfirm', '', {
path: row.external_path
}),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
const param = {
id: jobDetail?.instance?.taskId,
isOnLine: jobDetail?.instance?.step == JOB_LIFE_CYCLE.PUBLISH,
savePointPath: row.external_path
};
const result = await getData(API_CONSTANTS.RESTART_TASK_FROM_CHECKPOINT, param);
if (result.code == 0) {
message.success(l('devops.jobinfo.ck.recovery.success'));
} else {
message.error(l('devops.jobinfo.ck.recovery.failed'));
}
}
});
}
const columns: ProColumns<CheckPointsDetailInfo>[] = [
{
title: l('devops.jobinfo.ck.id'),
......@@ -165,7 +131,11 @@ const CheckpointTable = (props: JobProps) => {
return (
<>
{entity.status === 'COMPLETED' ? (
<Button onClick={() => recoveryCheckPoint(entity)}>
<Button
onClick={() =>
recoveryCheckPoint(jobDetail?.instance?.taskId, entity.external_path)
}
>
{l('devops.jobinfo.ck.recovery.recoveryTo')}
</Button>
) : undefined}
......
......@@ -18,12 +18,14 @@
*/
import EllipsisMiddle from '@/components/Typography/EllipsisMiddle';
import { recoveryCheckPoint } from '@/pages/DevOps/JobDetail/CheckPointsTab/components/functions';
import { JobProps } from '@/pages/DevOps/JobDetail/data';
import { queryDataByParams } from '@/services/BusinessCrud';
import { API_CONSTANTS } from '@/services/endpoints';
import { SavePoint } from '@/types/Studio/data';
import { l } from '@/utils/intl';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
const SavepointTable = (props: JobProps) => {
......@@ -76,6 +78,17 @@ const SavepointTable = (props: JobProps) => {
align: 'center',
valueType: 'dateTime',
dataIndex: 'createTime'
},
{
title: l('global.table.operate'),
align: 'center',
render: (dom, entity) => {
return (
<Button onClick={() => recoveryCheckPoint(jobDetail?.instance?.taskId, entity.path)}>
{l('devops.jobinfo.ck.recovery.recoveryTo')}
</Button>
);
}
}
];
......
/*
*
* 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 { restartTask } from '@/pages/DataStudio/HeaderContainer/service';
import { l } from '@/utils/intl';
import { message, Modal } from 'antd';
export const recoveryCheckPoint = (taskId: number, path: string) => {
Modal.confirm({
title: l('devops.jobinfo.ck.recovery'),
content: l('devops.jobinfo.ck.recoveryConfirm', '', {
path: path
}),
okText: l('button.confirm'),
cancelText: l('button.cancel'),
onOk: async () => {
const result = await restartTask(taskId, path);
if (result.code == 0) {
message.success(l('devops.jobinfo.ck.recovery.success'));
} else {
message.error(l('devops.jobinfo.ck.recovery.failed'));
}
}
});
};
......@@ -17,17 +17,16 @@
*
*/
import { cancelTask, restartTask, savePointTask } from '@/pages/DataStudio/HeaderContainer/service';
import { JOB_LIFE_CYCLE } from '@/pages/DevOps/constants';
import { cancelTask, savePointTask } from '@/pages/DataStudio/HeaderContainer/service';
import { isStatusDone } from '@/pages/DevOps/function';
import EditJobInstanceForm from '@/pages/DevOps/JobDetail/JobOperator/components/EditJobInstanceForm';
import RestartForm from '@/pages/DevOps/JobDetail/JobOperator/components/RestartForm';
import { Jobs } from '@/types/DevOps/data';
import { l } from '@/utils/intl';
import { EllipsisOutlined, RedoOutlined } from '@ant-design/icons';
import { Button, Dropdown, message, Modal, Space } from 'antd';
const operatorType = {
RESTART_JOB: 'restart',
CANCEL_JOB: 'canceljob',
SAVEPOINT_CANCEL: 'cancel',
SAVEPOINT_TRIGGER: 'trigger',
......@@ -51,12 +50,6 @@ const JobOperator = (props: OperatorType) => {
onOk: async () => {
if (key == operatorType.CANCEL_JOB) {
cancelTask('', jobDetail?.instance?.taskId, false);
} else if (key == operatorType.RESTART_JOB) {
restartTask(
'',
jobDetail?.instance?.taskId,
jobDetail?.instance?.step == JOB_LIFE_CYCLE.PUBLISH
);
} else if (key == operatorType.SAVEPOINT_CANCEL) {
savePointTask('', jobDetail?.instance?.taskId, 'cancel');
} else if (key == operatorType.SAVEPOINT_STOP) {
......@@ -79,15 +72,11 @@ const JobOperator = (props: OperatorType) => {
<Button key='flinkwebui' href={webUri} target={'_blank'}>
FlinkWebUI
</Button>
<Button
key='autorestart'
type='primary'
onClick={() => handleJobOperator(operatorType.RESTART_JOB)}
>
{jobDetail?.instance?.step == 5
? l('devops.jobinfo.reonline')
: l('devops.jobinfo.restart')}
</Button>
<RestartForm
lastCheckpoint={jobDetail?.jobDataDto?.checkpoints?.latest}
instance={jobDetail?.instance}
/>
{isStatusDone(jobDetail?.instance?.status as string) ? (
<></>
......
/*
*
* 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 EllipsisMiddle from '@/components/Typography/EllipsisMiddle';
import useHookRequest from '@/hooks/useHookRequest';
import { restartTask } from '@/pages/DataStudio/HeaderContainer/service';
import { isStatusDone } from '@/pages/DevOps/function';
import { Jobs } from '@/types/DevOps/data';
import { parseByteStr } from '@/utils/function';
import { l } from '@/utils/intl';
import { ModalForm } from '@ant-design/pro-components';
import { Alert, Button, Descriptions, DescriptionsProps, Divider, Spin, Typography } from 'antd';
const { Paragraph } = Typography;
const RestartForm = (props: { lastCheckpoint: any; instance: Jobs.JobInstance }) => {
const { lastCheckpoint, instance } = props;
const { data, loading, run } = useHookRequest(restartTask, {
defaultParams: [instance?.taskId, ''],
manual: true
});
const buildDesc = (ckp: any, title: string) => {
if (!ckp) {
return (
<>
<Alert message={`Not Found ${title}`} type='warning' />
<br />
</>
);
}
const items: DescriptionsProps['items'] = [
{
key: 'ckp_id',
label: 'ID',
children: ckp.id
},
{
key: 'ckp_state_size',
label: l('devops.jobinfo.ck.state_size'),
children: parseByteStr(ckp.state_size)
},
{
key: 'latest_ack_timestamp',
label: l('devops.jobinfo.ck.latest_ack_timestamp'),
children: new Date(ckp.latest_ack_timestamp).toLocaleString('zh-cn')
},
{
key: 'ckp_path',
label: l('devops.jobinfo.ck.external_path'),
span: 4,
children: <EllipsisMiddle maxCount={60} children={ckp.external_path} copyable={false} />
}
];
return (
<>
<Descriptions
title={title}
size={'small'}
bordered
items={items}
extra={
<Button type={'link'} onClick={() => run(instance?.taskId, ckp.external_path)}>
重启后此处恢复
</Button>
}
/>
<br />
</>
);
};
return (
<ModalForm
loading={loading}
title={l('devops.jobinfo.restart')}
trigger={<Button type={'primary'}>{l('devops.jobinfo.restart')}</Button>}
submitter={false}
>
<Spin spinning={loading}>
{instance?.status && !isStatusDone(instance?.status) ? (
<>
<Divider orientation={'left'} style={{ margin: '8px 0' }}>
{l('devops.jobinfo.smart_restart')}
</Divider>
<Paragraph>
<blockquote>{l('devops.jobinfo.smart_restart.help')}</blockquote>
</Paragraph>
<Button type={'link'} size={'small'} onClick={() => run(instance?.taskId, '')}>
{l('devops.jobinfo.restart.auto.savepoint')}
</Button>
</>
) : (
<Alert message={l('devops.jobinfo.restart.cannot.auto.savepoint')} type={'warning'} />
)}
<Divider orientation={'left'} style={{ margin: '8px 0' }}>
{l('devops.jobinfo.restart.from.savepoint')}
</Divider>
<Paragraph>
<blockquote>{l('devops.jobinfo.restart.from.savepoint.help')}</blockquote>
</Paragraph>
{buildDesc(lastCheckpoint?.completed, 'Last Checkpoint')}
{buildDesc(lastCheckpoint?.savepoint, 'Last Savepoint')}
</Spin>
</ModalForm>
);
};
export default RestartForm;
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