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

Add job done hook, Solve the problem of getting "UNKNOWN" after job completion…

Add job done hook, Solve the problem of getting "UNKNOWN" after job completion in application mode (#2494) * Optimize the process * add job done hook * optimizeTheCode * optimizeTheCode
parent 2551fd76
......@@ -46,6 +46,7 @@ import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.lang.Dict;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
......@@ -133,8 +134,9 @@ public class JobInstanceController {
dataType = "Integer",
paramType = "query",
required = true)
public Result<JobInfoDetail> refreshJobInfoDetail(@RequestParam Integer id) {
return Result.succeed(jobInstanceService.refreshJobInfoDetail(id));
public Result<JobInfoDetail> refreshJobInfoDetail(
@RequestParam Integer id, @RequestParam(defaultValue = "false") boolean isForce) {
return Result.succeed(jobInstanceService.refreshJobInfoDetail(id, isForce));
}
/**
......@@ -301,4 +303,16 @@ public class JobInstanceController {
@RequestParam String metrics) {
return Result.succeed(FlinkAPI.build(address).getJobMetricsData(jobId, verticeId, metrics));
}
@GetMapping("/hookJobDone")
@ApiOperation("hookJobDone")
@SaIgnore
public Result<Dict> hookJobDone(@RequestParam String jobId, @RequestParam Integer taskId) {
boolean done = jobInstanceService.hookJobDone(jobId, taskId);
if (done) {
return Result.succeed();
} else {
return Result.failed();
}
}
}
......@@ -58,6 +58,11 @@ public class FlinkJobTask implements DaemonTask {
return this;
}
@Override
public DaemonTaskConfig getConfig() {
return config;
}
/**
* Processing tasks.
* <p>
......
......@@ -55,6 +55,8 @@ import org.springframework.stereotype.Component;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
......@@ -90,12 +92,18 @@ public class JobRefreshHandler {
jobInfoDetail.getInstance().getName());
JobInstance jobInstance = jobInfoDetail.getInstance();
JobDataDto jobDataDto = jobInfoDetail.getJobDataDto();
String oldStatus = jobInstance.getStatus();
JobDataDto jobDataDto = getJobHistory(
jobInstance.getId(),
jobInfoDetail.getClusterInstance().getJobManagerHost(),
jobInfoDetail.getInstance().getJid());
// Update the value of JobData from the flink api while ignoring the null value to prevent
// some other configuration from being overwritten
BeanUtil.copyProperties(
getJobData(
jobInstance.getId(),
jobInfoDetail.getClusterInstance().getJobManagerHost(),
jobInfoDetail.getInstance().getJid()),
jobDataDto,
CopyOptions.create().ignoreNullValue());
if (Asserts.isNull(jobDataDto.getJob()) || jobDataDto.isError()) {
// If the job fails to get it, the default Finish Time is the current time
......@@ -164,7 +172,7 @@ public class JobRefreshHandler {
* @param jobId The job ID.
* @return {@link org.dinky.data.dto.JobDataDto}.
*/
public static JobDataDto getJobHistory(Integer id, String jobManagerHost, String jobId) {
public static JobDataDto getJobData(Integer id, String jobManagerHost, String jobId) {
JobDataDto.JobDataDtoBuilder builder = JobDataDto.builder();
FlinkAPI api = FlinkAPI.build(jobManagerHost);
try {
......
......@@ -83,7 +83,16 @@ public interface JobInstanceService extends ISuperService<JobInstance> {
* @param jobInstanceId The ID of the job instance to refresh the job information detail for.
* @return A {@link JobInfoDetail} object representing the refreshed job information detail.
*/
JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId);
JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId, boolean isForce);
/**
* Hook the job done for the given job ID and task ID.
*
* @param jobId The ID of the job to hook the job done for.
* @param taskId The ID of the task to hook the job done for.
* @return A boolean indicating whether the hooking was successful or not.
*/
boolean hookJobDone(String jobId, Integer taskId);
/**
* Refresh the job instances for the given task IDs.
......
......@@ -21,7 +21,9 @@ package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.pool.DefaultThreadPool;
import org.dinky.daemon.task.DaemonFactory;
import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig;
import org.dinky.data.dto.ClusterConfigurationDTO;
import org.dinky.data.dto.JobDataDto;
......@@ -56,12 +58,14 @@ import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* JobInstanceServiceImpl
......@@ -70,6 +74,7 @@ import lombok.RequiredArgsConstructor;
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper, JobInstance>
implements JobInstanceService {
......@@ -182,18 +187,48 @@ public class JobInstanceServiceImpl extends SuperServiceImpl<JobInstanceMapper,
}
@Override
public JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId) {
public JobInfoDetail refreshJobInfoDetail(Integer jobInstanceId, boolean isForce) {
JobInfoDetail jobInfoDetail = getJobInfoDetail(jobInstanceId);
JobRefreshHandler.refreshJob(jobInfoDetail, true);
DaemonFactory.refeshOraddTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstanceId));
// Directly returns database data if the task has completed and is not a forced refresh
if (JobStatus.isDone(jobInfoDetail.getInstance().getStatus()) && !isForce) {
return jobInfoDetail;
}
boolean isDone = JobRefreshHandler.refreshJob(jobInfoDetail, true);
// If the task becomes incomplete after a forced refresh, it is re-queued to the task
if (!isDone) {
DaemonFactory.refeshOraddTask(DaemonTaskConfig.build(FlinkJobTask.TYPE, jobInstanceId));
}
return jobInfoDetail;
}
@Override
public boolean hookJobDone(String jobId, Integer taskId) {
LambdaQueryWrapper<JobInstance> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(JobInstance::getJid, jobId).eq(JobInstance::getTaskId, taskId);
JobInstance instance = baseMapper.selectOne(queryWrapper);
if (instance == null) {
// Not having a corresponding jobinstance means that this may not have succeeded in running,
// returning true to prevent retry.
return true;
}
DaemonTaskConfig config = DaemonTaskConfig.build(FlinkJobTask.TYPE, instance.getId());
DaemonTask daemonTask = DefaultThreadPool.getInstance().dequeueByTask(config);
if (daemonTask == null) {
daemonTask = DaemonTask.build(config);
}
boolean isDone = daemonTask.dealTask();
// If the task is not completed, it is re-queued
if (!isDone) {
DefaultThreadPool.getInstance().execute(daemonTask);
}
return isDone;
}
@Override
public void refreshJobByTaskIds(Integer... taskIds) {
for (Integer taskId : taskIds) {
JobInstance instance = getJobInstanceByTaskId(taskId);
refreshJobInfoDetail(instance.getId());
refreshJobInfoDetail(instance.getId(), false);
}
}
......
......@@ -22,6 +22,7 @@ package org.dinky.app;
import org.dinky.app.constant.AppParamConstant;
import org.dinky.app.db.DBUtil;
import org.dinky.app.flinksql.Submitter;
import org.dinky.app.util.FlinkAppUtil;
import org.dinky.data.app.AppParamConfig;
import org.dinky.utils.JsonUtils;
......@@ -55,6 +56,9 @@ public class MainApp {
} catch (Exception e) {
log.error("exectue app failed with config: {}", appConfig);
throw e;
} finally {
log.info("Start Monitor Job");
FlinkAppUtil.monitorFlinkTask(appConfig.getTaskId());
}
}
}
/*
*
* 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.
*
*/
package org.dinky.app.util;
import org.dinky.app.db.DBUtil;
import org.dinky.constant.FlinkConstant;
import org.dinky.data.enums.JobStatus;
import org.dinky.data.enums.Status;
import org.dinky.utils.JsonUtils;
import org.apache.flink.client.deployment.StandaloneClusterId;
import org.apache.flink.client.program.rest.RestClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.runtime.client.JobStatusMessage;
import java.util.Collection;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FlinkAppUtil {
/**
* Utility class for monitoring Flink tasks.
* This method creates a Flink REST client and continuously checks the status of the task until it is completed.
* If the task is completed, it sends a hook notification and stops monitoring.
*/
public static void monitorFlinkTask(int taskId) {
boolean isRun = true;
try (RestClusterClient<StandaloneClusterId> client = createClient()) {
while (isRun) {
Collection<JobStatusMessage> jobs = client.listJobs().get();
if (jobs.isEmpty()) {
log.error("No Flink task found, try again in 2 seconds.....");
}
for (JobStatusMessage job : jobs) {
if (JobStatus.isDone(job.getJobState().toString())) {
sendHook(taskId, job.getJobId().toHexString(), 0);
log.info("hook {} finished.", job.getJobName());
// There should be only one in application mode, so stop monitoring here
isRun = false;
}
}
Thread.sleep(5000);
}
} catch (Exception e) {
// If an exception is thrown, it will cause the k8s pod to trigger a restart,
// resulting in an inability to exit normally
log.error("hook failed:", e);
}
}
/**
* The sendHook method is used to send a Hook request.
* This method sends an HTTP request to notify a specific address about the completion status of a task.
* If the request is successful, the returned code in the result is 0; otherwise, an exception is thrown.
* If sending the request fails, it will be retried up to 30 times with a 1-second interval between each retry.
* If the retry limit is exceeded, an exception is thrown.
*/
private static void sendHook(int taskId, String jobId, int reTryCount) throws InterruptedException {
try {
String dinkyAddr = DBUtil.getSysConfig(Status.SYS_ENV_SETTINGS_DINKYADDR.getKey());
String url = StrFormatter.format(
"http://{}/api/jobInstance/hookJobDone?taskId={}&jobId={}", dinkyAddr, taskId, jobId);
String resultStr = HttpUtil.get(url);
// TODO 这里应该使用Result实体类,但是Result.class不在comm里,迁移改动太大,暂时不搞
String code = JsonUtils.parseObject(resultStr).get("code").toString();
if (!"0".equals(code)) {
throw new RuntimeException("Hook Job Done result failed: " + resultStr);
}
} catch (Exception e) {
if (reTryCount < 30) {
log.error("send hook failed,retry later taskId:{},jobId:{},{}", taskId, jobId, e.getMessage());
Thread.sleep(1000);
sendHook(taskId, jobId, reTryCount + 1);
} else {
throw new RuntimeException("Hook Job Done failed, The retry limit is exceeded: " + e.getMessage());
}
}
}
/**
* Create a REST cluster client for Flink.
* @return
* @throws Exception
*/
private static RestClusterClient<StandaloneClusterId> createClient() throws Exception {
Configuration config;
Configuration fromEnvConfig = GlobalConfiguration.loadConfiguration();
if (!fromEnvConfig.keySet().isEmpty()) {
config = fromEnvConfig;
} else {
config = GlobalConfiguration.loadConfiguration(FlinkConstant.DEFAULT_FLINK_HOME);
}
return new RestClusterClient<>(config, StandaloneClusterId.getInstance());
}
}
......@@ -19,6 +19,9 @@
package org.dinky.daemon.entity;
import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig;
import java.util.LinkedList;
import lombok.Getter;
......@@ -26,7 +29,7 @@ import lombok.extern.slf4j.Slf4j;
@Getter
@Slf4j
public class TaskQueue<T> {
public class TaskQueue<T extends DaemonTask> {
private final LinkedList<T> tasks = new LinkedList<>();
......@@ -36,7 +39,7 @@ public class TaskQueue<T> {
synchronized (lock) {
lock.notifyAll();
// prevent duplicate additions
tasks.remove(task);
dequeueByTask(task.getConfig());
tasks.addLast(task);
}
}
......@@ -54,6 +57,21 @@ public class TaskQueue<T> {
}
}
public T dequeueByTask(DaemonTaskConfig task) {
synchronized (lock) {
T find = null;
for (T t : tasks) {
if (t.getConfig().equals(task)) {
find = t;
}
}
if (find != null) {
tasks.remove(find);
}
return find;
}
}
public int getTaskSize() {
synchronized (lock) {
return tasks.size();
......
......@@ -22,6 +22,7 @@ package org.dinky.daemon.pool;
import org.dinky.daemon.entity.TaskQueue;
import org.dinky.daemon.entity.TaskWorker;
import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig;
import java.util.ArrayList;
import java.util.Collections;
......@@ -70,6 +71,11 @@ public class DefaultThreadPool implements ThreadPool {
}
}
@Override
public DaemonTask dequeueByTask(DaemonTaskConfig daemonTask) {
return queue.dequeueByTask(daemonTask);
}
@Override
public void addWorkers(int num) {
synchronized (lock) {
......
......@@ -20,6 +20,7 @@
package org.dinky.daemon.pool;
import org.dinky.daemon.task.DaemonTask;
import org.dinky.daemon.task.DaemonTaskConfig;
/**
* @operate
......@@ -30,6 +31,8 @@ public interface ThreadPool {
// 执行任务
void execute(DaemonTask daemonTask);
DaemonTask dequeueByTask(DaemonTaskConfig daemonTask);
// 关闭连接池
void shutdown();
......
......@@ -49,6 +49,8 @@ public interface DaemonTask {
DaemonTask setConfig(DaemonTaskConfig config);
DaemonTaskConfig getConfig();
default boolean canHandle(String type) {
return Asserts.isEqualsIgnoreCase(getType(), type);
}
......
......@@ -19,6 +19,8 @@
package org.dinky.daemon.task;
import java.util.Objects;
import lombok.Getter;
@Getter
......@@ -35,4 +37,17 @@ public class DaemonTaskConfig {
public static DaemonTaskConfig build(String type, Integer id) {
return new DaemonTaskConfig(type, id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DaemonTaskConfig that = (DaemonTaskConfig) o;
return Objects.equals(type, that.type) && Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(type, id);
}
}
......@@ -36,4 +36,6 @@ public interface FlinkConstant {
String LOCAL_HOST = "localhost:8081";
/** changlog op */
String OP = "op";
String DEFAULT_FLINK_HOME = "/opt/flink";
}
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