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 {
}
if (isDone) {
log.debug("Job is done: {}->{}", jobInstance.getId(), jobInstance.getName());
handleJobDone(jobInfoDetail);
try {
log.debug("Job is done: {}->{}", jobInstance.getId(), jobInstance.getName());
handleJobDone(jobInfoDetail);
} catch (Exception e) {
log.error("failed handel job done:", e);
}
}
return isDone;
}
......
......@@ -28,7 +28,6 @@ import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.kubernetes.utils.IgnoreNullRepresenter;
import org.dinky.gateway.result.GatewayResult;
import org.dinky.gateway.result.KubernetesResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.api.common.JobStatus;
import org.apache.flink.client.deployment.ClusterDeploymentException;
......@@ -36,7 +35,6 @@ 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.configuration.ConfigOption;
import org.apache.flink.kubernetes.KubernetesClusterDescriptor;
import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
......@@ -47,16 +45,10 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.yaml.snakeyaml.DumperOptions;
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 io.fabric8.kubernetes.api.model.ContainerStatus;
import io.fabric8.kubernetes.api.model.Pod;
......@@ -70,9 +62,6 @@ import lombok.extern.slf4j.Slf4j;
@Slf4j
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.
*/
......@@ -81,24 +70,6 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
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.
*
......@@ -137,9 +108,10 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
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"));
if (!flinContainer.isPresent()) {
return false;
}
ContainerStatus containerStatus = flinContainer.get();
Yaml yaml = new Yaml(new IgnoreNullRepresenter());
String logStr = StrFormatter.format(
"Got Flink Container State:\nPod: {},\tReady: {},\trestartCount: {},\timage: {}\n"
......@@ -235,20 +207,4 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
throw new GatewayException(
"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;
import org.dinky.gateway.kubernetes.utils.K8sClientHelper;
import org.dinky.gateway.result.SavePointResult;
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.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration;
......@@ -44,8 +46,11 @@ import java.lang.reflect.Method;
import java.util.Collections;
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.util.ReflectUtil;
import io.fabric8.kubernetes.api.model.Pod;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
......@@ -62,7 +67,12 @@ public abstract class KubernetesGateway extends AbstractGateway {
protected FlinkConfig flinkConfig;
protected K8sConfig k8sConfig;
private Pod jmPodTemplate;
private Pod tmPodTemplate;
private Pod defaultPodTemplate;
private K8sClientHelper k8sClientHelper;
private String tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
public KubernetesGateway() {}
......@@ -97,7 +107,35 @@ public abstract class KubernetesGateway extends AbstractGateway {
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) {
......@@ -184,6 +222,11 @@ public abstract class KubernetesGateway extends AbstractGateway {
}
public boolean close() {
try {
FileUtil.del(tmpConfDir);
} catch (Exception e) {
log.warn(e.getMessage());
}
if (k8sClientHelper != null) {
return k8sClientHelper.close();
}
......
......@@ -30,14 +30,10 @@ import org.dinky.gateway.kubernetes.operator.api.FlinkDeploymentSpec;
import org.dinky.gateway.kubernetes.operator.api.JobSpec;
import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.CoreOptions;
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.UUID;
......@@ -45,8 +41,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.EqualsAndHashCode;
......@@ -67,7 +61,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
initBase();
initMetadata();
initSpec();
initResource(getK8sClientHelper().getKubernetesClient());
initResource();
initJob();
}
......@@ -143,8 +137,7 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
flinkDeploymentSpec.setJob(jobSpecBuilder.build());
}
private void initResource(KubernetesClient kubernetesClient) {
Pod defaultPod;
private void initResource() {
AbstractPodSpec jobManagerSpec = new AbstractPodSpec();
AbstractPodSpec taskManagerSpec = new AbstractPodSpec();
String jbcpu = kubernetsConfiguration.getOrDefault("kubernetes.jobmanager.cpu", "1");
......@@ -157,21 +150,9 @@ public abstract class KubernetsOperatorGateway extends KubernetesGateway {
logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem);
taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem));
defaultPod = getK8sClientHelper().decoratePodTemplate(config.getSql());
flinkDeploymentSpec.setPodTemplate(defaultPod);
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.setPodTemplate(getDefaultPodTemplate());
jobManagerSpec.setPodTemplate(getJmPodTemplate());
taskManagerSpec.setPodTemplate(getTmPodTemplate());
flinkDeploymentSpec.setJobManager(jobManagerSpec);
flinkDeploymentSpec.setTaskManager(taskManagerSpec);
}
......
......@@ -19,7 +19,6 @@
package org.dinky.gateway.kubernetes.utils;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.kubernetes.decorate.DinkySqlConfigMapDecorate;
import org.dinky.utils.TextUtil;
......@@ -34,9 +33,12 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
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.OwnerReference;
import io.fabric8.kubernetes.api.model.OwnerReferenceBuilder;
......@@ -59,28 +61,24 @@ public class K8sClientHelper {
private FlinkKubeClient client;
private KubernetesClient kubernetesClient;
protected Configuration configuration;
private K8sConfig k8sConfig;
private String tmpConfDir;
private DinkySqlConfigMapDecorate sqlFileDecorate;
public K8sClientHelper(Configuration configuration, K8sConfig k8sConfig) {
public K8sClientHelper(Configuration configuration, String kubeConfig) {
this.configuration = configuration;
this.k8sConfig = k8sConfig;
tmpConfDir = String.format("%s/tmp/kubernets/%s", System.getProperty("user.dir"), UUID.randomUUID());
initKubeClient();
initKubeClient(kubeConfig);
}
/**
* initKubeClient
*/
private void initKubeClient() {
private void initKubeClient(String kubeConfig) {
// k8s flink native client
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
// k8s fabric client
if (TextUtils.isEmpty(k8sConfig.getKubeConfig())) {
if (TextUtils.isEmpty(kubeConfig)) {
kubernetesClient = new DefaultKubernetesClient();
} else {
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(k8sConfig.getKubeConfig()));
kubernetesClient = new DefaultKubernetesClient(Config.fromKubeconfig(kubeConfig));
}
}
......@@ -123,22 +121,41 @@ public class K8sClientHelper {
* @param sqlStatement
* @return
*/
public Pod decoratePodTemplate(String sqlStatement) {
public Pod decoratePodTemplate(String sqlStatement, String podTemplate) {
Pod pod;
// if the user has configured the pod template, combine user's configuration
if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) {
InputStream is = new ByteArrayInputStream(k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8));
if (!TextUtil.isEmpty(podTemplate)) {
InputStream is = new ByteArrayInputStream(podTemplate.getBytes(StandardCharsets.UTF_8));
pod = kubernetesClient.pods().load(is).get();
} else {
// if the user has not configured the pod template, use the default configuration
pod = new Pod();
}
// decorate the pod template
sqlFileDecorate = new DinkySqlConfigMapDecorate(configuration, pod, sqlStatement);
return sqlFileDecorate.decoratePodMount();
if (TextUtil.isEmpty(sqlStatement)) {
log.warn("Sql statement is Empty !!!!, will not decorate podTemplate");
return pod;
} else {
// decorate the pod template
sqlFileDecorate = new DinkySqlConfigMapDecorate(configuration, pod, sqlStatement);
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
* delete the temporary directory and close the client
......@@ -151,11 +168,6 @@ public class K8sClientHelper {
if (kubernetesClient != null) {
kubernetesClient.close();
}
try {
return FileUtil.del(tmpConfDir);
} catch (Exception e) {
log.warn("failed delete kubernetes temp dir: " + tmpConfDir);
}
return false;
return true;
}
}
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