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

Refactor Gateway Submit (#2132)

* Refactor Gateway Submit * revert SqlUtil.java * fix code style * refacotr k8s gateway * refacotr k8s gateway * fix code style * fix packge err
parent 8956a2d3
...@@ -19,16 +19,11 @@ ...@@ -19,16 +19,11 @@
package org.dinky.data.model; package org.dinky.data.model;
import org.dinky.assertion.Asserts; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.mybatis.model.SuperEntity; import org.dinky.mybatis.model.SuperEntity;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import lombok.Data; import lombok.Data;
...@@ -55,27 +50,10 @@ public class ClusterConfiguration extends SuperEntity { ...@@ -55,27 +50,10 @@ public class ClusterConfiguration extends SuperEntity {
private String note; private String note;
@TableField(exist = false) public FlinkClusterConfig getFlinkClusterCfg() {
private Map<String, Object> config = new HashMap<>();
public Map<String, Object> parseConfig() {
ObjectMapper objectMapper = new ObjectMapper();
try {
if (Asserts.isNotNullString(configJson)) {
config = objectMapper.readValue(configJson, HashMap.class);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return config;
}
public FlinkClusterConfiguration parse() {
JSONObject json = new JSONObject(getConfigJson()); JSONObject json = new JSONObject(getConfigJson());
config = json; FlinkClusterConfig flinkClusterConfig = json.toBean(FlinkClusterConfig.class);
FlinkClusterConfiguration flinkClusterConfiguration = flinkClusterConfig.setType(GatewayType.get(type));
json.toBean(FlinkClusterConfiguration.class); return flinkClusterConfig;
flinkClusterConfiguration.setType(FlinkClusterConfiguration.Type.valueOf(type));
return flinkClusterConfiguration;
} }
} }
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.data.model; package org.dinky.data.model;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import org.dinky.mybatis.model.SuperEntity; import org.dinky.mybatis.model.SuperEntity;
...@@ -142,11 +143,11 @@ public class Task extends SuperEntity<Task> { ...@@ -142,11 +143,11 @@ public class Task extends SuperEntity<Task> {
public JobConfig buildSubmitConfig() { public JobConfig buildSubmitConfig() {
boolean useRemote = clusterId != null && clusterId != 0; boolean useRemote = clusterId != null && clusterId != 0;
Map<String, String> map = Map<String, String> map =
config.stream() parseConfig().stream()
.filter(Asserts::isNotNull) .filter(Asserts::isNotNull)
.collect( .collect(
Collectors.toMap( Collectors.toMap(
item -> item.get("key"), item -> item.get("name"),
item -> item.get("value"), item -> item.get("value"),
(a, b) -> b)); (a, b) -> b));
...@@ -171,7 +172,8 @@ public class Task extends SuperEntity<Task> { ...@@ -171,7 +172,8 @@ public class Task extends SuperEntity<Task> {
parallelism, parallelism,
savePointStrategy, savePointStrategy,
savePointPath, savePointPath,
map); map,
isJarTask());
} }
public JsonNode parseJsonNode(ObjectMapper mapper) { public JsonNode parseJsonNode(ObjectMapper mapper) {
...@@ -194,4 +196,8 @@ public class Task extends SuperEntity<Task> { ...@@ -194,4 +196,8 @@ public class Task extends SuperEntity<Task> {
jsonNode.put("enabled", this.getEnabled()); jsonNode.put("enabled", this.getEnabled());
return jsonNode; return jsonNode;
} }
public boolean isJarTask() {
return Dialect.isJarDialect(dialect);
}
} }
...@@ -20,11 +20,11 @@ ...@@ -20,11 +20,11 @@
package org.dinky.service; package org.dinky.service;
import org.dinky.data.model.ClusterConfiguration; import org.dinky.data.model.ClusterConfiguration;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.mybatis.service.ISuperService; import org.dinky.mybatis.service.ISuperService;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* ClusterConfigService * ClusterConfigService
...@@ -37,7 +37,7 @@ public interface ClusterConfigurationService extends ISuperService<ClusterConfig ...@@ -37,7 +37,7 @@ public interface ClusterConfigurationService extends ISuperService<ClusterConfig
List<ClusterConfiguration> listEnabledAll(); List<ClusterConfiguration> listEnabledAll();
Map<String, Object> getGatewayConfig(Integer id); FlinkClusterConfig getFlinkClusterCfg(Integer id);
TestResult testGateway(ClusterConfiguration clusterConfiguration); TestResult testGateway(ClusterConfiguration clusterConfiguration);
......
...@@ -19,37 +19,23 @@ ...@@ -19,37 +19,23 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import static org.dinky.gateway.config.GatewayConfig.FLINK_VERSION;
import org.dinky.config.Docker;
import org.dinky.data.model.ClusterConfiguration; import org.dinky.data.model.ClusterConfiguration;
import org.dinky.data.model.FlinkClusterConfiguration;
import org.dinky.data.model.FlinkClusterConfiguration.Type;
import org.dinky.gateway.config.ClusterConfig;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.mapper.ClusterConfigurationMapper; import org.dinky.mapper.ClusterConfigurationMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.ClusterConfigurationService; import org.dinky.service.ClusterConfigurationService;
import org.dinky.utils.DockerClientUtils;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
/** /**
* ClusterConfigServiceImpl * ClusterConfigServiceImpl
...@@ -66,9 +52,7 @@ public class ClusterConfigurationServiceImpl ...@@ -66,9 +52,7 @@ public class ClusterConfigurationServiceImpl
@Override @Override
public ClusterConfiguration getClusterConfigById(Integer id) { public ClusterConfiguration getClusterConfigById(Integer id) {
ClusterConfiguration clusterConfiguration = baseMapper.selectById(id); return baseMapper.selectById(id);
clusterConfiguration.parseConfig();
return clusterConfiguration;
} }
@Override @Override
...@@ -77,68 +61,16 @@ public class ClusterConfigurationServiceImpl ...@@ -77,68 +61,16 @@ public class ClusterConfigurationServiceImpl
} }
@Override @Override
public Map<String, Object> getGatewayConfig(Integer id) { public FlinkClusterConfig getFlinkClusterCfg(Integer id) {
ClusterConfiguration clusterConfiguration = this.getClusterConfigById(id); ClusterConfiguration clusterConfiguration = this.getClusterConfigById(id);
return clusterConfiguration.getConfig(); Assert.notNull(clusterConfiguration, "The clusterConfiguration not exists!");
return clusterConfiguration.getFlinkClusterCfg();
} }
@Override @Override
public TestResult testGateway(ClusterConfiguration clusterConfiguration) { public TestResult testGateway(ClusterConfiguration clusterConfiguration) {
FlinkClusterConfiguration config = clusterConfiguration.parse(); FlinkClusterConfig config = clusterConfiguration.getFlinkClusterCfg();
GatewayConfig gatewayConfig = new GatewayConfig(); GatewayConfig gatewayConfig = GatewayConfig.build(config);
Opt.ofBlankAble(config.getHadoopConfigPath())
.ifPresentOrElse(
hadoopConfigPath ->
gatewayConfig.setClusterConfig(
ClusterConfig.build(
config.getFlinkConfigPath(),
config.getFlinkLibPath(),
hadoopConfigPath)),
() ->
gatewayConfig.setClusterConfig(
ClusterConfig.build(config.getFlinkConfigPath())));
FlinkConfig flinkConfig =
CollUtil.isEmpty(config.getFlinkConfig())
? FlinkConfig.build(new HashMap<>(8))
: FlinkConfig.build(config.getFlinkConfig());
Map<String, String> flinkConfigMap = flinkConfig.getConfiguration();
gatewayConfig.setFlinkConfig(flinkConfig);
if (config.getType() == FlinkClusterConfiguration.Type.Yarn) {
gatewayConfig.setType(GatewayType.YARN_APPLICATION);
} else if (config.getType() == FlinkClusterConfiguration.Type.Kubernetes) {
gatewayConfig.setType(GatewayType.KUBERNETES_APPLICATION);
Map<String, String> kubernetesConfig = config.getKubernetesConfig();
// filter str blank value
kubernetesConfig =
MapUtil.filter(kubernetesConfig, entry -> !StrUtil.isBlank(entry.getValue()));
// set default value
kubernetesConfig.putIfAbsent("kubernetes.cluster-id", UUID.randomUUID().toString());
flinkConfigMap.putAll(kubernetesConfig);
try {
Docker docker =
Docker.build(
(Map<String, Object>)
clusterConfiguration.getConfig().get("dockerConfig"));
if (docker != null && clusterConfiguration.getId() != null) {
new DockerClientUtils(docker).initImage();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (config.getType() == Type.KubernetesOperator) {
gatewayConfig.setType(GatewayType.KUBERNETES_APPLICATION_OPERATOR);
config.getKubernetesConfig().put(FLINK_VERSION, config.getFlinkVersion());
flinkConfig.setFlinkKubetnetsConfig(config.getKubernetesConfig());
}
return JobManager.testGateway(gatewayConfig); return JobManager.testGateway(gatewayConfig);
} }
......
...@@ -27,8 +27,8 @@ import org.dinky.constant.FlinkConstant; ...@@ -27,8 +27,8 @@ import org.dinky.constant.FlinkConstant;
import org.dinky.data.model.Cluster; import org.dinky.data.model.Cluster;
import org.dinky.data.model.ClusterConfiguration; import org.dinky.data.model.ClusterConfiguration;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.exception.GatewayException; import org.dinky.gateway.exception.GatewayException;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.gateway.result.GatewayResult; import org.dinky.gateway.result.GatewayResult;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.mapper.ClusterInstanceMapper; import org.dinky.mapper.ClusterInstanceMapper;
...@@ -168,13 +168,9 @@ public class ClusterInstanceServiceImpl extends SuperServiceImpl<ClusterInstance ...@@ -168,13 +168,9 @@ public class ClusterInstanceServiceImpl extends SuperServiceImpl<ClusterInstance
throw new GatewayException("The cluster has been killed."); throw new GatewayException("The cluster has been killed.");
} }
Integer clusterConfigurationId = cluster.getClusterConfigurationId(); Integer clusterConfigurationId = cluster.getClusterConfigurationId();
ClusterConfiguration clusterConfiguration = FlinkClusterConfig flinkClusterConfig =
clusterConfigurationService.getClusterConfigById(clusterConfigurationId); clusterConfigurationService.getFlinkClusterCfg(clusterConfigurationId);
if (Asserts.isNull(clusterConfiguration)) { GatewayConfig gatewayConfig = GatewayConfig.build(flinkClusterConfig);
throw new GatewayException("The cluster configuration does not exist.");
}
GatewayConfig gatewayConfig = GatewayConfig.build(clusterConfiguration.getConfig());
gatewayConfig.setType(GatewayType.get(cluster.getType()));
JobManager.killCluster(gatewayConfig, cluster.getName()); JobManager.killCluster(gatewayConfig, cluster.getName());
} }
...@@ -185,8 +181,8 @@ public class ClusterInstanceServiceImpl extends SuperServiceImpl<ClusterInstance ...@@ -185,8 +181,8 @@ public class ClusterInstanceServiceImpl extends SuperServiceImpl<ClusterInstance
if (Asserts.isNull(clusterConfiguration)) { if (Asserts.isNull(clusterConfiguration)) {
throw new GatewayException("The cluster configuration does not exist."); throw new GatewayException("The cluster configuration does not exist.");
} }
GatewayConfig gatewayConfig = GatewayConfig.build(clusterConfiguration.getConfig()); GatewayConfig gatewayConfig =
gatewayConfig.setType(GatewayType.getSessionType(clusterConfiguration.getType())); GatewayConfig.build(clusterConfiguration.getFlinkClusterCfg());
GatewayResult gatewayResult = JobManager.deploySessionCluster(gatewayConfig); GatewayResult gatewayResult = JobManager.deploySessionCluster(gatewayConfig);
return registersCluster( return registersCluster(
Cluster.autoRegistersCluster( Cluster.autoRegistersCluster(
......
...@@ -44,6 +44,7 @@ import org.dinky.data.result.SelectResult; ...@@ -44,6 +44,7 @@ import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult; import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.lineage.LineageBuilder; import org.dinky.explainer.lineage.LineageBuilder;
import org.dinky.explainer.lineage.LineageResult; import org.dinky.explainer.lineage.LineageResult;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.gateway.model.JobInfo; import org.dinky.gateway.model.JobInfo;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
...@@ -398,8 +399,8 @@ public class StudioServiceImpl implements StudioService { ...@@ -398,8 +399,8 @@ public class StudioServiceImpl implements StudioService {
JobConfig jobConfig = new JobConfig(); JobConfig jobConfig = new JobConfig();
jobConfig.setAddress(cluster.getJobManagerHost()); jobConfig.setAddress(cluster.getJobManagerHost());
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) { if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
Map<String, Object> gatewayConfig = FlinkClusterConfig gatewayConfig =
clusterConfigurationService.getGatewayConfig( clusterConfigurationService.getFlinkClusterCfg(
cluster.getClusterConfigurationId()); cluster.getClusterConfigurationId());
jobConfig.buildGatewayConfig(gatewayConfig); jobConfig.buildGatewayConfig(gatewayConfig);
} }
...@@ -413,25 +414,22 @@ public class StudioServiceImpl implements StudioService { ...@@ -413,25 +414,22 @@ public class StudioServiceImpl implements StudioService {
Cluster cluster = clusterInstanceService.getById(clusterId); Cluster cluster = clusterInstanceService.getById(clusterId);
Asserts.checkNotNull(cluster, "该集群不存在"); Asserts.checkNotNull(cluster, "该集群不存在");
boolean useGateway = false;
JobConfig jobConfig = new JobConfig(); JobConfig jobConfig = new JobConfig();
jobConfig.setAddress(cluster.getJobManagerHost()); jobConfig.setAddress(cluster.getJobManagerHost());
jobConfig.setType(cluster.getType()); jobConfig.setType(cluster.getType());
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) { if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
// 如果用户选择用dinky平台来托管集群信息 说明任务一定是从dinky发起提交的 // 如果用户选择用dinky平台来托管集群信息 说明任务一定是从dinky发起提交的
Map<String, Object> gatewayConfig = FlinkClusterConfig gatewayConfig =
clusterConfigurationService.getGatewayConfig( clusterConfigurationService.getFlinkClusterCfg(
cluster.getClusterConfigurationId()); cluster.getClusterConfigurationId());
jobConfig.buildGatewayConfig(gatewayConfig); jobConfig.buildGatewayConfig(gatewayConfig);
jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName()); jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName());
jobConfig.setTaskId(cluster.getTaskId()); jobConfig.setTaskId(cluster.getTaskId());
useGateway = true;
} else { } else {
// 用户选择外部的平台来托管集群信息,但是集群上的任务不一定是通过dinky提交的 // 用户选择外部的平台来托管集群信息,但是集群上的任务不一定是通过dinky提交的
jobConfig.setTaskId(taskId); jobConfig.setTaskId(taskId);
} }
JobManager jobManager = JobManager.build(jobConfig); JobManager jobManager = JobManager.build(jobConfig);
jobManager.setUseGateway(useGateway);
SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null); SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null);
if (Asserts.isNotNull(savePointResult)) { if (Asserts.isNotNull(savePointResult)) {
......
...@@ -32,6 +32,7 @@ import org.dinky.context.RowLevelPermissionsContext; ...@@ -32,6 +32,7 @@ import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.task.DaemonFactory; import org.dinky.daemon.task.DaemonFactory;
import org.dinky.daemon.task.DaemonTaskConfig; import org.dinky.daemon.task.DaemonTaskConfig;
import org.dinky.data.constant.CommonConstant;
import org.dinky.data.constant.FlinkRestResultConstant; import org.dinky.data.constant.FlinkRestResultConstant;
import org.dinky.data.dto.SqlDTO; import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskRollbackVersionDTO; import org.dinky.data.dto.TaskRollbackVersionDTO;
...@@ -74,6 +75,7 @@ import org.dinky.gateway.config.GatewayConfig; ...@@ -74,6 +75,7 @@ import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.enums.SavePointStrategy; import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.gateway.enums.SavePointType; import org.dinky.gateway.enums.SavePointType;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.dinky.gateway.model.JobInfo; import org.dinky.gateway.model.JobInfo;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.FlinkJobTask; import org.dinky.job.FlinkJobTask;
...@@ -88,7 +90,6 @@ import org.dinky.metadata.result.JdbcSelectResult; ...@@ -88,7 +90,6 @@ import org.dinky.metadata.result.JdbcSelectResult;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.process.context.ProcessContextHolder; import org.dinky.process.context.ProcessContextHolder;
import org.dinky.process.enums.ProcessType; import org.dinky.process.enums.ProcessType;
import org.dinky.process.exception.DinkyException;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.service.AlertGroupService; import org.dinky.service.AlertGroupService;
import org.dinky.service.AlertHistoryService; import org.dinky.service.AlertHistoryService;
...@@ -152,11 +153,11 @@ import cn.dev33.satoken.stp.StpUtil; ...@@ -152,11 +153,11 @@ import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode; import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil; import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
/** TaskServiceImpl */ /** TaskServiceImpl */
...@@ -166,7 +167,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -166,7 +167,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private final StatementService statementService; private final StatementService statementService;
private final ClusterInstanceService clusterInstanceService; private final ClusterInstanceService clusterInstanceService;
private final ClusterConfigurationService clusterConfigurationService; private final ClusterConfigurationService clusterCfgService;
private final SavepointsService savepointsService; private final SavepointsService savepointsService;
private final JarService jarService; private final JarService jarService;
private final DataBaseService dataBaseService; private final DataBaseService dataBaseService;
...@@ -204,14 +205,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -204,14 +205,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Value("server.port") @Value("server.port")
private String serverPort; private String serverPort;
private String buildParas(Integer id) { private String[] buildParas(Integer id) {
return buildParas(id, StrUtil.NULL); return buildParas(id, StrUtil.NULL);
} }
private String buildParas(Integer id, String dinkyAddr) { private String[] buildParas(Integer id, String dinkyAddr) {
return String.format( return String.format(
"--id %d --driver %s --url %s --username %s --password %s --dinkyAddr %s", "--id %d --driver %s --url %s --username %s --password %s --dinkyAddr %s",
id, driver(), url(), username(), password(), dinkyAddr); id, driver(), url(), username(), password(), dinkyAddr)
.split(" ");
} }
@Override @Override
...@@ -233,9 +235,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -233,9 +235,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
process.info("Initializing Flink job config..."); process.info("Initializing Flink job config...");
JobConfig config = buildJobConfig(task); JobConfig config = buildJobConfig(task);
if (GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) { // if (GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) {
loadDocker(id, config.getClusterConfigurationId(), config.getGatewayConfig()); // loadDocker(id, config.getClusterConfigurationId(), config.getGatewayConfig());
} // }
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
process.start(); process.start();
...@@ -253,20 +255,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -253,20 +255,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
private void loadDocker( private void loadDocker(
Integer taskId, Integer clusterConfigurationId, GatewayConfig gatewayConfig) { Integer taskId, Integer clusterConfigurationId, GatewayConfig gatewayConfig) {
Map<String, Object> dockerConfig = Map<String, Object> dockerConfig =
(Map<String, Object>) clusterCfgService
clusterConfigurationService .getClusterConfigById(clusterConfigurationId)
.getClusterConfigById(clusterConfigurationId) .getFlinkClusterCfg()
.getConfig() .getKubernetesConfig()
.get("dockerConfig"); .getDockerConfig();
if (dockerConfig == null) { if (dockerConfig == null) {
return; return;
} }
String params = String[] params =
buildParas(taskId, dockerConfig.getOrDefault("dinky.remote.addr", "").toString()); buildParas(taskId, dockerConfig.getOrDefault("dinky.remote.addr", "").toString());
gatewayConfig.getAppConfig().setUserJarParas(params.split(" ")); gatewayConfig.getAppConfig().setUserJarParas(params);
Docker docker = Docker.build(dockerConfig); Docker docker = Docker.build(dockerConfig);
if (docker == null || StringUtils.isBlank(docker.getInstance())) { if (docker == null || StringUtils.isBlank(docker.getInstance())) {
...@@ -588,8 +590,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -588,8 +590,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public Task getTaskByNameAndTenantId(String name, Integer tenantId) { public Task getTaskByNameAndTenantId(String name, Integer tenantId) {
Task task = baseMapper.getTaskByNameAndTenantId(name, tenantId); return baseMapper.getTaskByNameAndTenantId(name, tenantId);
return task;
} }
@Override @Override
...@@ -598,18 +599,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -598,18 +599,15 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
return JobStatus.UNKNOWN; return JobStatus.UNKNOWN;
} }
Map<String, Object> gatewayConfigMap = Integer clusterId = jobInfoDetail.getClusterConfiguration().getId();
clusterConfigurationService.getGatewayConfig( String appId = jobInfoDetail.getCluster().getName();
jobInfoDetail.getClusterConfiguration().getId());
JobConfig jobConfig = new JobConfig(); FlinkClusterConfig clusterConfig = clusterCfgService.getFlinkClusterCfg(clusterId);
jobConfig.buildGatewayConfig(gatewayConfigMap); GatewayConfig gatewayConfig = GatewayConfig.build(clusterConfig);
GatewayConfig gatewayConfig = jobConfig.getGatewayConfig(); gatewayConfig.getClusterConfig().setAppId(appId);
gatewayConfig.setType(GatewayType.get(jobInfoDetail.getCluster().getType()));
gatewayConfig.getClusterConfig().setAppId(jobInfoDetail.getCluster().getName());
Gateway gateway = Gateway.build(gatewayConfig); Gateway gateway = Gateway.build(gatewayConfig);
return gateway.getJobStatusById(jobInfoDetail.getCluster().getName()); return gateway.getJobStatusById(appId);
} }
@Override @Override
...@@ -900,27 +898,13 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -900,27 +898,13 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
JobConfig jobConfig = task.buildSubmitConfig(); JobConfig jobConfig = task.buildSubmitConfig();
jobConfig.setType(cluster.getType()); jobConfig.setType(cluster.getType());
boolean useGateway = false;
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) { if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
Map<String, Object> gatewayConfig = FlinkClusterConfig flinkClusterConfig = buildGatewayCfgObj(jobConfig);
clusterConfigurationService.getGatewayConfig( jobConfig.buildGatewayConfig(flinkClusterConfig);
cluster.getClusterConfigurationId());
// 如果是k8s application 模式,且不是sql任务,则需要补齐statement 内的自定义配置
if (Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect())) {
Statement statement = statementService.getById(cluster.getTaskId());
Map<String, Object> statementConfig =
JSONUtil.toMap(statement.getStatement(), String.class, Object.class);
gatewayConfig.putAll(statementConfig);
}
jobConfig.buildGatewayConfig(gatewayConfig);
jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName());
useGateway = true;
} }
jobConfig.setTaskId(jobInstance.getTaskId());
jobConfig.setAddress(cluster.getJobManagerHost()); jobConfig.setAddress(cluster.getJobManagerHost());
JobManager jobManager = JobManager.build(jobConfig); JobManager jobManager = JobManager.build(jobConfig);
jobManager.setUseGateway(useGateway);
String jobId = jobInstance.getJid(); String jobId = jobInstance.getJid();
if ("canceljob".equals(savePointType)) { if ("canceljob".equals(savePointType)) {
...@@ -952,97 +936,85 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -952,97 +936,85 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
private JobConfig buildJobConfig(Task task) { private JobConfig buildJobConfig(Task task) {
boolean isJarTask = if (!task.isJarTask()) {
Dialect.FLINK_JAR.equalsVal(task.getDialect()) String envSql = buildEnvSql(task);
|| Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect()); task.setStatement(envSql + task.getStatement());
boolean fragment = Asserts.isNotNull(task.getFragment()) ? task.getFragment() : false;
if (!isJarTask && fragment) {
String flinkWithSql = dataBaseService.getEnabledFlinkWithSql();
if (Asserts.isNotNullString(flinkWithSql)) {
task.setStatement(flinkWithSql + "\r\n" + task.getStatement());
}
} }
boolean isEnvIdValid = Asserts.isNotNull(task.getEnvId()) && task.getEnvId() != 0; JobConfig config = task.buildSubmitConfig();
if (!isJarTask && isEnvIdValid) {
Task envTask = getTaskInfoById(task.getEnvId()); Savepoints savepoints = buildSavepoint(config);
if (Asserts.isNotNull(envTask) && Asserts.isNotNullString(envTask.getStatement())) { if (Asserts.isNotNull(savepoints)) {
task.setStatement(envTask.getStatement() + "\r\n" + task.getStatement()); config.setSavePointPath(savepoints.getPath());
} config.getConfig().put("execution.savepoint.path", savepoints.getPath());
} }
JobConfig config = task.buildSubmitConfig(); if (!GatewayType.get(task.getType()).isDeployCluster()) {
config.setJarTask(isJarTask); String address =
if (!JobManager.useGateway(config.getType())) {
config.setAddress(
clusterInstanceService.buildEnvironmentAddress( clusterInstanceService.buildEnvironmentAddress(
config.isUseRemote(), task.getClusterId())); config.isUseRemote(), task.getClusterId());
} else if (Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect()) config.setAddress(address);
// support custom K8s app submit, rather than clusterConfiguration
&& (GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())
|| GatewayType.KUBERNETES_APPLICATION_OPERATOR.equalsValue(
config.getType()))) {
Map<String, Object> taskConfig =
JSONUtil.toMap(task.getStatement(), String.class, Object.class);
Map<String, Object> clusterConfiguration =
clusterConfigurationService.getGatewayConfig(task.getClusterConfigurationId());
clusterConfiguration.putAll((Map<String, Object>) taskConfig.get("appConfig"));
clusterConfiguration.put("taskCustomConfig", taskConfig);
config.buildGatewayConfig(clusterConfiguration);
} else { } else {
Map<String, Object> gatewayConfig = config.buildGatewayConfig(buildGatewayCfgObj(config));
clusterConfigurationService.getGatewayConfig(task.getClusterConfigurationId());
// submit application type with clusterConfiguration
if (GatewayType.YARN_APPLICATION.equalsValue(config.getType())
|| GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())
|| GatewayType.KUBERNETES_APPLICATION_OPERATOR.equalsValue(config.getType())) {
if (isJarTask) {
Jar jar = jarService.getById(task.getJarId());
Assert.check(jar);
gatewayConfig.put("userJarPath", jar.getPath());
gatewayConfig.put("userJarParas", jar.getParas());
gatewayConfig.put("userJarMainAppClass", jar.getMainClass());
} else {
Opt.ofBlankAble(gatewayConfig.get("userJarPath"))
.orElseThrow(
() ->
new DinkyException(
"application 模式支持需要在 注册中心->集群管理->集群配置管理 填写jar路径。"));
gatewayConfig.put("userJarParas", buildParas(config.getTaskId()));
gatewayConfig.put("userJarMainAppClass", "org.dinky.app.MainApp");
}
}
config.buildGatewayConfig(gatewayConfig);
config.addGatewayConfig(task.parseConfig());
} }
config.setVariables(fragmentVariableService.listEnabledVariables());
buildRowPermission();
return config;
}
private Savepoints buildSavepoint(JobConfig config) {
switch (config.getSavePointStrategy()) { switch (config.getSavePointStrategy()) {
case LATEST: case LATEST:
Savepoints latestSavepoints = return savepointsService.getLatestSavepointByTaskId(config.getTaskId());
savepointsService.getLatestSavepointByTaskId(task.getId());
if (Asserts.isNotNull(latestSavepoints)) {
config.setSavePointPath(latestSavepoints.getPath());
config.getConfig().put("execution.savepoint.path", latestSavepoints.getPath());
}
break;
case EARLIEST: case EARLIEST:
Savepoints earliestSavepoints = return savepointsService.getEarliestSavepointByTaskId(config.getTaskId());
savepointsService.getEarliestSavepointByTaskId(task.getId());
if (Asserts.isNotNull(earliestSavepoints)) {
config.setSavePointPath(earliestSavepoints.getPath());
config.getConfig()
.put("execution.savepoint.path", earliestSavepoints.getPath());
}
break;
case CUSTOM: case CUSTOM:
config.setSavePointPath(config.getSavePointPath()); return new Savepoints() {
config.getConfig().put("execution.savepoint.path", config.getSavePointPath()); {
break; setPath(config.getSavePointPath());
}
};
default: default:
config.setSavePointPath(null); return null;
} }
config.setVariables(fragmentVariableService.listEnabledVariables()); }
private FlinkClusterConfig buildGatewayCfgObj(JobConfig config) {
FlinkClusterConfig flinkClusterCfg =
clusterCfgService.getFlinkClusterCfg(config.getClusterConfigurationId());
flinkClusterCfg.getAppConfig().setUserJarParas(buildParas(config.getTaskId()));
flinkClusterCfg.getFlinkConfig().getConfiguration().putAll(config.getConfig());
// if (config.isJarTask()) {
// JSONObject clusterObj = new JSONObject(flinkClusterCfg);
// JSONObject taskObj = new JSONObject(task.getStatement());
// return JSONUtil.merge(clusterObj,taskObj).toBean(FlinkClusterConfig.class);
// }
return flinkClusterCfg;
}
private String buildEnvSql(Task task) {
String sql = CommonConstant.LineSep;
boolean fragment = Asserts.isNotNull(task.getFragment()) ? task.getFragment() : false;
if (fragment) {
String flinkWithSql = dataBaseService.getEnabledFlinkWithSql();
if (Asserts.isNotNullString(flinkWithSql)) {
sql += flinkWithSql + CommonConstant.LineSep;
}
}
boolean isEnvIdValid = Asserts.isNotNull(task.getEnvId()) && task.getEnvId() != 0;
if (isEnvIdValid) {
Task envTask = getTaskInfoById(task.getEnvId());
if (Asserts.isNotNull(envTask) && Asserts.isNotNullString(envTask.getStatement())) {
sql += envTask.getStatement() + CommonConstant.LineSep;
}
}
return sql;
}
private void buildRowPermission() {
List<RowPermissions> currentRoleSelectPermissions = List<RowPermissions> currentRoleSelectPermissions =
userService.getCurrentRoleSelectPermissions(); userService.getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) { if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
...@@ -1058,7 +1030,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1058,7 +1030,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
RowLevelPermissionsContext.set(permission); RowLevelPermissionsContext.set(permission);
} }
return config;
} }
@Override @Override
...@@ -1081,8 +1052,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1081,8 +1052,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
history.setConfig(JSONUtil.parseObject(history.getConfigJson())); history.setConfig(JSONUtil.parseObject(history.getConfigJson()));
if (Asserts.isNotNull(history.getClusterConfigurationId())) { if (Asserts.isNotNull(history.getClusterConfigurationId())) {
ClusterConfiguration clusterConfigById = ClusterConfiguration clusterConfigById =
clusterConfigurationService.getClusterConfigById( clusterCfgService.getClusterConfigById(history.getClusterConfigurationId());
history.getClusterConfigurationId());
jobInfoDetail.setClusterConfiguration(clusterConfigById); jobInfoDetail.setClusterConfiguration(clusterConfigById);
jobInfoDetail.getInstance().setType(history.getType()); jobInfoDetail.getInstance().setType(history.getType());
} }
...@@ -1198,7 +1168,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1198,7 +1168,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
// clusterConfigurationName // clusterConfigurationName
if (Asserts.isNotNull(task.getClusterConfigurationId())) { if (Asserts.isNotNull(task.getClusterConfigurationId())) {
ClusterConfiguration clusterConfiguration = ClusterConfiguration clusterConfiguration =
clusterConfigurationService.getById(task.getClusterConfigurationId()); clusterCfgService.getById(task.getClusterConfigurationId());
jsonNode.put( jsonNode.put(
"clusterConfigurationName", "clusterConfigurationName",
Asserts.isNotNull(clusterConfiguration) Asserts.isNotNull(clusterConfiguration)
...@@ -1287,7 +1257,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1287,7 +1257,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
if (Asserts.isNotNull(task.getClusterConfigurationName())) { if (Asserts.isNotNull(task.getClusterConfigurationName())) {
ClusterConfiguration clusterConfiguration = ClusterConfiguration clusterConfiguration =
clusterConfigurationService.getOne( clusterCfgService.getOne(
new QueryWrapper<ClusterConfiguration>() new QueryWrapper<ClusterConfiguration>()
.eq("name", task.getClusterConfigurationName())); .eq("name", task.getClusterConfigurationName()));
if (Asserts.isNotNull(clusterConfiguration)) { if (Asserts.isNotNull(clusterConfiguration)) {
...@@ -1430,7 +1400,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1430,7 +1400,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
Task updateTask = new Task(); Task updateTask = new Task();
updateTask.setId(jobInstance.getTaskId()); updateTask.setId(jobInstance.getTaskId());
updateTask.setJobInstanceId(0); updateTask.setJobInstanceId(jobInstance.getId());
Integer jobInstanceId = jobInstance.getId(); Integer jobInstanceId = jobInstance.getId();
// 获取任务历史信息 // 获取任务历史信息
...@@ -1438,12 +1408,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1438,12 +1408,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
// some job need do something on Done, example flink-kubernets-operator // some job need do something on Done, example flink-kubernets-operator
if (GatewayType.isDeployCluster(jobInstance.getType())) { if (GatewayType.isDeployCluster(jobInstance.getType())) {
JobConfig jobConfig = new JobConfig(); JobConfig jobConfig = new JobConfig();
Map<String, Object> clusterConfig = String configJson = jobHistory.getClusterConfiguration().get("configJson").asText();
JSONUtil.toMap( jobConfig.buildGatewayConfig(
jobHistory.getClusterConfiguration().get("configJson").asText(), new JSONObject(configJson).toBean(FlinkClusterConfig.class));
String.class,
Object.class);
jobConfig.buildGatewayConfig(clusterConfig);
jobConfig.getGatewayConfig().setType(GatewayType.get(jobInstance.getType())); jobConfig.getGatewayConfig().setType(GatewayType.get(jobInstance.getType()));
jobConfig.getGatewayConfig().getFlinkConfig().setJobName(jobInstance.getName()); jobConfig.getGatewayConfig().getFlinkConfig().setJobName(jobInstance.getName());
Gateway.build(jobConfig.getGatewayConfig()) Gateway.build(jobConfig.getGatewayConfig())
......
...@@ -33,7 +33,6 @@ import org.dinky.utils.ZipUtils; ...@@ -33,7 +33,6 @@ import org.dinky.utils.ZipUtils;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.flink.configuration.CheckpointingOptions;
import org.apache.flink.configuration.PipelineOptions; import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.python.PythonOptions; import org.apache.flink.python.PythonOptions;
...@@ -53,7 +52,6 @@ import java.util.Arrays; ...@@ -53,7 +52,6 @@ import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -176,33 +174,6 @@ public class Submitter { ...@@ -176,33 +174,6 @@ public class Submitter {
// 加载第三方jar // 加载第三方jar
loadDep(taskConfig.get("type"), id, dinkyAddr, executorSetting); loadDep(taskConfig.get("type"), id, dinkyAddr, executorSetting);
String uuid = UUID.randomUUID().toString().replace("-", "");
if (executorSetting
.getConfig()
.containsKey(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key())) {
executorSetting
.getConfig()
.put(
CheckpointingOptions.CHECKPOINTS_DIRECTORY.key(),
executorSetting
.getConfig()
.get(CheckpointingOptions.CHECKPOINTS_DIRECTORY.key())
+ "/"
+ uuid);
}
if (executorSetting
.getConfig()
.containsKey(CheckpointingOptions.SAVEPOINT_DIRECTORY.key())) {
executorSetting
.getConfig()
.put(
CheckpointingOptions.SAVEPOINT_DIRECTORY.key(),
executorSetting
.getConfig()
.get(CheckpointingOptions.SAVEPOINT_DIRECTORY.key())
+ "/"
+ uuid);
}
logger.info("作业配置如下: {}", executorSetting); logger.info("作业配置如下: {}", executorSetting);
Executor executor = Executor.buildAppStreamExecutor(executorSetting); Executor executor = Executor.buildAppStreamExecutor(executorSetting);
List<StatementParam> ddl = new ArrayList<>(); List<StatementParam> ddl = new ArrayList<>();
......
...@@ -108,4 +108,15 @@ public enum Dialect { ...@@ -108,4 +108,15 @@ public enum Dialect {
return false; return false;
} }
} }
public static boolean isJarDialect(String value) {
Dialect dialect = Dialect.get(value);
switch (dialect) {
case FLINK_JAR:
case KUBERNETES_APPLICATION:
return true;
default:
return false;
}
}
} }
...@@ -28,4 +28,7 @@ public final class CommonConstant { ...@@ -28,4 +28,7 @@ public final class CommonConstant {
/** 实例健康 */ /** 实例健康 */
public static final String HEALTHY = "1"; public static final String HEALTHY = "1";
public static final String DINKY_APP_MAIN_CLASS = "org.dinky.app.MainApp";
public static final String LineSep = System.getProperty("line.separator");
} }
...@@ -30,8 +30,10 @@ import org.dinky.assertion.Asserts; ...@@ -30,8 +30,10 @@ import org.dinky.assertion.Asserts;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.TimeZone; import java.util.TimeZone;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -50,6 +52,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -50,6 +52,9 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.CollectionType;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
/** /**
* JSONUtil * JSONUtil
* *
...@@ -200,4 +205,22 @@ public class JSONUtil { ...@@ -200,4 +205,22 @@ public class JSONUtil {
} }
} }
} }
public static JSONObject merge(JSONObject mergeTo, JSONObject... values) {
for (JSONObject value : values) {
Set<String> allKeys = new HashSet<>();
allKeys.addAll(mergeTo.keySet());
allKeys.addAll(value.keySet());
for (String key : allKeys) {
if (value.containsKey(key)) {
if (value.get(key) instanceof JSONObject) {
return merge((JSONObject) mergeTo.get(key), (JSONObject) value.get(key));
} else if (value.get(key) instanceof JSONArray) {
((JSONArray) mergeTo.get(key)).addAll(((JSONArray) value.get(key)));
}
}
}
}
return mergeTo;
}
} }
...@@ -25,12 +25,12 @@ import org.dinky.executor.ExecutorSetting; ...@@ -25,12 +25,12 @@ import org.dinky.executor.ExecutorSetting;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.enums.SavePointStrategy; import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.apache.flink.configuration.CoreOptions; import org.apache.flink.configuration.CoreOptions;
import org.apache.flink.configuration.RestOptions; import org.apache.flink.configuration.RestOptions;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import lombok.Getter; import lombok.Getter;
...@@ -233,7 +233,8 @@ public class JobConfig { ...@@ -233,7 +233,8 @@ public class JobConfig {
Integer parallelism, Integer parallelism,
Integer savePointStrategyValue, Integer savePointStrategyValue,
String savePointPath, String savePointPath,
Map<String, String> config) { Map<String, String> config,
boolean isJarTask) {
this.type = type; this.type = type;
this.step = step; this.step = step;
this.useResult = useResult; this.useResult = useResult;
...@@ -252,6 +253,7 @@ public class JobConfig { ...@@ -252,6 +253,7 @@ public class JobConfig {
this.savePointStrategy = SavePointStrategy.get(savePointStrategyValue); this.savePointStrategy = SavePointStrategy.get(savePointStrategyValue);
this.savePointPath = savePointPath; this.savePointPath = savePointPath;
this.config = config; this.config = config;
this.isJarTask = isJarTask;
} }
public ExecutorSetting getExecutorSetting() { public ExecutorSetting getExecutorSetting() {
...@@ -266,29 +268,15 @@ public class JobConfig { ...@@ -266,29 +268,15 @@ public class JobConfig {
config); config);
} }
public void buildGatewayConfig(Map<String, Object> config) { public void buildGatewayConfig(FlinkClusterConfig config) {
gatewayConfig = GatewayConfig.build(config); gatewayConfig = GatewayConfig.build(config);
if (config.containsKey("flinkConfig") gatewayConfig.setTaskId(getTaskId());
&& Asserts.isNotNullMap((Map<String, String>) config.get("flinkConfig"))) { gatewayConfig.getFlinkConfig().setJobName(getJobName());
gatewayConfig gatewayConfig
.getFlinkConfig() .getFlinkConfig()
.getConfiguration() .getConfiguration()
.put(CoreOptions.DEFAULT_PARALLELISM.key(), String.valueOf(parallelism)); .put(CoreOptions.DEFAULT_PARALLELISM.key(), String.valueOf(parallelism));
} setUseRemote(false);
}
public void addGatewayConfig(List<Map<String, String>> configList) {
if (Asserts.isNull(gatewayConfig)) {
gatewayConfig = new GatewayConfig();
}
for (Map<String, String> item : configList) {
if (Asserts.isNotNull(item)) {
gatewayConfig
.getFlinkConfig()
.getConfiguration()
.put(item.get("key"), item.get("value"));
}
}
} }
public void addGatewayConfig(Map<String, Object> config) { public void addGatewayConfig(Map<String, Object> config) {
......
...@@ -128,14 +128,6 @@ public class JobManager { ...@@ -128,14 +128,6 @@ public class JobManager {
public JobManager() {} public JobManager() {}
public void setUseGateway(boolean useGateway) {
this.useGateway = useGateway;
}
public boolean isUseGateway() {
return useGateway;
}
public void setPlanMode(boolean planMode) { public void setPlanMode(boolean planMode) {
isPlanMode = planMode; isPlanMode = planMode;
} }
...@@ -179,7 +171,6 @@ public class JobManager { ...@@ -179,7 +171,6 @@ public class JobManager {
} }
public static JobManager build(JobConfig config) { public static JobManager build(JobConfig config) {
initGatewayConfig(config);
JobManager manager = new JobManager(config); JobManager manager = new JobManager(config);
manager.init(); manager.init();
return manager; return manager;
...@@ -193,24 +184,6 @@ public class JobManager { ...@@ -193,24 +184,6 @@ public class JobManager {
return manager; return manager;
} }
private static void initGatewayConfig(JobConfig config) {
if (useGateway(config.getType())) {
Asserts.checkNull(config.getGatewayConfig(), "GatewayConfig 不能为空");
config.getGatewayConfig().setType(GatewayType.get(config.getType()));
config.getGatewayConfig().setTaskId(config.getTaskId());
config.getGatewayConfig().getFlinkConfig().setJobName(config.getJobName());
config.getGatewayConfig().getFlinkConfig().setSavePoint(config.getSavePointPath());
config.setUseRemote(false);
}
}
public static boolean useGateway(String type) {
return (GatewayType.YARN_PER_JOB.equalsValue(type)
|| GatewayType.YARN_APPLICATION.equalsValue(type)
|| GatewayType.KUBERNETES_APPLICATION.equalsValue(type)
|| GatewayType.KUBERNETES_APPLICATION_OPERATOR.equalsValue(type));
}
private Executor createExecutor() { private Executor createExecutor() {
initEnvironmentSetting(); initEnvironmentSetting();
if (!runMode.equals(GatewayType.LOCAL) && !useGateway && config.isUseRemote()) { if (!runMode.equals(GatewayType.LOCAL) && !useGateway && config.isUseRemote()) {
...@@ -246,7 +219,7 @@ public class JobManager { ...@@ -246,7 +219,7 @@ public class JobManager {
public boolean init() { public boolean init() {
if (!isPlanMode) { if (!isPlanMode) {
runMode = GatewayType.get(config.getType()); runMode = GatewayType.get(config.getType());
useGateway = useGateway(config.getType()); useGateway = GatewayType.isDeployCluster(config.getType());
handler = JobHandler.build(); handler = JobHandler.build();
} }
useStatementSet = config.isUseStatementSet(); useStatementSet = config.isUseStatementSet();
......
...@@ -62,7 +62,7 @@ public abstract class AbstractGateway implements Gateway { ...@@ -62,7 +62,7 @@ public abstract class AbstractGateway implements Gateway {
protected static final Logger logger = LoggerFactory.getLogger(AbstractGateway.class); protected static final Logger logger = LoggerFactory.getLogger(AbstractGateway.class);
protected GatewayConfig config; protected GatewayConfig config;
protected Configuration configuration; protected Configuration configuration = new Configuration();
public AbstractGateway() {} public AbstractGateway() {}
......
...@@ -19,40 +19,19 @@ ...@@ -19,40 +19,19 @@
package org.dinky.gateway.config; package org.dinky.gateway.config;
import org.dinky.assertion.Asserts; import org.dinky.data.constant.CommonConstant;
import lombok.Getter; import lombok.Data;
import lombok.Setter;
import lombok.With;
/** /**
* AppConfig * AppConfig
* *
* @since 2021/11/3 21:55 * @since 2021/11/3 21:55
*/ */
@Setter @Data
@Getter
@With
public class AppConfig { public class AppConfig {
private String userJarPath; private String userJarPath;
private String[] userJarParas; private String[] userJarParas;
private String userJarMainAppClass; private String userJarMainAppClass = CommonConstant.DINKY_APP_MAIN_CLASS;
public AppConfig() {}
public AppConfig(String userJarPath, String[] userJarParas, String userJarMainAppClass) {
this.userJarPath = userJarPath;
this.userJarParas = userJarParas;
this.userJarMainAppClass = userJarMainAppClass;
}
public static AppConfig build(
String userJarPath, String userJarParasStr, String userJarMainAppClass) {
if (Asserts.isNotNullString(userJarParasStr)) {
return new AppConfig(userJarPath, userJarParasStr.split(" "), userJarMainAppClass);
} else {
return new AppConfig(userJarPath, new String[] {}, userJarMainAppClass);
}
}
} }
...@@ -23,7 +23,9 @@ import org.dinky.assertion.Asserts; ...@@ -23,7 +23,9 @@ import org.dinky.assertion.Asserts;
import org.dinky.gateway.enums.ActionType; import org.dinky.gateway.enums.ActionType;
import org.dinky.gateway.enums.SavePointType; import org.dinky.gateway.enums.SavePointType;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
...@@ -45,11 +47,12 @@ public class FlinkConfig { ...@@ -45,11 +47,12 @@ public class FlinkConfig {
private String jobName; private String jobName;
private String jobId; private String jobId;
private String flinkVersion;
private ActionType action; private ActionType action;
private SavePointType savePointType; private SavePointType savePointType;
private String savePoint; private String savePoint;
private Map<String, String> configuration = new HashMap<>(); private Map<String, String> configuration = new HashMap<>();
private Map<String, String> FlinkKubetnetsConfig = new HashMap<>(); private List<Map<String, String>> flinkConfigList = new ArrayList<>();
private static final ObjectMapper mapper = new ObjectMapper(); private static final ObjectMapper mapper = new ObjectMapper();
......
...@@ -21,14 +21,12 @@ package org.dinky.gateway.config; ...@@ -21,14 +21,12 @@ package org.dinky.gateway.config;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.gateway.enums.GatewayType; import org.dinky.gateway.enums.GatewayType;
import org.dinky.gateway.model.FlinkClusterConfig;
import org.apache.http.util.TextUtils;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
...@@ -41,25 +39,13 @@ import lombok.Setter; ...@@ -41,25 +39,13 @@ import lombok.Setter;
@Setter @Setter
public class GatewayConfig { public class GatewayConfig {
public static final String FLINK_CONFIG_PATH = "flinkConfigPath";
public static final String FLINK_LIB_PATH = "flinkLibPath";
public static final String FLINK_VERSION = "flinkVersion";
public static final String HADOOP_CONFIG_PATH = "hadoopConfigPath";
public static final String USER_JAR_PATH = "userJarPath";
public static final String USER_JAR_MAIN_APP_CLASS = "userJarMainAppClass";
public static final String USER_JAR_PARAS = "userJarParas";
public static final String FLINK_CONFIG = "flinkConfig";
public static final String KUBERNETES_CONFIG = "kubernetesConfig";
public static final String TASK_CUSTOM_CONFIG = "taskCustomConfig";
private Integer taskId; private Integer taskId;
private String[] jarPaths; private String[] jarPaths;
private GatewayType type; private GatewayType type;
private ClusterConfig clusterConfig; private ClusterConfig clusterConfig;
private FlinkConfig flinkConfig; private FlinkConfig flinkConfig;
private AppConfig appConfig; private AppConfig appConfig;
private K8sConfig kubernetesConfig;
private static final ObjectMapper mapper = new ObjectMapper();
public GatewayConfig() { public GatewayConfig() {
clusterConfig = new ClusterConfig(); clusterConfig = new ClusterConfig();
...@@ -67,84 +53,20 @@ public class GatewayConfig { ...@@ -67,84 +53,20 @@ public class GatewayConfig {
appConfig = new AppConfig(); appConfig = new AppConfig();
} }
public static GatewayConfig build(Map<String, Object> config) { public static GatewayConfig build(FlinkClusterConfig config) {
Assert.notNull(config);
GatewayConfig gatewayConfig = new GatewayConfig(); GatewayConfig gatewayConfig = new GatewayConfig();
gatewayConfig.setClusterConfig(getClusterConfig(config)); BeanUtil.copyProperties(config, gatewayConfig);
gatewayConfig.setAppConfig(getAppConfig(config)); for (Map<String, String> item : gatewayConfig.getFlinkConfig().getFlinkConfigList()) {
gatewayConfig.setFlinkConfig(getFlinkConfig(config)); if (Asserts.isNotNull(item)) {
Assert.notNull(item.get("name"), "Custer config has null item");
if (config.containsKey("taskId")) { Assert.notNull(item.get("value"), "Custer config has null item");
gatewayConfig.setTaskId(Integer.valueOf(config.get("taskId").toString())); gatewayConfig
} .getFlinkConfig()
return gatewayConfig; .getConfiguration()
} .put(item.get("name"), item.get("value"));
private static FlinkConfig getFlinkConfig(Map<String, Object> config) {
FlinkConfig fc = new FlinkConfig();
if (config.containsKey(FLINK_CONFIG)
&& Asserts.isNotNullMap((Map<String, String>) config.get(FLINK_CONFIG))) {
fc = FlinkConfig.build((Map<String, String>) config.get(FLINK_CONFIG));
}
final Map<String, String> configuration = fc.getConfiguration();
final Map<String, String> k8sConfig = fc.getFlinkKubetnetsConfig();
if (config.containsKey(KUBERNETES_CONFIG)) {
Map<String, String> kubernetesConfig =
(Map<String, String>) config.get(KUBERNETES_CONFIG);
k8sConfig.putAll(kubernetesConfig);
}
if (config.containsKey(FLINK_VERSION)) {
k8sConfig.put(FLINK_VERSION, String.valueOf(config.get(FLINK_VERSION)));
}
// at present only k8s task have this
if (config.containsKey(TASK_CUSTOM_CONFIG)) {
Map<String, Map<String, String>> taskCustomConfig =
(Map<String, Map<String, String>>) config.get(TASK_CUSTOM_CONFIG);
if (taskCustomConfig.containsKey(KUBERNETES_CONFIG)) {
k8sConfig.putAll(taskCustomConfig.get(KUBERNETES_CONFIG));
}
if (taskCustomConfig.containsKey(FLINK_CONFIG)) {
configuration.putAll(taskCustomConfig.get(FLINK_CONFIG));
} }
} }
return fc; return gatewayConfig;
}
private static AppConfig getAppConfig(Map<String, Object> config) {
AppConfig appConfig = new AppConfig();
if (config.containsKey(USER_JAR_PATH)
&& Asserts.isNotNullString((String) config.get(USER_JAR_PATH))) {
appConfig.setUserJarPath(config.get(USER_JAR_PATH).toString());
if (config.containsKey(USER_JAR_MAIN_APP_CLASS)
&& Asserts.isNotNullString((String) config.get(USER_JAR_MAIN_APP_CLASS))) {
appConfig.setUserJarMainAppClass(config.get(USER_JAR_MAIN_APP_CLASS).toString());
}
if (config.containsKey(USER_JAR_PARAS)
&& Asserts.isNotNullString((String) config.get(USER_JAR_PARAS))) {
// There may be multiple spaces between the parameter and value during user input,
// which will directly lead to a parameter passing error and needs to be eliminated
String[] temp = config.get(USER_JAR_PARAS).toString().split(" ");
appConfig.setUserJarParas(
Arrays.stream(temp)
.filter(s -> !TextUtils.isEmpty(s.trim()))
.toArray(String[]::new));
}
}
return appConfig;
}
private static ClusterConfig getClusterConfig(Map<String, Object> config) {
if (config.containsKey(HADOOP_CONFIG_PATH)) {
return ClusterConfig.build(
config.get(FLINK_CONFIG_PATH).toString(),
config.get(FLINK_LIB_PATH).toString(),
config.get(HADOOP_CONFIG_PATH).toString());
} else {
return ClusterConfig.build(String.valueOf(config.get(FLINK_CONFIG_PATH)));
}
} }
} }
/*
*
* 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.gateway.config;
import java.util.HashMap;
import java.util.Map;
import lombok.Data;
@Data
public class K8sConfig {
private Map<String, String> configuration = new HashMap<>();
private Map<String, Object> dockerConfig = new HashMap<>();
private String podTemplate;
private String jmPodTemplate;
private String tmPodTemplate;
}
...@@ -74,15 +74,7 @@ public enum GatewayType { ...@@ -74,15 +74,7 @@ public enum GatewayType {
} }
public static boolean isDeployCluster(String type) { public static boolean isDeployCluster(String type) {
switch (get(type)) { return get(type).isDeployCluster();
case YARN_APPLICATION:
case YARN_PER_JOB:
case KUBERNETES_APPLICATION:
case KUBERNETES_APPLICATION_OPERATOR:
return true;
default:
return false;
}
} }
public boolean isDeployCluster() { public boolean isDeployCluster() {
...@@ -90,6 +82,7 @@ public enum GatewayType { ...@@ -90,6 +82,7 @@ public enum GatewayType {
case "ya": case "ya":
case "ypj": case "ypj":
case "ka": case "ka":
case "kao":
return true; return true;
default: default:
return false; return false;
......
...@@ -73,7 +73,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway { ...@@ -73,7 +73,7 @@ public class KubernetesApplicationGateway extends KubernetesGateway {
new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass()); new ApplicationConfiguration(userJarParas, appConfig.getUserJarMainAppClass());
KubernetesResult result = KubernetesResult.build(getType()); KubernetesResult result = KubernetesResult.build(getType());
;
try (KubernetesClusterDescriptor kubernetesClusterDescriptor = try (KubernetesClusterDescriptor kubernetesClusterDescriptor =
new KubernetesClusterDescriptor(configuration, client)) { new KubernetesClusterDescriptor(configuration, client)) {
ClusterClientProvider<String> clusterClientProvider = ClusterClientProvider<String> clusterClientProvider =
......
...@@ -23,10 +23,13 @@ import org.dinky.assertion.Asserts; ...@@ -23,10 +23,13 @@ import org.dinky.assertion.Asserts;
import org.dinky.gateway.AbstractGateway; import org.dinky.gateway.AbstractGateway;
import org.dinky.gateway.config.FlinkConfig; import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.exception.GatewayException; import org.dinky.gateway.exception.GatewayException;
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.Configuration; import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.DeploymentOptions; import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.DeploymentOptionsInternal; import org.apache.flink.configuration.DeploymentOptionsInternal;
...@@ -38,12 +41,13 @@ import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions; ...@@ -38,12 +41,13 @@ import org.apache.flink.kubernetes.configuration.KubernetesConfigOptions;
import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient; import org.apache.flink.kubernetes.kubeclient.Fabric8FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient; import org.apache.flink.kubernetes.kubeclient.FlinkKubeClient;
import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory; import org.apache.flink.kubernetes.kubeclient.FlinkKubeClientFactory;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collections; import java.util.Collections;
import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
/** /**
...@@ -67,33 +71,45 @@ public abstract class KubernetesGateway extends AbstractGateway { ...@@ -67,33 +71,45 @@ public abstract class KubernetesGateway extends AbstractGateway {
} }
private void initConfig() { private void initConfig() {
configuration = String flinkConfigPath = config.getClusterConfig().getFlinkConfigPath();
GlobalConfiguration.loadConfiguration( if (!TextUtil.isEmpty(flinkConfigPath)) {
config.getClusterConfig().getFlinkConfigPath()); configuration = GlobalConfiguration.loadConfiguration(flinkConfigPath);
final FlinkConfig flinkConfig = config.getFlinkConfig();
if (flinkConfig.getFlinkKubetnetsConfig() != null) {
flinkConfig.getConfiguration().putAll(flinkConfig.getFlinkKubetnetsConfig());
}
if (Asserts.isNotNull(flinkConfig.getConfiguration())) {
addConfigParas(flinkConfig.getConfiguration());
} }
FlinkConfig flinkConfig = config.getFlinkConfig();
flinkConfig.getConfiguration().putAll(config.getKubernetesConfig().getConfiguration());
addConfigParas(flinkConfig.getConfiguration());
configuration.set(DeploymentOptions.TARGET, getType().getLongValue()); configuration.set(DeploymentOptions.TARGET, getType().getLongValue());
if (Asserts.isNotNullString(flinkConfig.getSavePoint())) { configuration.set(KubernetesConfigOptions.CLUSTER_ID, flinkConfig.getJobName());
configuration.setString(
SavepointConfigOptions.SAVEPOINT_PATH, flinkConfig.getSavePoint());
}
if (Asserts.isNotNullString(flinkConfig.getJobName())) { K8sConfig k8sConfig = config.getKubernetesConfig();
configuration.set(KubernetesConfigOptions.CLUSTER_ID, flinkConfig.getJobName()); preparPodTemplate(
} k8sConfig.getPodTemplate(), KubernetesConfigOptions.KUBERNETES_POD_TEMPLATE);
preparPodTemplate(
k8sConfig.getJmPodTemplate(), KubernetesConfigOptions.JOB_MANAGER_POD_TEMPLATE);
preparPodTemplate(
k8sConfig.getTmPodTemplate(), KubernetesConfigOptions.TASK_MANAGER_POD_TEMPLATE);
if (getType().isApplicationMode()) { if (getType().isApplicationMode()) {
resetCheckpointInApplicationMode(); resetCheckpointInApplicationMode();
} }
} }
public void preparPodTemplate(String podTemplate, ConfigOption<String> option) {
if (TextUtil.isEmpty(podTemplate)) {
return;
}
String filePath =
String.format(
"%s/tmp/Kubernets/%s.yaml",
System.getProperty("user.dir"), config.getFlinkConfig().getJobName());
if (FileUtil.exist(filePath)) {
Assert.isTrue(FileUtil.del(filePath));
}
FileUtil.writeUtf8String(podTemplate, filePath);
configuration.set(option, filePath);
}
private void initKubeClient() { private void initKubeClient() {
client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client"); client = FlinkKubeClientFactory.getInstance().fromConfiguration(configuration, "client");
} }
......
...@@ -22,6 +22,8 @@ package org.dinky.gateway.kubernetes.operator; ...@@ -22,6 +22,8 @@ package org.dinky.gateway.kubernetes.operator;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.enums.JobStatus; import org.dinky.data.enums.JobStatus;
import org.dinky.gateway.AbstractGateway; import org.dinky.gateway.AbstractGateway;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.enums.UpgradeMode; import org.dinky.gateway.enums.UpgradeMode;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec; import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec;
import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec.Resource; import org.dinky.gateway.kubernetes.operator.api.AbstractPodSpec.Resource;
...@@ -32,6 +34,9 @@ import org.dinky.gateway.result.SavePointResult; ...@@ -32,6 +34,9 @@ import org.dinky.gateway.result.SavePointResult;
import org.dinky.gateway.result.TestResult; import org.dinky.gateway.result.TestResult;
import org.dinky.process.context.ProcessContextHolder; import org.dinky.process.context.ProcessContextHolder;
import org.dinky.process.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.utils.TextUtil;
import org.apache.flink.configuration.CoreOptions;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.InputStream; import java.io.InputStream;
...@@ -53,8 +58,9 @@ import lombok.EqualsAndHashCode; ...@@ -53,8 +58,9 @@ import lombok.EqualsAndHashCode;
@Data @Data
public abstract class KubernetsOperatorGateway extends AbstractGateway { public abstract class KubernetsOperatorGateway extends AbstractGateway {
private Map<String, String> submitConfiguration; private Map<String, String> kubernetsConfiguration;
private Map<String, String> flinkConfig; private K8sConfig k8sConfig;
private FlinkConfig flinkConfig;
private FlinkDeployment flinkDeployment = new FlinkDeployment(); private FlinkDeployment flinkDeployment = new FlinkDeployment();
private FlinkDeploymentSpec flinkDeploymentSpec = new FlinkDeploymentSpec(); private FlinkDeploymentSpec flinkDeploymentSpec = new FlinkDeploymentSpec();
private KubernetesClient kubernetesClient; private KubernetesClient kubernetesClient;
...@@ -64,8 +70,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -64,8 +70,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
@Override @Override
protected void init() { protected void init() {
submitConfiguration = config.getFlinkConfig().getFlinkKubetnetsConfig(); kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
flinkConfig = config.getFlinkConfig().getConfiguration(); flinkConfig = config.getFlinkConfig();
k8sConfig = config.getKubernetesConfig();
kubernetesClient = new DefaultKubernetesClient(); kubernetesClient = new DefaultKubernetesClient();
initBase(); initBase();
initMetadata(); initMetadata();
...@@ -77,8 +84,8 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -77,8 +84,8 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
@Override @Override
public TestResult test() { public TestResult test() {
submitConfiguration = config.getFlinkConfig().getFlinkKubetnetsConfig(); kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
flinkConfig = config.getFlinkConfig().getConfiguration(); flinkConfig = config.getFlinkConfig();
config.getFlinkConfig().setJobName("test"); config.getFlinkConfig().setJobName("test");
kubernetesClient = new DefaultKubernetesClient(); kubernetesClient = new DefaultKubernetesClient();
initBase(); initBase();
...@@ -92,7 +99,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -92,7 +99,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
@Override @Override
public boolean onJobFinishCallback(String status) { public boolean onJobFinishCallback(String status) {
submitConfiguration = config.getFlinkConfig().getFlinkKubetnetsConfig(); kubernetsConfiguration = config.getKubernetesConfig().getConfiguration();
kubernetesClient = new DefaultKubernetesClient(); kubernetesClient = new DefaultKubernetesClient();
String jobName = config.getFlinkConfig().getJobName(); String jobName = config.getFlinkConfig().getJobName();
...@@ -117,7 +124,8 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -117,7 +124,8 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
String jarMainClass = config.getAppConfig().getUserJarMainAppClass(); String jarMainClass = config.getAppConfig().getUserJarMainAppClass();
String userJarPath = config.getAppConfig().getUserJarPath(); String userJarPath = config.getAppConfig().getUserJarPath();
String[] userJarParas = config.getAppConfig().getUserJarParas(); String[] userJarParas = config.getAppConfig().getUserJarParas();
String parallelism = flinkConfig.get("parallelism.default"); String parallelism =
flinkConfig.getConfiguration().get(CoreOptions.DEFAULT_PARALLELISM.key());
logger.info( logger.info(
"\nThe app config is : \njarMainClass:{}\n userJarPath:{}\n userJarParas:{}\n ", "\nThe app config is : \njarMainClass:{}\n userJarPath:{}\n userJarParas:{}\n ",
...@@ -160,42 +168,40 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -160,42 +168,40 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
Pod defaultPod; Pod defaultPod;
AbstractPodSpec jobManagerSpec = new AbstractPodSpec(); AbstractPodSpec jobManagerSpec = new AbstractPodSpec();
AbstractPodSpec taskManagerSpec = new AbstractPodSpec(); AbstractPodSpec taskManagerSpec = new AbstractPodSpec();
String jbcpu = submitConfiguration.getOrDefault("kubernetes.jobmanager.cpu", "1"); String jbcpu = kubernetsConfiguration.getOrDefault("kubernetes.jobmanager.cpu", "1");
String jbmem = flinkConfig.getOrDefault("jobmanager.memory.process.size", "1G"); String jbmem =
flinkConfig.getConfiguration().getOrDefault("jobmanager.memory.process.size", "1G");
logger.info("jobmanager resource is : cpu-->{}, mem-->{}", jbcpu, jbmem); logger.info("jobmanager resource is : cpu-->{}, mem-->{}", jbcpu, jbmem);
process.info(String.format("jobmanager resource is : cpu-->%s, mem-->%s", jbcpu, jbmem)); process.info(String.format("jobmanager resource is : cpu-->%s, mem-->%s", jbcpu, jbmem));
jobManagerSpec.setResource(new Resource(Double.parseDouble(jbcpu), jbmem)); jobManagerSpec.setResource(new Resource(Double.parseDouble(jbcpu), jbmem));
String tmcpu = submitConfiguration.getOrDefault("kubernetes.taskmanager.cpu", "1"); String tmcpu = kubernetsConfiguration.getOrDefault("kubernetes.taskmanager.cpu", "1");
String tmmem = flinkConfig.getOrDefault("taskmanager.memory.process.size", "1G"); String tmmem =
flinkConfig
.getConfiguration()
.getOrDefault("taskmanager.memory.process.size", "1G");
logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem); logger.info("taskmanager resource is : cpu-->{}, mem-->{}", tmcpu, tmmem);
process.info(String.format("taskmanager resource is : cpu-->%s, mem-->%s", tmcpu, tmmem)); process.info(String.format("taskmanager resource is : cpu-->%s, mem-->%s", tmcpu, tmmem));
taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem)); taskManagerSpec.setResource(new Resource(Double.parseDouble(tmcpu), tmmem));
if (submitConfiguration.containsKey("kubernetes.pod-template")) { if (!TextUtil.isEmpty(k8sConfig.getPodTemplate())) {
InputStream inputStream = InputStream inputStream =
new ByteArrayInputStream( new ByteArrayInputStream(
submitConfiguration k8sConfig.getPodTemplate().getBytes(StandardCharsets.UTF_8));
.get("kubernetes.pod-template")
.getBytes(StandardCharsets.UTF_8));
defaultPod = kubernetesClient.pods().load(inputStream).get(); defaultPod = kubernetesClient.pods().load(inputStream).get();
flinkDeploymentSpec.setPodTemplate(defaultPod); flinkDeploymentSpec.setPodTemplate(defaultPod);
} }
if (submitConfiguration.containsKey("kubernetes.pod-template.jobmanager")) { if (!TextUtil.isEmpty(k8sConfig.getJmPodTemplate())) {
InputStream inputStream = InputStream inputStream =
new ByteArrayInputStream( new ByteArrayInputStream(
submitConfiguration k8sConfig.getJmPodTemplate().getBytes(StandardCharsets.UTF_8));
.get("kubernetes.pod-template.jobmanager")
.getBytes(StandardCharsets.UTF_8));
Pod pod = kubernetesClient.pods().load(inputStream).get(); Pod pod = kubernetesClient.pods().load(inputStream).get();
jobManagerSpec.setPodTemplate(pod); jobManagerSpec.setPodTemplate(pod);
} }
if (submitConfiguration.containsKey("kubernetes.pod-template.taskmanager")) { if (!TextUtil.isEmpty(k8sConfig.getTmPodTemplate())) {
InputStream inputStream = InputStream inputStream =
new ByteArrayInputStream( new ByteArrayInputStream(
submitConfiguration k8sConfig.getTmPodTemplate().getBytes(StandardCharsets.UTF_8));
.get("kubernetes.pod-template.taskmanager")
.getBytes(StandardCharsets.UTF_8));
Pod pod = kubernetesClient.pods().load(inputStream).get(); Pod pod = kubernetesClient.pods().load(inputStream).get();
taskManagerSpec.setPodTemplate(pod); taskManagerSpec.setPodTemplate(pod);
} }
...@@ -204,9 +210,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -204,9 +210,9 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
} }
private void initSpec() { private void initSpec() {
String flinkVersion = submitConfiguration.get("flinkVersion"); String flinkVersion = flinkConfig.getFlinkVersion();
String image = submitConfiguration.get("kubernetes.container.image"); String image = kubernetsConfiguration.get("kubernetes.container.image");
String serviceAccount = submitConfiguration.get("kubernetes.service.account"); String serviceAccount = kubernetsConfiguration.get("kubernetes.service.account");
logger.info("\nflinkVersion is : {} \n image is : {}", flinkVersion, image); logger.info("\nflinkVersion is : {} \n image is : {}", flinkVersion, image);
process.info(String.format("\nflinkVersion is : %s \n image is : %s", flinkVersion, image)); process.info(String.format("\nflinkVersion is : %s \n image is : %s", flinkVersion, image));
...@@ -220,7 +226,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -220,7 +226,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
flinkDeploymentSpec.setImage(image); flinkDeploymentSpec.setImage(image);
flinkDeploymentSpec.setFlinkConfiguration(flinkConfig); flinkDeploymentSpec.setFlinkConfiguration(flinkConfig.getConfiguration());
flinkDeployment.setSpec(flinkDeploymentSpec); flinkDeployment.setSpec(flinkDeploymentSpec);
if (Asserts.isNotNull(serviceAccount)) { if (Asserts.isNotNull(serviceAccount)) {
...@@ -242,7 +248,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway { ...@@ -242,7 +248,7 @@ public abstract class KubernetsOperatorGateway extends AbstractGateway {
private void initMetadata() { private void initMetadata() {
String jobName = config.getFlinkConfig().getJobName(); String jobName = config.getFlinkConfig().getJobName();
String nameSpace = submitConfiguration.get("kubernetes.namespace"); String nameSpace = kubernetsConfiguration.get("kubernetes.namespace");
logger.info("\njobName is :{} \n namespce is : {}", jobName, nameSpace); logger.info("\njobName is :{} \n namespce is : {}", jobName, nameSpace);
process.info(String.format("\njobName is :%s \n namespce is : %s", jobName, nameSpace)); process.info(String.format("\njobName is :%s \n namespce is : %s", jobName, nameSpace));
......
...@@ -17,9 +17,13 @@ ...@@ -17,9 +17,13 @@
* *
*/ */
package org.dinky.data.model; package org.dinky.gateway.model;
import java.util.Map; import org.dinky.gateway.config.AppConfig;
import org.dinky.gateway.config.ClusterConfig;
import org.dinky.gateway.config.FlinkConfig;
import org.dinky.gateway.config.K8sConfig;
import org.dinky.gateway.enums.GatewayType;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
...@@ -27,21 +31,10 @@ import lombok.Setter; ...@@ -27,21 +31,10 @@ import lombok.Setter;
/** @since */ /** @since */
@Getter @Getter
@Setter @Setter
public class FlinkClusterConfiguration { public class FlinkClusterConfig {
private Type type; private GatewayType type;
private String hadoopConfigPath; private ClusterConfig clusterConfig;
private String flinkConfigPath; private FlinkConfig flinkConfig;
private String flinkLibPath; private AppConfig appConfig;
private String userJarPath; private K8sConfig kubernetesConfig;
private String flinkVersion;
Map<String, String> flinkConfig;
Map<String, String> kubernetesConfig;
public enum Type {
//
Yarn,
Kubernetes,
KubernetesOperator;
}
} }
...@@ -37,7 +37,6 @@ import org.apache.flink.client.program.ClusterClient; ...@@ -37,7 +37,6 @@ import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.configuration.DeploymentOptions; import org.apache.flink.configuration.DeploymentOptions;
import org.apache.flink.configuration.GlobalConfiguration; import org.apache.flink.configuration.GlobalConfiguration;
import org.apache.flink.configuration.SecurityOptions; import org.apache.flink.configuration.SecurityOptions;
import org.apache.flink.runtime.jobgraph.SavepointConfigOptions;
import org.apache.flink.runtime.security.SecurityConfiguration; import org.apache.flink.runtime.security.SecurityConfiguration;
import org.apache.flink.runtime.security.SecurityUtils; import org.apache.flink.runtime.security.SecurityUtils;
import org.apache.flink.yarn.YarnClientYarnClusterInformationRetriever; import org.apache.flink.yarn.YarnClientYarnClusterInformationRetriever;
...@@ -99,10 +98,6 @@ public abstract class YarnGateway extends AbstractGateway { ...@@ -99,10 +98,6 @@ public abstract class YarnGateway extends AbstractGateway {
} }
configuration.set(DeploymentOptions.TARGET, getType().getLongValue()); configuration.set(DeploymentOptions.TARGET, getType().getLongValue());
final String savePoint = flinkConfig.getSavePoint();
if (Asserts.isNotNullString(savePoint)) {
configuration.setString(SavepointConfigOptions.SAVEPOINT_PATH, savePoint);
}
configuration.set( configuration.set(
YarnConfigOptions.PROVIDED_LIB_DIRS, YarnConfigOptions.PROVIDED_LIB_DIRS,
......
...@@ -28,7 +28,7 @@ const ApplicationConfig = () => { ...@@ -28,7 +28,7 @@ const ApplicationConfig = () => {
<ProFormGroup labelLayout={'inline'}> <ProFormGroup labelLayout={'inline'}>
<ProFormText <ProFormText
width={'xl'} width={'xl'}
name={["configJson","userJarPath"]} name={["configJson",'appConfig',"userJarPath"]}
placeholder={l('rc.cc.sqlSubmitJarPathHelp')} placeholder={l('rc.cc.sqlSubmitJarPathHelp')}
label={l('rc.cc.sqlSubmitJarPath')} label={l('rc.cc.sqlSubmitJarPath')}
tooltip={l('rc.cc.sqlSubmitJarPathHelp')} tooltip={l('rc.cc.sqlSubmitJarPathHelp')}
......
...@@ -48,13 +48,13 @@ const FlinkK8s = (props: { type: string, value: any }) => { ...@@ -48,13 +48,13 @@ const FlinkK8s = (props: { type: string, value: any }) => {
<ProFormText <ProFormText
tooltip={item.tooltip} tooltip={item.tooltip}
key={item.name} key={item.name}
name={['configJson', 'kubernetesConfig', item.name]} name={['configJson', 'kubernetesConfig','configuration', item.name]}
label={item.label} label={item.label}
width={250} width={250}
placeholder={item.placeholder}/> placeholder={item.placeholder}/>
)} )}
<ProFormList <ProFormList
name={['configJson', 'flinkConfigList']} name={['configJson','flinkConfig', 'flinkConfigList']}
copyIconProps={false} copyIconProps={false}
deleteIconProps={{tooltipText: l('rc.cc.deleteConfig'),}} deleteIconProps={{tooltipText: l('rc.cc.deleteConfig'),}}
creatorButtonProps={{style: {width: '32vw'}, creatorButtonText: l('rc.cc.addConfig'),}} creatorButtonProps={{style: {width: '32vw'}, creatorButtonText: l('rc.cc.addConfig'),}}
...@@ -72,24 +72,24 @@ const FlinkK8s = (props: { type: string, value: any }) => { ...@@ -72,24 +72,24 @@ const FlinkK8s = (props: { type: string, value: any }) => {
key: "defaultPodTemplate", key: "defaultPodTemplate",
label: <TagAlignCenter>Default Pod Template</TagAlignCenter>, label: <TagAlignCenter>Default Pod Template</TagAlignCenter>,
children: children:
<ProFormItem key="dpe" name={['configJson', 'podTemplate']}> <ProFormItem key="dpe" name={['configJson', 'kubernetesConfig', 'podTemplate']}>
<CodeEdit {...CodeEditProps} code={value.configJson.podTemplate}/> <CodeEdit {...CodeEditProps} code={value.configJson.kubernetesConfig.podTemplate}/>
</ProFormItem> </ProFormItem>
}, },
{ {
key: "JMPodTemplate", key: "JMPodTemplate",
label: <TagAlignCenter>JM Pod Template</TagAlignCenter>, label: <TagAlignCenter>JM Pod Template</TagAlignCenter>,
children: children:
<ProFormItem key="jmdpe" name={['configJson', 'JMpodTemplate']}> <ProFormItem key="jmdpe" name={['configJson', 'kubernetesConfig', 'jmPodTemplate']}>
<CodeEdit {...CodeEditProps} code={value.configJson.JMpodTemplate}/> <CodeEdit {...CodeEditProps} code={value.configJson.kubernetesConfig.jmPodTemplate}/>
</ProFormItem> </ProFormItem>
}, },
{ {
key: "TMPodTemplate", key: "TMPodTemplate",
label: <TagAlignCenter>TM Pod Template</TagAlignCenter>, label: <TagAlignCenter>TM Pod Template</TagAlignCenter>,
children: children:
<ProFormItem key="tmdpe" name={['configJson', 'TMpodTemplate']}> <ProFormItem key="tmdpe" name={['configJson', 'kubernetesConfig', 'tmPodTemplate']}>
<CodeEdit {...CodeEditProps} code={value.configJson.TMpodTemplate}/> <CodeEdit {...CodeEditProps} code={value.configJson.kubernetesConfig.tmPodTemplate}/>
</ProFormItem> </ProFormItem>
}, },
]; ];
...@@ -101,7 +101,7 @@ const FlinkK8s = (props: { type: string, value: any }) => { ...@@ -101,7 +101,7 @@ const FlinkK8s = (props: { type: string, value: any }) => {
<ProFormGroup> <ProFormGroup>
{(type && type === ClusterType.KUBERNETES_NATIVE) && {(type && type === ClusterType.KUBERNETES_NATIVE) &&
<ProFormSelect <ProFormSelect
name={['configJson', 'kubernetesConfig', 'kubernetes.rest-service.exposed.type']} name={['configJson', 'kubernetesConfig','configuration', 'kubernetes.rest-service.exposed.type']}
label={l('rc.cc.k8s.exposed')} label={l('rc.cc.k8s.exposed')}
tooltip={l('rc.cc.k8s.exposedHelp')} tooltip={l('rc.cc.k8s.exposedHelp')}
placeholder={l('rc.cc.k8s.exposedHelp')} placeholder={l('rc.cc.k8s.exposedHelp')}
...@@ -110,7 +110,7 @@ const FlinkK8s = (props: { type: string, value: any }) => { ...@@ -110,7 +110,7 @@ const FlinkK8s = (props: { type: string, value: any }) => {
/>} />}
{(type && type === ClusterType.KUBERNETES_OPERATOR) && {(type && type === ClusterType.KUBERNETES_OPERATOR) &&
<ProFormSelect <ProFormSelect
name={['configJson', 'flinkVersion']} name={['configJson','flinkConfig', 'flinkVersion']}
label={l('rc.cc.k8sOp.version')} label={l('rc.cc.k8sOp.version')}
width={250} width={250}
placeholder={l('rc.cc.k8sOp.versionHelp')} placeholder={l('rc.cc.k8sOp.versionHelp')}
......
...@@ -28,7 +28,7 @@ const HighPriorityConfig = () => { ...@@ -28,7 +28,7 @@ const HighPriorityConfig = () => {
const renderHighPriorityConfig = () => { const renderHighPriorityConfig = () => {
return FLINK_CONFIG_LIST.map(item => <> return FLINK_CONFIG_LIST.map(item => <>
<ProFormText <ProFormText
name={['configJson', 'flinkConfig', item.name]} name={['configJson', 'flinkConfig','configuration', item.name]}
label={item.label} label={item.label}
width={400} width={400}
placeholder={item.placeholder} placeholder={item.placeholder}
...@@ -41,6 +41,11 @@ const HighPriorityConfig = () => { ...@@ -41,6 +41,11 @@ const HighPriorityConfig = () => {
<Divider>{l('rc.cc.defineConfig')}</Divider> <Divider>{l('rc.cc.defineConfig')}</Divider>
<ProFormGroup direction={'horizontal'} align={'baseline'}> <ProFormGroup direction={'horizontal'} align={'baseline'}>
{renderHighPriorityConfig()} {renderHighPriorityConfig()}
<ProFormText
name={['configJson','clusterConfig', 'flinkConfigPath']}
label={"Flink Conf Yaml Path"}
width={400}
/>
</ProFormGroup> </ProFormGroup>
</> </>
} }
......
...@@ -19,11 +19,11 @@ ...@@ -19,11 +19,11 @@
export const enum ClusterType { export const enum ClusterType {
STANDALONE = 'Standalone', STANDALONE = 'standalone',
YARN = 'Yarn', YARN = 'yarn-application',
YARN_SESSION = 'Yarn Session', YARN_SESSION = 'yarn-session',
KUBERNETES_SESSION = 'Kubernetes Session', KUBERNETES_SESSION = 'kubernetes-session',
KUBERNETES_NATIVE = 'Kubernetes', KUBERNETES_NATIVE = 'kubernetes-application',
KUBERNETES_OPERATOR = 'KubernetesOperator', KUBERNETES_OPERATOR = 'kubernetes-application-operator',
}; };
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