Unverified Commit 58afc08b authored by gaoyan's avatar gaoyan Committed by GitHub

[Bug] Fix k8s pod template not decorate bug (#3350)

parent d4e8a5ef
...@@ -172,8 +172,12 @@ public class JobRefreshHandler { ...@@ -172,8 +172,12 @@ public class JobRefreshHandler {
} }
if (isDone) { if (isDone) {
try {
log.debug("Job is done: {}->{}", jobInstance.getId(), jobInstance.getName()); log.debug("Job is done: {}->{}", jobInstance.getId(), jobInstance.getName());
handleJobDone(jobInfoDetail); handleJobDone(jobInfoDetail);
} catch (Exception e) {
log.error("failed handel job done:", e);
}
} }
return isDone; return isDone;
} }
......
...@@ -28,7 +28,6 @@ import org.dinky.gateway.exception.GatewayException; ...@@ -28,7 +28,6 @@ import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.IgnoreNullRepresenter; import org.dinky.gateway.kubernetes.utils.IgnoreNullRepresenter;
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.TextUtil;
import org.apache.flink.api.common.JobStatus; import org.apache.flink.api.common.JobStatus;
import org.apache.flink.client.deployment.ClusterDeploymentException; import org.apache.flink.client.deployment.ClusterDeploymentException;
...@@ -36,7 +35,6 @@ import org.apache.flink.client.deployment.ClusterSpecification; ...@@ -36,7 +35,6 @@ 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.configuration.ConfigOption;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor; import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions; import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient; import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
...@@ -47,16 +45,10 @@ import java.util.Collection; ...@@ -47,16 +45,10 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.text.StrFormatter; import cn.hutool.core.text.StrFormatter;
import io.fabric8.kubernetes.api.model.ContainerStatus; import io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.api.model.Pod;
...@@ -70,9 +62,6 @@ import lombok.extern.slf4j.Slf4j; ...@@ -70,9 +62,6 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class KubernetesApplicationGateway extends KubernetesGateway { public class KubernetesApplicationGateway extends KubernetesGateway {
private final String tmpConfDir =
String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
/** /**
* @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION. * @return The type of the Kubernetes gateway, which is GatewayType.KUBERNETES_APPLICATION.
*/ */
...@@ -81,24 +70,6 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -81,24 +70,6 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
return GatewayType.KUBERNETES_APPLICATION; return GatewayType.KUBERNETES_APPLICATION;
} }
@Override
public void init() {
super.init();
Pod decoratedPodTemplate = getK8sClientHelper().decoratePodTemplate(config.getSql());
// use snakyaml to serialize the pod
Representer representer = new IgnoreNullRepresenter();
// set the label of the Map type, only the map type will not print the class name when dumping
representer.addClassTag(Pod.class, Tag.MAP);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(representer, options);
preparPodTemplate(yaml.dump(decoratedPodTemplate), KubernetesConfigOptions.KUBERNETES_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getJmPodTemplate(), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getTmPodTemplate(), KubernetesConfigOptions.TASK_MANAGER_POD_TEMPLATE);
preparPodTemplate(k8sConfig.getKubeConfig(), KubernetesConfigOptions.KUBE_CONFIG_FILE);
}
/** /**
* Submits a jar file to the Kubernetes gateway. * Submits a jar file to the Kubernetes gateway.
* *
...@@ -137,9 +108,10 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -137,9 +108,10 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
Optional<ContainerStatus> flinContainer = pod.getStatus().getContainerStatuses().stream() Optional<ContainerStatus> flinContainer = pod.getStatus().getContainerStatuses().stream()
.filter(s -> s.getName().equals(Constants.MAIN_CONTAINER_NAME)) .filter(s -> s.getName().equals(Constants.MAIN_CONTAINER_NAME))
.findFirst(); .findFirst();
ContainerStatus containerStatus = if (!flinContainer.isPresent()) {
flinContainer.orElseThrow(() -> new GatewayException("Deploy k8s failed, can't find flink container")); return false;
}
ContainerStatus containerStatus = flinContainer.get();
Yaml yaml = new Yaml(new IgnoreNullRepresenter()); Yaml yaml = new Yaml(new IgnoreNullRepresenter());
String logStr = StrFormatter.format( String logStr = StrFormatter.format(
"Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n" "Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n"
...@@ -235,20 +207,4 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -235,20 +207,4 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
throw new GatewayException( throw new GatewayException(
"The number of retries exceeds the limit, check the K8S cluster for more information"); "The number of retries exceeds the limit, check the K8S cluster for more information");
} }
private void preparPodTemplate(String podTemplate, ConfigOption<String> option) {
if (!TextUtil.isEmpty(podTemplate)) {
String filePath = String.format("%s/%s.yaml", tmpConfDir, option.key());
if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath));
}
FileUtil.writeUtf8String(podTemplate, filePath);
addConfigParas(option, filePath);
}
}
public boolean close() {
super.close();
return FileUtil.del(tmpConfDir);
}
} }
...@@ -28,7 +28,9 @@ import org.dinky.gateway.exception.GatewayException; ...@@ -28,7 +28,9 @@ import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.K8sClientHelper; import org.dinky.gateway.kubernetes.utils.K8sClientHelper;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.DeploymentOptions; import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.GlobalConfiguration;
...@@ -44,8 +46,11 @@ import java.lang.reflect.Method; ...@@ -44,8 +46,11 @@ import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import java.util.UUID; import java.util.UUID;
import cn.hutool.core.io.FileUtil;
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.api.model.Pod;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -62,7 +67,12 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -62,7 +67,12 @@ public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkConfig flinkConfig; protected FlinkConfig flinkConfig;
protected K8sConfig k8sConfig; protected K8sConfig k8sConfig;
private Pod jmPodTemplate;
private Pod tmPodTemplate;
private Pod defaultPodTemplate;
private K8sClientHelper k8sClientHelper; private K8sClientHelper k8sClientHelper;
private String tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
public KubernetesGateway() {} public KubernetesGateway() {}
...@@ -97,7 +107,35 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -97,7 +107,35 @@ public abstract class KubernetesGateway extends AbstractGateway {
resetCheckpointInApplicationMode(flinkConfig.getJobName()); resetCheckpointInApplicationMode(flinkConfig.getJobName());
} }
k8sClientHelper = new K8sClientHelper(configuration, k8sConfig); preparPodTemplate(k8sConfig.getKubeConfig(), KubernetesConfigOptions.KUBE_CONFIG_FILE);
k8sClientHelper = new K8sClientHelper(configuration, k8sConfig.getKubeConfig());
String sql = config.getSql();
defaultPodTemplate = k8sClientHelper.decoratePodTemplate(sql, k8sConfig.getPodTemplate());
preparPodTemplate(
k8sClientHelper.dumpPod2Str(defaultPodTemplate), KubernetesConfigOptions.KUBERNETES_POD_TEMPLATE);
if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) {
jmPodTemplate = k8sClientHelper.decoratePodTemplate(sql, k8sConfig.getJmPodTemplate());
preparPodTemplate(
k8sClientHelper.dumpPod2Str(jmPodTemplate), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
}
if (!TextUtil.isEmpty(k8sConfig.getTmPodTemplate())) {
tmPodTemplate = k8sClientHelper.decoratePodTemplate(sql, k8sConfig.getJmPodTemplate());
preparPodTemplate(
k8sClientHelper.dumpPod2Str(tmPodTemplate), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
}
}
protected void preparPodTemplate(String podTemplate, ConfigOption<String> option) {
if (!TextUtil.isEmpty(podTemplate)) {
String filePath = String.format("%s/%s.yaml", tmpConfDir, option.key());
if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath));
}
FileUtil.writeUtf8String(podTemplate, filePath);
addConfigParas(option, filePath);
}
} }
public SavePointResult savepointCluster(String savePoint) { public SavePointResult savepointCluster(String savePoint) {
...@@ -184,6 +222,11 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -184,6 +222,11 @@ public abstract class KubernetesGateway extends AbstractGateway {
} }
public boolean close() { public boolean close() {
try {
FileUtil.del(tmpConfDir);
} catch (Exception e) {
log.warn(e.getMessage());
}
if (k8sClientHelper != null) { if (k8sClientHelper != null) {
return k8sClientHelper.close(); return k8sClientHelper.close();
} }
......
...@@ -30,14 +30,10 @@ import org.dinky.gateway.kubernetes.operator.api.FlinkDeploymentSpec; ...@@ -30,14 +30,10 @@ import org.dinky.gateway.kubernetes.operator.api.FlinkDeploymentSpec;
import org.dinky.gateway.kubernetes.operator.api.JobSpec; import org.dinky.gateway.kubernetes.operator.api.JobSpec;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions; import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
...@@ -45,8 +41,6 @@ import org.slf4j.Logger; ...@@ -45,8 +41,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
...@@ -67,7 +61,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway { ...@@ -67,7 +61,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
initBase(); initBase();
initMetadata(); initMetadata();
initSpec(); initSpec();
initResource(getK8sClientHelper().getKubernetesClient()); initResource();
initJob(); initJob();
} }
...@@ -143,8 +137,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway { ...@@ -143,8 +137,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
flinkDeploymentSpec.setJob(jobSpecBuilder.build()); flinkDeploymentSpec.setJob(jobSpecBuilder.build());
} }
private void initResource(KubernetesClient kubernetesClient) { private void initResource() {
Pod defaultPod;
AbstractPodSpec jobManagerSpec = new AbstractPodSpec(); AbstractPodSpec jobManagerSpec = new AbstractPodSpec();
AbstractPodSpec taskManagerSpec = new AbstractPodSpec(); AbstractPodSpec taskManagerSpec = new AbstractPodSpec();
String jbcpu = kubernetsConfiguration.getOrDefault("kubernetes.jobmanager.cpu", "1"); String jbcpu = kubernetsConfiguration.getOrDefault("kubernetes.jobmanager.cpu", "1");
...@@ -157,21 +150,9 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway { ...@@ -157,21 +150,9 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem); logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem);
taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem)); taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem));
defaultPod = getK8sClientHelper().decoratePodTemplate(config.getSql()); flinkDeploymentSpec.setPodTemplate(getDefaultPodTemplate());
flinkDeploymentSpec.setPodTemplate(defaultPod); jobManagerSpec.setPodTemplate(getJmPodTemplate());
taskManagerSpec.setPodTemplate(getTmPodTemplate());
if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) {
InputStream inputStream =
new ByteArrayInputStream(k8sConfig.getJmPodTemplate().getBytes(StandardCharsets.UTF_8));
Pod pod = kubernetesClient.pods().load(inputStream).get();
jobManagerSpec.setPodTemplate(pod);
}
if (!TextUtil.isEmpty(k8sConfig.getTmPodTemplate())) {
InputStream inputStream =
new ByteArrayInputStream(k8sConfig.getTmPodTemplate().getBytes(StandardCharsets.UTF_8));
Pod pod = kubernetesClient.pods().load(inputStream).get();
taskManagerSpec.setPodTemplate(pod);
}
flinkDeploymentSpec.setJobManager(jobManagerSpec); flinkDeploymentSpec.setJobManager(jobManagerSpec);
flinkDeploymentSpec.setTaskManager(taskManagerSpec); flinkDeploymentSpec.setTaskManager(taskManagerSpec);
} }
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
package org.dinky.gateway.kubernetes.utils; package org.dinky.gateway.kubernetes.utils;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.kubernetes.decorate.DinkySqlConfigMapDecorate; import org.dinky.gateway.kubernetes.decorate.DinkySqlConfigMapDecorate;
import org.dinky.utils.TextUtil; import org.dinky.utils.TextUtil;
...@@ -34,9 +33,12 @@ import java.io.InputStream; ...@@ -34,9 +33,12 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID;
import cn.hutool.core.io.FileUtil; import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.OwnerReference; import io.fabric8.kubernetes.api.model.OwnerReference;
import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder; import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder;
...@@ -59,28 +61,24 @@ public class K8sClientHelper { ...@@ -59,28 +61,24 @@ public class K8sClientHelper {
private FlinkKubeClient client; private FlinkKubeClient client;
private KubernetesClient kubernetesClient; private KubernetesClient kubernetesClient;
protected Configuration configuration; protected Configuration configuration;
private K8sConfig k8sConfig;
private String tmpConfDir;
private DinkySqlConfigMapDecorate sqlFileDecorate; private DinkySqlConfigMapDecorate sqlFileDecorate;
public K8sClientHelper(Configuration configuration, K8sConfig k8sConfig) { public K8sClientHelper(Configuration configuration, String kubeConfig) {
this.configuration = configuration; this.configuration = configuration;
this.k8sConfig = k8sConfig; initKubeClient(kubeConfig);
tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
initKubeClient();
} }
/** /**
* initKubeClient * initKubeClient
*/ */
private void initKubeClient() { private void initKubeClient(String kubeConfig) {
// k8s flink native client // k8s flink native client
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client"); client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
// k8s fabric client // k8s fabric client
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) { if (TextUtils.isEmpty(kubeConfig)) {
kubernetesClient = new DefaultKubernetesClient(); kubernetesClient = new DefaultKubernetesClient();
} else { } else {
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(k8sConfig.getKubeConfig())); kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(kubeConfig));
} }
} }
...@@ -123,22 +121,41 @@ public class K8sClientHelper { ...@@ -123,22 +121,41 @@ public class K8sClientHelper {
* @param sqlStatement * @param sqlStatement
* @return * @return
*/ */
public Pod decoratePodTemplate(String sqlStatement) { public Pod decoratePodTemplate(String sqlStatement, String podTemplate) {
Pod pod; Pod pod;
// if the user has configured the pod template, combine user's configuration // if the user has configured the pod template, combine user's configuration
if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) { if (!TextUtil.isEmpty(podTemplate)) {
InputStream is = new ByteArrayInputStream(k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8)); InputStream is = new ByteArrayInputStream(podTemplate.getBytes(StandardCharsets.UTF_8));
pod = kubernetesClient.pods().load(is).get(); pod = kubernetesClient.pods().load(is).get();
} else { } else {
// if the user has not configured the pod template, use the default configuration // if the user has not configured the pod template, use the default configuration
pod = new Pod(); pod = new Pod();
} }
if (TextUtil.isEmpty(sqlStatement)) {
log.warn("Sql statement is Empty !!!!, will not decorate podTemplate");
return pod;
} else {
// decorate the pod template // decorate the pod template
sqlFileDecorate = new DinkySqlConfigMapDecorate(configuration, pod, sqlStatement); sqlFileDecorate = new DinkySqlConfigMapDecorate(configuration, pod, sqlStatement);
return sqlFileDecorate.decoratePodMount(); return sqlFileDecorate.decoratePodMount();
} }
}
/**
* dumpPod2Str
*
* */
public String dumpPod2Str(Pod pod) {
// use snakyaml to serialize the pod
Representer representer = new IgnoreNullRepresenter();
// set the label of the Map type, only the map type will not print the class name when dumping
representer.addClassTag(Pod.class, Tag.MAP);
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(representer, options);
return yaml.dump(pod);
}
/** /**
* close * close
* delete the temporary directory and close the client * delete the temporary directory and close the client
...@@ -151,11 +168,6 @@ public class K8sClientHelper { ...@@ -151,11 +168,6 @@ public class K8sClientHelper {
if (kubernetesClient != null) { if (kubernetesClient != null) {
kubernetesClient.close(); kubernetesClient.close();
} }
try { return true;
return FileUtil.del(tmpConfDir);
} catch (Exception e) {
log.warn("failed delete kubernetes temp dir: " + tmpConfDir);
}
return false;
} }
} }
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