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 { ...@@ -101,7 +101,7 @@ public class ProcessAspect {
ProcessStepType processStepType = processStep.type(); ProcessStepType processStepType = processStep.type();
ProcessStepEntity step = contextHolder.registerProcessStep(processStepType, MDC.get(PROCESS_NAME), parentStep); ProcessStepEntity step = contextHolder.registerProcessStep(processStepType, MDC.get(PROCESS_NAME), parentStep);
MDC.put(PROCESS_STEP, step.getKey()); 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 { try {
result = joinPoint.proceed(); result = joinPoint.proceed();
......
...@@ -70,7 +70,7 @@ public class ConsoleContextHolder { ...@@ -70,7 +70,7 @@ public class ConsoleContextHolder {
/** /**
* Get a list of all processes * Get a list of all processes
* */ */
public List<ProcessEntity> list() { public List<ProcessEntity> list() {
return new ArrayList<>(logPross.values()); return new ArrayList<>(logPross.values());
} }
...@@ -97,12 +97,14 @@ public class ConsoleContextHolder { ...@@ -97,12 +97,14 @@ public class ConsoleContextHolder {
* @param log messages * @param log messages
* @throws BusException Throws an exception if the process does not exist * @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)) { if (!logPross.containsKey(processName)) {
throw new BusException(StrFormatter.format("process {} does not exist", processName)); throw new BusException(StrFormatter.format("process {} does not exist", processName));
} }
ProcessEntity process = logPross.get(processName); ProcessEntity process = logPross.get(processName);
if (recordGlobal) {
process.appendLog(log); process.appendLog(log);
}
if (stepPid != null) { if (stepPid != null) {
ProcessStepEntity stepNode = getStepNode(stepPid, getStepsMap(processName)); ProcessStepEntity stepNode = getStepNode(stepPid, getStepsMap(processName));
stepNode.appendLog(log); stepNode.appendLog(log);
...@@ -136,7 +138,7 @@ public class ConsoleContextHolder { ...@@ -136,7 +138,7 @@ public class ConsoleContextHolder {
.children(new CopyOnWriteArrayList<>()) .children(new CopyOnWriteArrayList<>())
.build(); .build();
logPross.put(processName, entity); logPross.put(processName, entity);
appendLog(processName, null, "Start Process:" + processName); appendLog(processName, null, "Start Process:" + processName, true);
} }
/** /**
...@@ -180,7 +182,6 @@ public class ConsoleContextHolder { ...@@ -180,7 +182,6 @@ public class ConsoleContextHolder {
* @param processName process name * @param processName process name
* @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 void finishedProcess(String processName, ProcessStatus status, Throwable e) {
if (!logPross.containsKey(processName)) { if (!logPross.containsKey(processName)) {
...@@ -192,14 +193,14 @@ public class ConsoleContextHolder { ...@@ -192,14 +193,14 @@ public class ConsoleContextHolder {
process.setTime( process.setTime(
Duration.between(process.getStartTime(), process.getEndTime()).toMillis()); Duration.between(process.getStartTime(), process.getEndTime()).toMillis());
if (e != null) { 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()); String filePath = String.format("%s/tmp/log/%s.json", System.getProperty("user.dir"), process.getTitle());
if (FileUtil.exist(filePath)) { if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath)); Assert.isTrue(FileUtil.del(filePath));
} }
FileUtil.writeUtf8String(JSONObject.toJSONString(process), 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); logPross.remove(processName);
} }
...@@ -211,7 +212,7 @@ public class ConsoleContextHolder { ...@@ -211,7 +212,7 @@ public class ConsoleContextHolder {
* @param status Process step status * @param status Process step status
* @param e exception object, optional * @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)) { if (!logPross.containsKey(processName)) {
return; return;
} }
...@@ -219,12 +220,13 @@ public class ConsoleContextHolder { ...@@ -219,12 +220,13 @@ public class ConsoleContextHolder {
step.setEndTime(LocalDateTime.now()); step.setEndTime(LocalDateTime.now());
step.setTime(Duration.between(step.getStartTime(), step.getEndTime()).toMillis()); step.setTime(Duration.between(step.getStartTime(), step.getEndTime()).toMillis());
if (e != null) { if (e != null) {
appendLog(processName, step.getKey(), LogUtil.getError(e)); appendLog(processName, step.getKey(), LogUtil.getError(e.getCause()), false);
} }
appendLog( appendLog(
processName, processName,
step.getKey(), 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) { private ProcessStepEntity getStepNode(String stepPid, CopyOnWriteArrayList<ProcessStepEntity> stepsMap) {
...@@ -243,7 +245,7 @@ public class ConsoleContextHolder { ...@@ -243,7 +245,7 @@ public class ConsoleContextHolder {
/** /**
* 递归查找节点 * 递归查找节点
* */ */
private ProcessStepEntity findStepNode(String stepPid, CopyOnWriteArrayList<ProcessStepEntity> stepsMap) { private ProcessStepEntity findStepNode(String stepPid, CopyOnWriteArrayList<ProcessStepEntity> stepsMap) {
for (ProcessStepEntity processStepEntity : stepsMap) { for (ProcessStepEntity processStepEntity : stepsMap) {
if (processStepEntity.getKey().equals(stepPid)) { if (processStepEntity.getKey().equals(stepPid)) {
......
...@@ -228,9 +228,10 @@ public class JobRefreshHandler { ...@@ -228,9 +228,10 @@ public class JobRefreshHandler {
Gateway gateway = Gateway.build(gatewayConfig); Gateway gateway = Gateway.build(gatewayConfig);
return gateway.getJobStatusById(appId); return gateway.getJobStatusById(appId);
} catch (NotSupportGetStatusException ignored) { } 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(); JobDataDto jobDataDto = jobInfoDetail.getJobDataDto();
String status = jobDataDto.getJob().getState(); String status = jobDataDto.getJob().getState();
return JobStatus.get(status); return JobStatus.get(status);
......
...@@ -251,7 +251,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -251,7 +251,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
@Override @Override
@ProcessStep(type = ProcessStepType.SUBMIT_TASK)
public JobResult submitTask(Integer id, String savePointPath) throws Exception { public JobResult submitTask(Integer id, String savePointPath) throws Exception {
TaskDTO taskDTO = this.getTaskInfoById(id); TaskDTO taskDTO = this.getTaskInfoById(id);
...@@ -262,16 +261,11 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -262,16 +261,11 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
// 注解自调用会失效,这里通过获取对象方法绕过此限制 // 注解自调用会失效,这里通过获取对象方法绕过此限制
TaskServiceImpl taskServiceBean = applicationContext.getBean(TaskServiceImpl.class); TaskServiceImpl taskServiceBean = applicationContext.getBean(TaskServiceImpl.class);
JobResult jobResult = taskServiceBean.executeJob(taskDTO); JobResult jobResult = taskServiceBean.executeJob(taskDTO);
if (Job.JobStatus.SUCCESS == jobResult.getStatus()) {
log.info("Job Submit success"); log.info("Job Submit success");
Task task = new Task(id, jobResult.getJobInstanceId()); Task task = new Task(id, jobResult.getJobInstanceId());
if (!this.updateById(task)) { if (!this.updateById(task)) {
throw new BusException(Status.TASK_UPDATE_FAILED.getMessage()); throw new BusException(Status.TASK_UPDATE_FAILED.getMessage());
} }
} else {
log.error("Job Submit failed, error: " + jobResult.getError());
}
return jobResult; return jobResult;
} }
...@@ -426,6 +420,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -426,6 +420,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Integer tenantId = baseMapper.getTenantByTaskId(id); Integer tenantId = baseMapper.getTenantByTaskId(id);
Asserts.checkNull(tenantId, Status.TASK_NOT_EXIST.getMessage()); Asserts.checkNull(tenantId, Status.TASK_NOT_EXIST.getMessage());
TenantContextHolder.set(tenantId); TenantContextHolder.set(tenantId);
log.info("Init task tenan finished..");
} }
@Override @Override
......
...@@ -69,7 +69,7 @@ public class LogSseAppender extends AbstractAppender { ...@@ -69,7 +69,7 @@ public class LogSseAppender extends AbstractAppender {
String processName = contextData.getValue(ProcessAspect.PROCESS_NAME); String processName = contextData.getValue(ProcessAspect.PROCESS_NAME);
String processStepPid = contextData.getValue(ProcessAspect.PROCESS_STEP); String processStepPid = contextData.getValue(ProcessAspect.PROCESS_STEP);
String log = getStringLayout().toSerializable(event); 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; ...@@ -102,6 +102,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
...@@ -604,12 +605,13 @@ public class JobManager { ...@@ -604,12 +605,13 @@ public class JobManager {
success(); success();
} }
} catch (Exception e) { } 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.setEndTime(LocalDateTime.now());
job.setStatus(Job.JobStatus.FAILED); job.setStatus(Job.JobStatus.FAILED);
job.setError(error); job.setError(error);
failed(); failed();
throw e; throw new Exception(error, e);
} finally { } finally {
close(); close();
} }
......
...@@ -25,6 +25,7 @@ import org.dinky.gateway.config.GatewayConfig; ...@@ -25,6 +25,7 @@ import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.ActionType; import org.dinky.gateway.enums.ActionType;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.exception.GatewayException; import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.exception.NotSupportGetStatusException;
import org.dinky.gateway.model.JobInfo; import org.dinky.gateway.model.JobInfo;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
...@@ -172,7 +173,7 @@ public abstract class AbstractGateway implements Gateway { ...@@ -172,7 +173,7 @@ public abstract class AbstractGateway implements Gateway {
@Override @Override
public JobStatus getJobStatusById(String id) { public JobStatus getJobStatusById(String id) {
return JobStatus.UNKNOWN; throw new NotSupportGetStatusException(StrFormatter.format("{} is not support get status.", getType()));
} }
@Override @Override
......
...@@ -20,141 +20,215 @@ ...@@ -20,141 +20,215 @@
package org.dinky.gateway.kubernetes; package org.dinky.gateway.kubernetes;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.constant.NetConstant;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.gateway.config.AppConfig; import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult; 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.ClusterSpecification;
import org.apache.flink.client.deployment.application.ApplicationConfiguration; import org.apache.flink.client.deployment.application.ApplicationConfiguration;
import org.apache.flink.client.program.ClusterClient; import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.ClusterClientProvider; import org.apache.flink.client.program.ClusterClientProvider;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor; 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.flink.runtime.client.JobStatusMessage;
import org.apache.http.util.TextUtils;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; 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.text.StrFormatter;
import cn.hutool.core.thread.ThreadUtil; import io.fabric8.kubernetes.api.model.ContainerStatus;
import cn.hutool.core.util.StrUtil; import io.fabric8.kubernetes.api.model.Pod;
import cn.hutool.http.HttpUtil; import io.fabric8.kubernetes.api.model.apps.Deployment;
/** /**
* KubernetesApplicationGateway * KubernetesApplicationGateway
*
* @since 2021/12/26 14:59
*/ */
public class KubernetesApplicationGateway extends KubernetesGateway { public class KubernetesApplicationGateway extends KubernetesGateway {
/**
* @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION.
*/
@Override @Override
public GatewayType getType() { public GatewayType getType() {
return GatewayType.KUBERNETES_APPLICATION; return GatewayType.KUBERNETES_APPLICATION;
} }
/**
* Submits a jar file to the Kubernetes gateway.
*
* @throws RuntimeException if an error occurs during submission.
*/
@Override @Override
public GatewayResult submitJar() { 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)) { if (Asserts.isNull(client)) {
init(); init();
} }
// Build the commit information
AppConfig appConfig = config.getAppConfig(); AppConfig appConfig = config.getAppConfig();
String[] userJarParas = String[] userJarParas =
Asserts.isNotNull(appConfig.getUserJarParas()) ? appConfig.getUserJarParas() : new String[0]; Asserts.isNotNull(appConfig.getUserJarParas()) ? appConfig.getUserJarParas() : new String[0];
ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder = ClusterSpecification.ClusterSpecificationBuilder clusterSpecificationBuilder =
createClusterSpecificationBuilder(); createClusterSpecificationBuilder();
// Deploy to k8s
ApplicationConfiguration applicationConfiguration = ApplicationConfiguration applicationConfiguration =
new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass()); new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass());
KubernetesClusterDescriptor kubernetesClusterDescriptor =
KubernetesResult result = KubernetesResult.build(getType()); new KubernetesClusterDescriptor(configuration, client);
return kubernetesClusterDescriptor.deployApplicationCluster(
try (KubernetesClusterDescriptor kubernetesClusterDescriptor =
new KubernetesClusterDescriptor(configuration, client)) {
ClusterClientProvider<String> clusterClientProvider = kubernetesClusterDescriptor.deployApplicationCluster(
clusterSpecificationBuilder.createClusterSpecification(), applicationConfiguration); 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;
}
}
if (!jobStatusMessages.isEmpty()) {
break;
}
} }
// application mode only have one job, so we can get any one to be jobId /**
String jobId = ""; * Waits for the JobManager and the Job to start in Kubernetes.
if (!jobStatusMessages.isEmpty()) { *
List<String> jids = new ArrayList<>(); * @param deployment The deployment in Kubernetes.
for (JobStatusMessage jobStatusMessage : jobStatusMessages) { * @param clusterClient The ClusterClientProvider<String> object for accessing the Kubernetes cluster.
jobId = jobStatusMessage.getJobId().toHexString(); * @return A KubernetesResult object containing the Kubernetes gateway's Web URL, the Job ID, and the cluster ID.
jids.add(jobId); * @throws InterruptedException if waiting is interrupted.
*/
public KubernetesResult waitForJmAndJobStart(Deployment deployment, ClusterClientProvider<String> clusterClient)
throws InterruptedException {
KubernetesResult result = KubernetesResult.build(getType());
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;
} }
result.setJids(jids); 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();
// if JobStatusMessage not have job id, it`s maybe wrong with submit,throw exception JobStatus jobStatus = client.getJobStatus(job.getJobId()).get();
if (TextUtils.isEmpty(jobId)) { // To create a cluster ID, you need to combine the cluster ID with the jobID to ensure uniqueness
int cost = SystemConfiguration.getInstances().getJobIdWait() - counts; String cid = configuration.getString(KubernetesConfigOptions.CLUSTER_ID)
String clusterId = clusterClient.getClusterId(); + job.getJobId().toHexString();
throw new Exception( logger.info("Success get job status:{}", jobStatus);
StrFormatter.format("Unable to get JobID,wait time:{}, Job name:{}", cost, clusterId)); 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.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));
} }
return result; Thread.sleep(5000);
}
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 * Represents Java Bean properties for YAML serialization with LogRepresenter.
* If the property value is null, it is ignored.
*/
static class LogRepresenter extends Representer {
/**
* Represents the Java Bean property, ignoring null and empty values.
* *
* @param apiPath * @param javaBean The Java Bean object.
* @param jobId * @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.
*/ */
static void waitForTaskManagerToBeReady(String apiPath, String jobId) { @Override
int jobIdWait = SystemConfiguration.getInstances().getJobIdWait(); protected NodeTuple representJavaBeanProperty(
String fullPath = String.format("%s/jobs/%s", apiPath, jobId); Object javaBean, Property property, Object propertyValue, Tag tag) {
for (int i = 1; i <= jobIdWait; i++) { if (propertyValue == null) {
try { return null;
// 不抛异常,就为成功
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);
} }
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; ...@@ -47,6 +47,8 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
/** /**
* KubernetesGateway * KubernetesGateway
...@@ -55,6 +57,7 @@ import cn.hutool.core.util.ReflectUtil; ...@@ -55,6 +57,7 @@ import cn.hutool.core.util.ReflectUtil;
public abstract class KubernetesGateway extends AbstractGateway { public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkKubeClient client; protected FlinkKubeClient client;
protected KubernetesClient kubernetesClient;
public KubernetesGateway() {} public KubernetesGateway() {}
...@@ -108,6 +111,7 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -108,6 +111,7 @@ public abstract class KubernetesGateway extends AbstractGateway {
private void initKubeClient() { private void initKubeClient() {
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client"); client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
kubernetesClient = new DefaultKubernetesClient();
} }
public SavePointResult savepointCluster(String savePoint) { public SavePointResult savepointCluster(String savePoint) {
......
...@@ -30,7 +30,7 @@ public interface GatewayResult { ...@@ -30,7 +30,7 @@ public interface GatewayResult {
String getId(); String getId();
void setId(String id); GatewayResult setId(String id);
String getWebURL(); String getWebURL();
......
...@@ -26,12 +26,14 @@ import java.util.List; ...@@ -26,12 +26,14 @@ import java.util.List;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
/** /**
* KubernetesResult * KubernetesResult
* *
* @since 2021/12/26 15:06 * @since 2021/12/26 15:06
*/ */
@Getter
@ApiModel(value = "KubernetesResult", description = "Result of Kubernetes operation") @ApiModel(value = "KubernetesResult", description = "Result of Kubernetes operation")
public class KubernetesResult extends AbstractGatewayResult { public class KubernetesResult extends AbstractGatewayResult {
...@@ -60,28 +62,20 @@ public class KubernetesResult extends AbstractGatewayResult { ...@@ -60,28 +62,20 @@ public class KubernetesResult extends AbstractGatewayResult {
super(type, startTime); super(type, startTime);
} }
public KubernetesResult(
String clusterId, LocalDateTime startTime, LocalDateTime endTime, boolean isSuccess, String exceptionMsg) {
super(startTime, endTime, isSuccess, exceptionMsg);
this.clusterId = clusterId;
}
@Override @Override
public String getId() { public String getId() {
return clusterId; return clusterId;
} }
@Override @Override
public void setId(String id) { public KubernetesResult setId(String id) {
this.clusterId = id; this.clusterId = id;
return this;
} }
public void setWebURL(String webURL) { public KubernetesResult setWebURL(String webURL) {
this.webURL = webURL; this.webURL = webURL;
} return this;
public String getWebURL() {
return webURL;
} }
@Override @Override
...@@ -89,8 +83,9 @@ public class KubernetesResult extends AbstractGatewayResult { ...@@ -89,8 +83,9 @@ public class KubernetesResult extends AbstractGatewayResult {
return jids; return jids;
} }
public void setJids(List<String> jids) { public KubernetesResult setJids(List<String> jids) {
this.jids = jids; this.jids = jids;
return this;
} }
public static KubernetesResult build(GatewayType type) { public static KubernetesResult build(GatewayType type) {
......
...@@ -69,8 +69,9 @@ public class SavePointResult extends AbstractGatewayResult { ...@@ -69,8 +69,9 @@ public class SavePointResult extends AbstractGatewayResult {
} }
@Override @Override
public void setId(String id) { public GatewayResult setId(String id) {
this.appId = id; this.appId = id;
return this;
} }
@Override @Override
......
...@@ -71,8 +71,9 @@ public class YarnResult extends AbstractGatewayResult { ...@@ -71,8 +71,9 @@ public class YarnResult extends AbstractGatewayResult {
} }
@Override @Override
public void setId(String id) { public GatewayResult setId(String id) {
this.appId = id; this.appId = id;
return this;
} }
public String getWebURL() { 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