Unverified Commit 09aa5c0b authored by gaoyan's avatar gaoyan Committed by GitHub

Optimized the Kubernetes submission logic (#2484)

* Optimize the process * fix some bugs * Optimized the Kubernetes submission logic * close client after submit finish * fix some bug * fix some bug
parent 6d623f38
......@@ -101,7 +101,7 @@ public class ProcessAspect {
ProcessStepType processStepType = processStep.type();
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());
contextHolder.appendLog(processName, step.getKey(), "Start Process Step:" + step.getType(), true);
try {
result = joinPoint.proceed();
......
......@@ -70,7 +70,7 @@ public class ConsoleContextHolder {
/**
* Get a list of all processes
* */
*/
public List<ProcessEntity> list() {
return new ArrayList<>(logPross.values());
}
......@@ -93,16 +93,18 @@ public class ConsoleContextHolder {
* Add log messages to specific processes and process steps.
*
* @param processName process name
* @param stepPid process step type
* @param stepPid process step type
* @param log messages
* @throws BusException Throws an exception if the process does not exist
*/
public void appendLog(String processName, String stepPid, String log) {
public void appendLog(String processName, String stepPid, String log, boolean recordGlobal) {
if (!logPross.containsKey(processName)) {
throw new BusException(StrFormatter.format("process {} does not exist", processName));
}
ProcessEntity process = logPross.get(processName);
process.appendLog(log);
if (recordGlobal) {
process.appendLog(log);
}
if (stepPid != null) {
ProcessStepEntity stepNode = getStepNode(stepPid, getStepsMap(processName));
stepNode.appendLog(log);
......@@ -136,15 +138,15 @@ public class ConsoleContextHolder {
.children(new CopyOnWriteArrayList<>())
.build();
logPross.put(processName, entity);
appendLog(processName, null, "Start Process:" + processName);
appendLog(processName, null, "Start Process:" + processName, true);
}
/**
* Register a new process step.
*
* @param type process step type
* @param processName process name
* @param parentStepPid parent step
* @param type process step type
* @param processName process name
* @param parentStepPid parent step
* @throws RuntimeException Throws an exception if the process does not exist
*/
public ProcessStepEntity registerProcessStep(ProcessStepType type, String processName, String parentStepPid)
......@@ -180,7 +182,6 @@ public class ConsoleContextHolder {
* @param processName process name
* @param status Process status
* @param e exception object, optional
*
*/
public void finishedProcess(String processName, ProcessStatus status, Throwable e) {
if (!logPross.containsKey(processName)) {
......@@ -192,14 +193,14 @@ public class ConsoleContextHolder {
process.setTime(
Duration.between(process.getStartTime(), process.getEndTime()).toMillis());
if (e != null) {
appendLog(processName, null, LogUtil.getError(e));
appendLog(processName, null, LogUtil.getError(e.getCause()), true);
}
String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), process.getTitle());
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));
appendLog(processName, null, StrFormatter.format("Process {} exit with status:{}", processName, status), true);
logPross.remove(processName);
}
......@@ -211,7 +212,7 @@ public class ConsoleContextHolder {
* @param status Process step status
* @param e exception object, optional
*/
public void finishedStep(String processName, ProcessStepEntity step, ProcessStatus status, Throwable e) {
public void finishedStep(String processName, ProcessStepEntity step, ProcessStatus status, Exception e) {
if (!logPross.containsKey(processName)) {
return;
}
......@@ -219,12 +220,13 @@ public class ConsoleContextHolder {
step.setEndTime(LocalDateTime.now());
step.setTime(Duration.between(step.getStartTime(), step.getEndTime()).toMillis());
if (e != null) {
appendLog(processName, step.getKey(), LogUtil.getError(e));
appendLog(processName, step.getKey(), LogUtil.getError(e.getCause()), false);
}
appendLog(
processName,
step.getKey(),
StrFormatter.format("Process Step {} exit with status:{}", step.getType(), status));
StrFormatter.format("Process Step {} exit with status:{}", step.getType(), status),
true);
}
private ProcessStepEntity getStepNode(String stepPid, CopyOnWriteArrayList<ProcessStepEntity> stepsMap) {
......@@ -243,7 +245,7 @@ public class ConsoleContextHolder {
/**
* 递归查找节点
* */
*/
private ProcessStepEntity findStepNode(String stepPid, CopyOnWriteArrayList<ProcessStepEntity> stepsMap) {
for (ProcessStepEntity processStepEntity : stepsMap) {
if (processStepEntity.getKey().equals(stepPid)) {
......
......@@ -228,9 +228,10 @@ public class JobRefreshHandler {
Gateway gateway = Gateway.build(gatewayConfig);
return gateway.getJobStatusById(appId);
} catch (NotSupportGetStatusException ignored) {
// if the gateway does not support get status, then use the api to get job status
// ignore to do something here
}
}
JobDataDto jobDataDto = jobInfoDetail.getJobDataDto();
String status = jobDataDto.getJob().getState();
return JobStatus.get(status);
......
......@@ -251,7 +251,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
}
@Override
@ProcessStep(type = ProcessStepType.SUBMIT_TASK)
public JobResult submitTask(Integer id, String savePointPath) throws Exception {
TaskDTO taskDTO = this.getTaskInfoById(id);
......@@ -262,15 +261,10 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
// 注解自调用会失效,这里通过获取对象方法绕过此限制
TaskServiceImpl taskServiceBean = applicationContext.getBean(TaskServiceImpl.class);
JobResult jobResult = taskServiceBean.executeJob(taskDTO);
if (Job.JobStatus.SUCCESS == jobResult.getStatus()) {
log.info("Job Submit success");
Task task = new Task(id, jobResult.getJobInstanceId());
if (!this.updateById(task)) {
throw new BusException(Status.TASK_UPDATE_FAILED.getMessage());
}
} else {
log.error("Job Submit failed, error: " + jobResult.getError());
log.info("Job Submit success");
Task task = new Task(id, jobResult.getJobInstanceId());
if (!this.updateById(task)) {
throw new BusException(Status.TASK_UPDATE_FAILED.getMessage());
}
return jobResult;
}
......@@ -426,6 +420,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Integer tenantId = baseMapper.getTenantByTaskId(id);
Asserts.checkNull(tenantId, Status.TASK_NOT_EXIST.getMessage());
TenantContextHolder.set(tenantId);
log.info("Init task tenan finished..");
}
@Override
......
......@@ -69,7 +69,7 @@ public class LogSseAppender extends AbstractAppender {
String processName = contextData.getValue(ProcessAspect.PROCESS_NAME);
String processStepPid = contextData.getValue(ProcessAspect.PROCESS_STEP);
String log = getStringLayout().toSerializable(event);
ConsoleContextHolder.getInstances().appendLog(processName, processStepPid, log);
ConsoleContextHolder.getInstances().appendLog(processName, processStepPid, log, true);
}
}
......
......@@ -102,6 +102,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
......@@ -604,12 +605,13 @@ public class JobManager {
success();
}
} catch (Exception e) {
String error = LogUtil.getError("Exception in executing FlinkSQL:\n" + addLineNumber(currentSql), e);
String error = StrFormatter.format(
"Exception in executing FlinkSQL:\n{}\n{}", addLineNumber(currentSql), e.getMessage());
job.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED);
job.setError(error);
failed();
throw e;
throw new Exception(error, e);
} finally {
close();
}
......
......@@ -25,6 +25,7 @@ import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.ActionType;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.exception.NotSupportGetStatusException;
import org.dinky.gateway.model.JobInfo;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.SavePointResult;
......@@ -172,7 +173,7 @@ public abstract class AbstractGateway implements Gateway {
@Override
public JobStatus getJobStatusById(String id) {
return JobStatus.UNKNOWN;
throw new NotSupportGetStatusException(StrFormatter.format("{} is not support get status.", getType()));
}
@Override
......
......@@ -20,141 +20,215 @@
package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts;
import org.dinky.data.constant.NetConstant;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult;
import org.dinky.utils.LogUtil;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.client.deployment.ClusterDeploymentException;
import org.apache.flink.client.deployment.ClusterSpecification;
import org.apache.flink.client.deployment.application.ApplicationConfiguration;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ClusterClientProvider;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.utils.Constants;
import org.apache.flink.runtime.client.JobStatusMessage;
import org.apache.http.util.TextUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.apps.Deployment;
/**
* KubernetesApplicationGateway
*
* @since 2021/12/26 14:59
*/
public class KubernetesApplicationGateway extends KubernetesGateway {
/**
* @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION.
*/
@Override
public GatewayType getType() {
return GatewayType.KUBERNETES_APPLICATION;
}
/**
* Submits a jar file to the Kubernetes gateway.
*
* @throws RuntimeException if an error occurs during submission.
*/
@Override
public GatewayResult submitJar() {
try {
logger.info("Start submit k8s application.");
ClusterClientProvider<String> clusterClient = deployApplication();
Deployment deployment = kubernetesClient
.apps()
.deployments()
.inNamespace(configuration.getString(KubernetesConfigOptions.NAMESPACE))
.withName(configuration.getString(KubernetesConfigOptions.CLUSTER_ID))
.get();
KubernetesResult kubernetesResult = waitForJmAndJobStart(deployment, clusterClient);
kubernetesResult.success();
return kubernetesResult;
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
client.close();
kubernetesClient.close();
}
}
/**
* Checks the status of a Pod in Kubernetes.
*
* @param pod The Pod to check the status of.
* @return True if the Pod is ready, false otherwise.
* @throws GatewayException if the Pod has restarted or terminated.
*/
public boolean checkPodStatus(Pod pod) {
// Get the Flink container status.
Optional<ContainerStatus> flinContainer = pod.getStatus().getContainerStatuses().stream()
.filter(s -> s.getName().equals(Constants.MAIN_CONTAINER_NAME))
.findFirst();
ContainerStatus containerStatus =
flinContainer.orElseThrow(() -> new GatewayException("Deploy k8s failed, can't find flink container"));
Yaml yaml = new Yaml(new LogRepresenter());
String logStr = StrFormatter.format(
"Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n"
+ "------CurrentState------\n{}\n------LastState------\n{}",
pod.getMetadata().getName(),
containerStatus.getReady(),
containerStatus.getRestartCount(),
containerStatus.getImage(),
yaml.dumpAsMap(containerStatus.getState()),
yaml.dumpAsMap(containerStatus.getLastState()));
logger.info(logStr);
if (containerStatus.getRestartCount() > 0 || containerStatus.getState().getTerminated() != null) {
throw new GatewayException("Deploy k8s failed, pod have restart or terminated");
}
return containerStatus.getReady();
}
/**
* Deploys an application to Kubernetes.
*
* @return A ClusterClientProvider<String> object for accessing the Kubernetes cluster.
* @throws ClusterDeploymentException if deployment to Kubernetes fails.
*/
public ClusterClientProvider<String> deployApplication() throws ClusterDeploymentException {
if (Asserts.isNull(client)) {
init();
}
// Build the commit information
AppConfig appConfig = config.getAppConfig();
String[] userJarParas =
Asserts.isNotNull(appConfig.getUserJarParas()) ? appConfig.getUserJarParas() : new String[0];
ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder =
createClusterSpecificationBuilder();
// Deploy to k8s
ApplicationConfiguration applicationConfiguration =
new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass());
KubernetesClusterDescriptor kubernetesClusterDescriptor =
new KubernetesClusterDescriptor(configuration, client);
return kubernetesClusterDescriptor.deployApplicationCluster(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration);
}
/**
* Waits for the JobManager and the Job to start in Kubernetes.
*
* @param deployment The deployment in Kubernetes.
* @param clusterClient The ClusterClientProvider<String> object for accessing the Kubernetes cluster.
* @return A KubernetesResult object containing the Kubernetes gateway's Web URL, the Job ID, and the cluster ID.
* @throws InterruptedException if waiting is interrupted.
*/
public KubernetesResult waitForJmAndJobStart(Deployment deployment, ClusterClientProvider<String> clusterClient)
throws InterruptedException {
KubernetesResult result = KubernetesResult.build(getType());
try (KubernetesClusterDescriptor kubernetesClusterDescriptor =
new KubernetesClusterDescriptor(configuration, client)) {
ClusterClientProvider<String> clusterClientProvider = kubernetesClusterDescriptor.deployApplicationCluster(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration);
ClusterClient<String> clusterClient = clusterClientProvider.getClusterClient();
Collection<JobStatusMessage> jobStatusMessages =
clusterClient.listJobs().get();
int counts = SystemConfiguration.getInstances().getJobIdWait();
while (jobStatusMessages.isEmpty() && counts > 0) {
Thread.sleep(1000);
counts--;
try {
jobStatusMessages = clusterClient.listJobs().get();
logger.info("Get K8s Job list: {}", jobStatusMessages);
} catch (ExecutionException e) {
logger.error("Get Job list Error: {}", e.getMessage());
if (StrUtil.contains(e.getMessage(), "Number of retries has been exhausted.")) {
// refresh the job manager ip address
clusterClient.close();
clusterClient = clusterClientProvider.getClusterClient();
} else {
throw e;
}
long waitSends = SystemConfiguration.getInstances().getJobIdWait() * 1000L;
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime < waitSends) {
List<Pod> pods = kubernetesClient
.pods()
.inNamespace(deployment.getMetadata().getNamespace())
.withLabelSelector(deployment.getSpec().getSelector())
.list()
.getItems();
for (Pod pod : pods) {
if (!checkPodStatus(pod)) {
logger.info("Kubernetes Pod have not ready, reTry at 5 sec later");
continue;
}
if (!jobStatusMessages.isEmpty()) {
break;
}
}
// application mode only have one job, so we can get any one to be jobId
String jobId = "";
if (!jobStatusMessages.isEmpty()) {
List<String> jids = new ArrayList<>();
for (JobStatusMessage jobStatusMessage : jobStatusMessages) {
jobId = jobStatusMessage.getJobId().toHexString();
jids.add(jobId);
try (ClusterClient<String> client = clusterClient.getClusterClient()) {
logger.info("Start get job list ....");
Collection<JobStatusMessage> jobList = client.listJobs().get(15, TimeUnit.SECONDS);
logger.info("Get K8S Job list: {}", jobList);
if (jobList.isEmpty()) {
logger.error("Get job is empty, will be reconnect later....");
continue;
}
JobStatusMessage job = jobList.stream().findFirst().get();
JobStatus jobStatus = client.getJobStatus(job.getJobId()).get();
// To create a cluster ID, you need to combine the cluster ID with the jobID to ensure uniqueness
String cid = configuration.getString(KubernetesConfigOptions.CLUSTER_ID)
+ job.getJobId().toHexString();
logger.info("Success get job status:{}", jobStatus);
return result.setWebURL(client.getWebInterfaceURL())
.setJids(Collections.singletonList(job.getJobId().toHexString()))
.setId(cid);
} catch (GatewayException e) {
throw e;
} catch (Exception ex) {
logger.error("Get job status failed,{}", ex.getMessage());
}
result.setJids(jids);
}
// if JobStatusMessage not have job id, it`s maybe wrong with submit,throw exception
if (TextUtils.isEmpty(jobId)) {
int cost = SystemConfiguration.getInstances().getJobIdWait() - counts;
String clusterId = clusterClient.getClusterId();
throw new Exception(
StrFormatter.format("Unable to get JobID,wait time:{}, Job name:{}", cost, clusterId));
}
result.setId(jobId);
result.setWebURL(clusterClient.getWebInterfaceURL());
waitForTaskManagerToBeReady(result.getWebURL(), jobId);
result.success();
} catch (Exception e) {
logger.error("submit K8s Application error", e);
result.fail(LogUtil.getError(e));
Thread.sleep(5000);
}
return result;
throw new GatewayException(
"The number of retries exceeds the limit, check the K8S cluster for more information");
}
/**
* Waiting for TaskManager to successfully start,if skip this step, may obtain an NullPointerException in the next step
*
* @param apiPath
* @param jobId
* Represents Java Bean properties for YAML serialization with LogRepresenter.
* If the property value is null, it is ignored.
*/
static void waitForTaskManagerToBeReady(String apiPath, String jobId) {
int jobIdWait = SystemConfiguration.getInstances().getJobIdWait();
String fullPath = String.format("%s/jobs/%s", apiPath, jobId);
for (int i = 1; i <= jobIdWait; i++) {
try {
// 不抛异常,就为成功
String result = HttpUtil.get(fullPath, NetConstant.SERVER_TIME_OUT_ACTIVE);
logger.info("get job status success,jobPath:{},result: {}", fullPath, result);
return;
} catch (Exception e) {
logger.info("Unable to connect to Flink JobManager: {},wait count:{}", fullPath, i);
ThreadUtil.sleep(1000);
static class LogRepresenter extends Representer {
/**
* Represents the Java Bean property, ignoring null and empty values.
*
* @param javaBean The Java Bean object.
* @param property The property to represent.
* @param propertyValue The value of the property.
* @param tag The custom tag.
* @return The represented node tuple, or null if the property value is null.
*/
@Override
protected NodeTuple representJavaBeanProperty(
Object javaBean, Property property, Object propertyValue, Tag tag) {
if (propertyValue == null) {
return null;
}
return super.representJavaBeanProperty(javaBean, property, propertyValue, tag);
}
logger.error("wait for taskManager to be ready timeout,path=" + fullPath);
}
}
......@@ -47,6 +47,8 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ReflectUtil;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
/**
* KubernetesGateway
......@@ -55,6 +57,7 @@ import cn.hutool.core.util.ReflectUtil;
public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkKubeClient client;
protected KubernetesClient kubernetesClient;
public KubernetesGateway() {}
......@@ -108,6 +111,7 @@ public abstract class KubernetesGateway extends AbstractGateway {
private void initKubeClient() {
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
kubernetesClient = new DefaultKubernetesClient();
}
public SavePointResult savepointCluster(String savePoint) {
......
......@@ -30,7 +30,7 @@ public interface GatewayResult {
String getId();
void setId(String id);
GatewayResult setId(String id);
String getWebURL();
......
......@@ -26,12 +26,14 @@ import java.util.List;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
/**
* KubernetesResult
*
* @since 2021/12/26 15:06
*/
@Getter
@ApiModel(value = "KubernetesResult", description = "Result of Kubernetes operation")
public class KubernetesResult extends AbstractGatewayResult {
......@@ -60,28 +62,20 @@ public class KubernetesResult extends AbstractGatewayResult {
super(type, startTime);
}
public KubernetesResult(
String clusterId, LocalDateTime startTime, LocalDateTime endTime, boolean isSuccess, String exceptionMsg) {
super(startTime, endTime, isSuccess, exceptionMsg);
this.clusterId = clusterId;
}
@Override
public String getId() {
return clusterId;
}
@Override
public void setId(String id) {
public KubernetesResult setId(String id) {
this.clusterId = id;
return this;
}
public void setWebURL(String webURL) {
public KubernetesResult setWebURL(String webURL) {
this.webURL = webURL;
}
public String getWebURL() {
return webURL;
return this;
}
@Override
......@@ -89,8 +83,9 @@ public class KubernetesResult extends AbstractGatewayResult {
return jids;
}
public void setJids(List<String> jids) {
public KubernetesResult setJids(List<String> jids) {
this.jids = jids;
return this;
}
public static KubernetesResult build(GatewayType type) {
......
......@@ -69,8 +69,9 @@ public class SavePointResult extends AbstractGatewayResult {
}
@Override
public void setId(String id) {
public GatewayResult setId(String id) {
this.appId = id;
return this;
}
@Override
......
......@@ -71,8 +71,9 @@ public class YarnResult extends AbstractGatewayResult {
}
@Override
public void setId(String id) {
public GatewayResult setId(String id) {
this.appId = id;
return this;
}
public String getWebURL() {
......
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