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

Refactor task submit (#2368)

* fix dag npe * refactor task submit * merge dev * merge dev and formate code * fix some problem * merge dev * remove useSession * formate code * formate code * fix task vesion time * change task version create * formate code
parent a76beb7d
......@@ -23,7 +23,6 @@ import org.dinky.assertion.Asserts;
import org.dinky.data.annotation.Log;
import org.dinky.data.dto.StudioCADTO;
import org.dinky.data.dto.StudioDDLDTO;
import org.dinky.data.dto.StudioExecuteDTO;
import org.dinky.data.dto.StudioMetaStoreDTO;
import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status;
......@@ -33,9 +32,7 @@ import org.dinky.data.model.Schema;
import org.dinky.data.result.IResult;
import org.dinky.data.result.Result;
import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.lineage.LineageResult;
import org.dinky.job.JobResult;
import org.dinky.metadata.result.JdbcSelectResult;
import org.dinky.service.StudioService;
......@@ -49,7 +46,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
......@@ -72,75 +68,6 @@ public class StudioController {
private final StudioService studioService;
/** 执行Sql */
@PostMapping("/executeSql")
@ApiOperation("Execute Sql")
@Log(title = "Execute Sql", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "studioExecuteDTO",
value = "Execute Sql",
required = true,
dataType = "StudioExecuteDTO",
paramType = "body")
public Result<JobResult> executeSql(@RequestBody StudioExecuteDTO studioExecuteDTO) {
try {
JobResult jobResult = studioService.executeSql(studioExecuteDTO);
return Result.succeed(jobResult, Status.EXECUTE_SUCCESS);
} catch (Exception ex) {
JobResult jobResult = new JobResult();
jobResult.setJobConfig(studioExecuteDTO.getJobConfig());
jobResult.setSuccess(false);
jobResult.setStatement(studioExecuteDTO.getStatement());
jobResult.setError(ex.toString());
return Result.failed(jobResult, ex.toString());
}
}
/** 解释Sql */
@PostMapping("/explainSql")
@ApiOperation("Explain Sql")
@ApiImplicitParam(
name = "studioExecuteDTO",
value = "Explain Sql",
required = true,
dataType = "StudioExecuteDTO",
paramType = "body")
public Result<List<SqlExplainResult>> explainSql(@RequestBody StudioExecuteDTO studioExecuteDTO) {
return Result.succeed(studioService.explainSql(studioExecuteDTO), "解释成功");
}
/** 获取执行图 */
@PostMapping("/getStreamGraph")
@ApiOperation("Get Stream Graph")
@ApiImplicitParam(
name = "studioExecuteDTO",
value = "Get Stream Graph",
required = true,
dataType = "StudioExecuteDTO",
paramType = "body")
public Result<ObjectNode> getStreamGraph(@RequestBody StudioExecuteDTO studioExecuteDTO) {
return Result.succeed(studioService.getStreamGraph(studioExecuteDTO));
}
/** 获取sql的jobplan */
@PostMapping("/getJobPlan")
@ApiOperation("Get Job Execute Plan")
@ApiImplicitParam(
name = "studioExecuteDTO",
value = "Get Job Execute Plan",
required = true,
dataType = "StudioExecuteDTO",
paramType = "body")
public Result<ObjectNode> getJobPlan(@RequestBody StudioExecuteDTO studioExecuteDTO) {
try {
return Result.succeed(studioService.getJobPlan(studioExecuteDTO));
} catch (Exception e) {
e.printStackTrace();
return Result.failed(e.getMessage());
}
}
/** 进行DDL操作 */
@PostMapping("/executeDDL")
@ApiOperation("Execute SQL DDL")
@Log(title = "Execute SQL DDL", businessType = BusinessType.EXECUTE)
......@@ -162,6 +89,7 @@ public class StudioController {
public Result<SelectResult> getJobData(@RequestParam String jobId) {
return Result.succeed(studioService.getJobData(jobId));
}
/** 根据jobId获取数据 */
@GetMapping("/getCommonSqlData")
@ApiOperation("Get Common Sql Data")
......@@ -203,54 +131,6 @@ public class StudioController {
return Result.succeed(jobs.toArray(new JsonNode[0]));
}
/** 停止任务 */
@GetMapping("/cancel")
@ApiOperation("Cancel Flink Job")
@Log(title = "Cancel Flink Job", businessType = BusinessType.REMOTE_OPERATION)
@ApiImplicitParams({
@ApiImplicitParam(
name = "clusterId",
value = "clusterId",
required = true,
dataType = "Integer",
paramType = "query"),
@ApiImplicitParam(name = "jobId", value = "jobId", required = true, dataType = "String", paramType = "query")
})
public Result<Boolean> cancelFlinkJob(@RequestParam Integer clusterId, @RequestParam String jobId) {
return Result.succeed(studioService.cancelFlinkJob(clusterId, jobId), Status.STOP_SUCCESS);
}
/** savepoint */
@GetMapping("/savepoint")
@ApiOperation("Savepoint Trigger")
@Log(title = "Savepoint Trigger", businessType = BusinessType.REMOTE_OPERATION)
@ApiImplicitParams({
@ApiImplicitParam(
name = "clusterId",
value = "clusterId",
required = true,
dataType = "Integer",
paramType = "query"),
@ApiImplicitParam(name = "jobId", value = "jobId", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(
name = "savePointType",
value = "savePointType",
required = true,
dataType = "String",
paramType = "query"),
@ApiImplicitParam(name = "name", value = "name", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "taskId", value = "taskId", required = true, dataType = "Integer", paramType = "query")
})
public Result<Boolean> savepointTrigger(
@RequestParam Integer clusterId,
@RequestParam String jobId,
@RequestParam String savePointType,
@RequestParam String name,
@RequestParam Integer taskId) {
return Result.succeed(
studioService.savepointTrigger(taskId, clusterId, jobId, savePointType, name), "savepoint 成功");
}
/** 获取 Meta Store Catalog 和 Database */
@PostMapping("/getMSCatalogs")
@ApiOperation("Get Catalog List")
......
......@@ -21,6 +21,7 @@ package org.dinky.data.dto;
import org.dinky.assertion.Asserts;
import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.job.JobConfig;
import java.util.Map;
......@@ -119,25 +120,23 @@ public class APIExecuteSqlDTO extends AbstractStatementDTO {
public JobConfig getJobConfig() {
int savePointStrategy = Asserts.isNotNullString(savePointPath) ? 3 : 0;
return new JobConfig(
type,
useResult,
useChangeLog,
useAutoCancel,
false,
null,
true,
address,
jobName,
isFragment(),
useStatementSet,
maxRowNum,
checkPoint,
parallelism,
savePointStrategy,
savePointPath,
configuration,
gatewayConfig);
return JobConfig.builder()
.type(type)
.useResult(useResult)
.useChangeLog(useChangeLog)
.useAutoCancel(useAutoCancel)
.useRemote(true)
.address(address)
.jobName(jobName)
.fragment(isFragment())
.statementSet(useStatementSet)
.maxRowNum(maxRowNum)
.checkpoint(checkPoint)
.parallelism(parallelism)
.savePointStrategy(SavePointStrategy.get(savePointStrategy))
.savePointPath(savePointPath)
.configJson(configuration)
.gatewayConfig(gatewayConfig)
.build();
}
}
......@@ -19,6 +19,7 @@
package org.dinky.data.dto;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.job.JobConfig;
import java.util.Map;
......@@ -55,6 +56,13 @@ public class APIExplainSqlDTO extends AbstractStatementDTO {
private Map<String, String> configuration;
public JobConfig getJobConfig() {
return new JobConfig("local", false, false, isFragment(), useStatementSet, parallelism, configuration);
return JobConfig.builder()
.type(GatewayType.LOCAL.getLongValue())
.useRemote(false)
.fragment(isFragment())
.statementSet(useStatementSet)
.parallelism(parallelism)
.configJson(configuration)
.build();
}
}
......@@ -23,6 +23,7 @@ import java.util.Map;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* AbstractStatementDTO
......@@ -30,6 +31,7 @@ import io.swagger.annotations.ApiModelProperty;
* @since 2021/12/29
*/
@ApiModel(value = "AbstractStatementDTO", description = "Abstract Statement Data Transfer Object")
@Data
public class AbstractStatementDTO {
@ApiModelProperty(value = "Statement", dataType = "String", example = "SELECT * FROM table", notes = "SQL语句")
......@@ -47,36 +49,4 @@ public class AbstractStatementDTO {
example = "{\"key\": \"value\"}",
notes = "变量集合")
private Map<String, String> variables;
public String getStatement() {
return statement;
}
public void setStatement(String statement) {
this.statement = statement;
}
public Integer getEnvId() {
return envId;
}
public void setEnvId(Integer envId) {
this.envId = envId;
}
public boolean isFragment() {
return fragment;
}
public void setFragment(boolean fragment) {
this.fragment = fragment;
}
public Map<String, String> getVariables() {
return variables;
}
public void setVariables(Map<String, String> variables) {
this.variables = variables;
}
}
......@@ -21,6 +21,7 @@ package org.dinky.data.dto;
import org.dinky.job.JobConfig;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
......@@ -85,6 +86,8 @@ public class StudioDDLDTO {
private Integer maxRowNum = 10000;
public JobConfig getJobConfig() {
return new JobConfig(type, useResult, useSession, session, useRemote, clusterId, maxRowNum);
JobConfig jobConfig = new JobConfig();
BeanUtil.copyProperties(this, jobConfig);
return jobConfig;
}
}
......@@ -65,27 +65,15 @@ public class StudioMetaStoreDTO extends AbstractStatementDTO {
private Integer databaseId;
public JobConfig getJobConfig() {
return new JobConfig(
GatewayType.LOCAL.getLongValue(),
true,
false,
false,
false,
null,
null,
null,
null,
null,
null,
isFragment(),
false,
false,
0,
null,
null,
null,
null,
null,
null);
return JobConfig.builder()
.type(GatewayType.LOCAL.getLongValue())
.useResult(true)
.useChangeLog(false)
.useAutoCancel(false)
.fragment(isFragment())
.statementSet(false)
.batchModel(false)
.maxRowNum(0)
.build();
}
}
/*
*
* 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.data.exception;
public class NotSupportExplainExcepition extends SqlExplainExcepition {
public NotSupportExplainExcepition(String message) {
super(message);
}
}
/*
*
* 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.data.exception;
import org.dinky.process.exception.ExcuteException;
public class SqlExplainExcepition extends ExcuteException {
public SqlExplainExcepition(String message) {
super(message);
}
}
/*
*
* 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.data.exception;
import org.dinky.process.exception.ExcuteException;
public class TaskNotDoneException extends ExcuteException {
public TaskNotDoneException(String message) {
super(message);
}
}
......@@ -19,23 +19,13 @@
package org.dinky.data.model;
import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect;
import org.dinky.data.typehandler.TaskExtConfigTypeHandler;
import org.dinky.job.JobConfig;
import org.dinky.mybatis.model.SuperEntity;
import org.apache.ibatis.type.JdbcType;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
......@@ -73,11 +63,7 @@ public class Task extends SuperEntity<Task> {
@ApiModelProperty(value = "Check Point", dataType = "Integer", example = "1", notes = "Check point for the task")
private Integer checkPoint;
@ApiModelProperty(
value = "Save Point Strategy",
dataType = "Integer",
example = "2",
notes = "Save point strategy for the task")
@ApiModelProperty(value = "Save point strategy", dataType = "SavePointStrategy", notes = "Save point strategy")
private Integer savePointStrategy;
@ApiModelProperty(value = "Save Point Path", dataType = "String", notes = "Save point path for the task")
......@@ -149,6 +135,13 @@ public class Task extends SuperEntity<Task> {
notes = "ID of the alert group associated with the task")
private Integer alertGroupId;
@ApiModelProperty(
value = "Configuration JSON",
dataType = "TaskExtConfig",
notes = "Extended configuration in JSON format for the task")
@TableField(typeHandler = TaskExtConfigTypeHandler.class, jdbcType = JdbcType.VARCHAR)
private TaskExtConfig configJson;
@ApiModelProperty(value = "Note", dataType = "String", notes = "Additional notes for the task")
private String note;
......@@ -170,126 +163,5 @@ public class Task extends SuperEntity<Task> {
private Integer versionId;
@ApiModelProperty(value = "Statement", dataType = "String", notes = "SQL statement for the task")
@TableField(exist = false)
private String statement;
@ApiModelProperty(value = "Cluster Name", dataType = "String", notes = "Name of the associated cluster")
@TableField(exist = false)
private String clusterName;
@ApiModelProperty(
value = "Save Points",
dataType = "List<Savepoints>",
notes = "List of save points associated with the task")
@TableField(exist = false)
private List<Savepoints> savePoints;
@ApiModelProperty(
value = "Configuration JSON",
dataType = "TaskExtConfig",
notes = "Extended configuration in JSON format for the task")
@TableField(typeHandler = TaskExtConfigTypeHandler.class, jdbcType = JdbcType.VARCHAR)
private TaskExtConfig configJson;
@ApiModelProperty(value = "Path", dataType = "String", notes = "Path associated with the task")
@TableField(exist = false)
private String path;
@ApiModelProperty(value = "JAR Name", dataType = "String", notes = "Name of the associated JAR")
@TableField(exist = false)
private String jarName;
@ApiModelProperty(
value = "Cluster Configuration Name",
dataType = "String",
notes = "Name of the associated cluster configuration")
@TableField(exist = false)
private String clusterConfigurationName;
@ApiModelProperty(value = "Database Name", dataType = "String", notes = "Name of the associated database")
@TableField(exist = false)
private String databaseName;
@ApiModelProperty(value = "Environment Name", dataType = "String", notes = "Name of the associated environment")
@TableField(exist = false)
private String envName;
@ApiModelProperty(value = "Alert Group Name", dataType = "String", notes = "Name of the associated alert group")
@TableField(exist = false)
private String alertGroupName;
public JobConfig buildSubmitConfig() {
boolean useRemote = clusterId != null && clusterId != 0;
List<ConfigItem> extCustomConfig = this.configJson.getCustomConfig();
Map<String, String> parsedConfig =
extCustomConfig.stream().collect(Collectors.toMap(ConfigItem::getKey, ConfigItem::getValue));
int jid = Asserts.isNull(jarId) ? 0 : jarId;
boolean fg = Asserts.isNotNull(fragment) && fragment;
boolean sts = Asserts.isNotNull(statementSet) && statementSet;
return new JobConfig(
type,
step,
false,
false,
useRemote,
clusterId,
clusterConfigurationId,
jid,
getId(),
getName(),
fg,
sts,
batchModel,
checkPoint,
parallelism,
savePointStrategy,
savePointPath,
parsedConfig,
isJarTask());
}
/**
* 根据key获取自定义配置的值
* @param key
* @return String
*/
public String findCustomConfigKeyOfValue(String key) {
return this.configJson.containsKey(key) ? this.configJson.getCustomConfigValue(key) : null;
}
/**
* 判断是否有自定义配置
* @param key
* @return
*/
public boolean hasCustomConfigKey(String key) {
return this.configJson.containsKey(key);
}
public JsonNode parseJsonNode(ObjectMapper mapper) {
ObjectNode jsonNode = mapper.createObjectNode();
jsonNode.put("name", this.getName());
jsonNode.put("dialect", this.dialect);
jsonNode.put("type", this.type);
jsonNode.put("statement", this.statement);
jsonNode.put("checkPoint", this.checkPoint);
jsonNode.put("savePointStrategy", this.savePointStrategy);
jsonNode.put("savePointPath", this.savePointPath);
jsonNode.put("parallelism", this.parallelism);
jsonNode.put("fragment", this.fragment);
jsonNode.put("statementSet", this.statementSet);
jsonNode.put("batchModel", this.batchModel);
jsonNode.put("clusterName", this.clusterName);
jsonNode.put("note", this.note);
jsonNode.put("step", this.step);
jsonNode.put("enabled", this.getEnabled());
return jsonNode;
}
public boolean isJarTask() {
return Dialect.isJarDialect(dialect);
}
}
......@@ -22,7 +22,7 @@ package org.dinky.data.model;
import org.dinky.data.dto.TaskVersionConfigureDTO;
import java.io.Serializable;
import java.util.Date;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
......@@ -83,5 +83,5 @@ public class TaskVersion implements Serializable {
@ApiModelProperty(value = "Create Time", dataType = "Date", notes = "Timestamp when the version was created")
@TableField(value = "create_time")
private Date createTime;
private LocalDateTime createTime;
}
......@@ -29,6 +29,7 @@ import org.dinky.context.FreeMarkerHolder;
import org.dinky.context.SpringContextUtils;
import org.dinky.daemon.pool.DefaultThreadPool;
import org.dinky.data.dto.AlertRuleDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.enums.Status;
import org.dinky.data.model.AlertGroup;
import org.dinky.data.model.AlertHistory;
......@@ -36,7 +37,6 @@ import org.dinky.data.model.AlertInstance;
import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobInstance;
import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Task;
import org.dinky.data.options.AlertRuleOptions;
import org.dinky.service.AlertGroupService;
import org.dinky.service.AlertHistoryService;
......@@ -214,7 +214,7 @@ public class JobAlertHandler {
private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) {
JobInfoDetail jobInfoDetail = facts.get(AlertRuleOptions.JOB_ALERT_RULE_JOB_DETAIL);
JobInstance jobInstance = jobInfoDetail.getInstance();
Task task = taskService.getById(jobInfoDetail.getInstance().getTaskId());
TaskDTO task = taskService.getTaskInfoById(jobInfoDetail.getInstance().getTaskId());
String taskUrl = StrFormatter.format(
"{}/#/devops/job-detail?id={}",
......
......@@ -19,35 +19,9 @@
package org.dinky.service;
import org.dinky.data.dto.APICancelDTO;
import org.dinky.data.dto.APIExecuteJarDTO;
import org.dinky.data.dto.APIExecuteSqlDTO;
import org.dinky.data.dto.APIExplainSqlDTO;
import org.dinky.data.dto.APISavePointDTO;
import org.dinky.data.result.APIJobResult;
import org.dinky.data.result.ExplainResult;
import org.dinky.gateway.result.SavePointResult;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* APIService
*
* @since 2021/12/11 21:45
*/
public interface APIService {
APIJobResult executeSql(APIExecuteSqlDTO apiExecuteSqlDTO);
ExplainResult explainSql(APIExplainSqlDTO apiExplainSqlDTO);
ObjectNode getJobPlan(APIExplainSqlDTO apiExplainSqlDTO);
ObjectNode getStreamGraph(APIExplainSqlDTO apiExplainSqlDTO);
boolean cancel(APICancelDTO apiCancelDTO);
SavePointResult savepoint(APISavePointDTO apiSavePointDTO);
APIJobResult executeJar(APIExecuteJarDTO apiExecuteJarDTO);
}
public interface APIService {}
......@@ -19,11 +19,15 @@
package org.dinky.service;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Column;
import org.dinky.data.model.DataBase;
import org.dinky.data.model.QueryData;
import org.dinky.data.model.Schema;
import org.dinky.data.model.SqlGeneration;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobResult;
import org.dinky.metadata.result.JdbcSelectResult;
import org.dinky.mybatis.service.ISuperService;
......@@ -136,4 +140,8 @@ public interface DataBaseService extends ISuperService<DataBase> {
* @return {@link Boolean}
*/
Boolean copyDatabase(DataBase database);
List<SqlExplainResult> explainCommonSql(TaskDTO task);
JobResult executeCommonSql(SqlDTO sqlDTO);
}
......@@ -19,6 +19,7 @@
package org.dinky.service;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Savepoints;
import org.dinky.mybatis.service.ISuperService;
......@@ -36,4 +37,6 @@ public interface SavepointsService extends ISuperService<Savepoints> {
Savepoints getLatestSavepointByTaskId(Integer taskId);
Savepoints getEarliestSavepointByTaskId(Integer taskId);
Savepoints getSavePointWithStrategy(TaskDTO task);
}
......@@ -19,25 +19,20 @@
package org.dinky.service;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.StudioCADTO;
import org.dinky.data.dto.StudioDDLDTO;
import org.dinky.data.dto.StudioExecuteDTO;
import org.dinky.data.dto.StudioMetaStoreDTO;
import org.dinky.data.model.Catalog;
import org.dinky.data.model.FlinkColumn;
import org.dinky.data.model.Schema;
import org.dinky.data.result.IResult;
import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.lineage.LineageResult;
import org.dinky.job.JobResult;
import org.dinky.metadata.result.JdbcSelectResult;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/**
* StudioService
......@@ -46,18 +41,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
*/
public interface StudioService {
JobResult executeSql(StudioExecuteDTO studioExecuteDTO);
JobResult executeCommonSql(SqlDTO sqlDTO);
IResult executeDDL(StudioDDLDTO studioDDLDTO);
List<SqlExplainResult> explainSql(StudioExecuteDTO studioExecuteDTO);
ObjectNode getStreamGraph(StudioExecuteDTO studioExecuteDTO);
ObjectNode getJobPlan(StudioExecuteDTO studioExecuteDTO);
JdbcSelectResult getCommonSqlData(Integer taskId);
SelectResult getJobData(String jobId);
......@@ -66,10 +51,6 @@ public interface StudioService {
List<JsonNode> listFlinkJobs(Integer clusterId);
boolean cancelFlinkJob(Integer clusterId, String jobId);
boolean savepointTrigger(Integer taskId, Integer clusterId, String jobId, String savePointType, String name);
List<Catalog> getMSCatalogs(StudioMetaStoreDTO studioMetaStoreDTO);
Schema getMSSchemaInfo(StudioMetaStoreDTO studioMetaStoreDTO);
......
......@@ -19,24 +19,27 @@
package org.dinky.service;
import org.dinky.data.dto.AbstractStatementDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.TaskRollbackVersionDTO;
import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.JobStatus;
import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.model.JobModelOverview;
import org.dinky.data.model.JobTypeOverView;
import org.dinky.data.model.Task;
import org.dinky.data.result.Result;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.data.result.TaskOperatingResult;
import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.JobResult;
import org.dinky.mybatis.service.ISuperService;
import org.dinky.process.exception.ExcuteException;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.lang.tree.Tree;
......@@ -47,45 +50,37 @@ import cn.hutool.core.lang.tree.Tree;
*/
public interface TaskService extends ISuperService<Task> {
JobResult submitTask(Integer id);
String buildEnvSql(AbstractStatementDTO task);
JobResult submitTaskToOnline(Task dtoTask, Integer id);
JobResult submitTask(Integer id, String savePointPath) throws ExcuteException;
JobResult restartTask(Integer id, String savePointPath);
JobResult restartTask(Integer id, String savePointPath) throws ExcuteException;
List<SqlExplainResult> explainTask(Integer id);
SavePointResult savepointTaskJob(TaskDTO task, String savePointType);
Task getTaskInfoById(Integer id);
List<SqlExplainResult> explainTask(TaskDTO task) throws NotSupportExplainExcepition;
void initTenantByTaskId(Integer id);
boolean cancelTaskJob(TaskDTO task);
boolean saveOrUpdateTask(Task task);
List<Task> listFlinkSQLEnv();
Task initDefaultFlinkSQLEnv(Integer tenantId);
ObjectNode getStreamGraph(TaskDTO taskDTO);
String exportSql(Integer id);
Task getUDFByClassName(String className);
List<Task> getAllUDF();
Result<Void> releaseTask(Integer id);
ObjectNode getJobPlan(TaskDTO task);
boolean developTask(Integer id);
TaskDTO getTaskInfoById(Integer id);
Result<JobResult> onLineTask(Integer id);
void initTenantByTaskId(Integer id);
Result<JobResult> reOnLineTask(Integer id, String savePointPath);
boolean changeTaskLifeRecyle(Integer taskId, JobLifeCycle lifeCycle);
Result<Void> offLineTask(Integer id, String type);
boolean saveOrUpdateTask(Task task);
Result<Void> cancelTask(Integer id);
List<Task> listFlinkSQLEnv();
boolean recoveryTask(Integer id);
Task initDefaultFlinkSQLEnv(Integer tenantId);
boolean savepointTask(Integer taskId, String savePointType);
List<Task> getAllUDF();
String getTaskAPIAddress();
......@@ -101,17 +96,8 @@ public interface TaskService extends ISuperService<Task> {
Result<Tree<Integer>> queryAllCatalogue();
Result<List<Task>> queryOnLineTaskByDoneStatus(
List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses, boolean includeNull, Integer catalogueId);
void selectSavepointOnLineTask(TaskOperatingResult taskOperatingResult);
void selectSavepointOffLineTask(TaskOperatingResult taskOperatingResult);
Task getTaskByNameAndTenantId(String name, Integer tenantId);
JobStatus checkJobStatus(JobInfoDetail jobInfoDetail);
List<JobTypeOverView> getTaskOnlineRate();
JobModelOverview getJobStreamingOrBatchModelOverview();
......
......@@ -19,6 +19,7 @@
package org.dinky.service;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.TaskVersion;
import org.dinky.mybatis.service.ISuperService;
......@@ -32,4 +33,6 @@ public interface TaskVersionService extends ISuperService<TaskVersion> {
* @return java.util.List<org.dinky.data.model.TaskVersion>
*/
List<TaskVersion> getTaskVersionByTaskId(Integer taskId);
void createTaskVersionSnapshot(TaskDTO task);
}
......@@ -149,6 +149,8 @@ public interface UserService extends ISuperService<User> {
*/
List<RowPermissions> getCurrentRoleSelectPermissions();
void buildRowPermission();
/** user loginout */
void outLogin();
......
......@@ -19,25 +19,12 @@
package org.dinky.service.impl;
import org.dinky.data.dto.APICancelDTO;
import org.dinky.data.dto.APIExecuteJarDTO;
import org.dinky.data.dto.APIExecuteSqlDTO;
import org.dinky.data.dto.APIExplainSqlDTO;
import org.dinky.data.dto.APISavePointDTO;
import org.dinky.data.result.APIJobResult;
import org.dinky.data.result.ExplainResult;
import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
import org.dinky.job.JobResult;
import org.dinky.service.APIService;
import org.dinky.utils.RunTimeUtil;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* APIServiceImpl
......@@ -45,79 +32,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
* @since 2021/12/11 21:46
*/
@Service
public class APIServiceImpl implements APIService {
@Override
public APIJobResult executeSql(APIExecuteSqlDTO apiExecuteSqlDTO) {
JobConfig config = apiExecuteSqlDTO.getJobConfig();
JobManager jobManager = JobManager.build(config);
JobResult jobResult = jobManager.executeSql(apiExecuteSqlDTO.getStatement());
APIJobResult apiJobResult = APIJobResult.build(jobResult);
RunTimeUtil.recovery(jobManager);
return apiJobResult;
}
@Override
public ExplainResult explainSql(APIExplainSqlDTO apiExplainSqlDTO) {
JobConfig config = apiExplainSqlDTO.getJobConfig();
JobManager jobManager = JobManager.buildPlanMode(config);
ExplainResult explainResult = jobManager.explainSql(apiExplainSqlDTO.getStatement());
RunTimeUtil.recovery(jobManager);
return explainResult;
}
@Override
public ObjectNode getJobPlan(APIExplainSqlDTO apiExplainSqlDTO) {
JobConfig config = apiExplainSqlDTO.getJobConfig();
JobManager jobManager = JobManager.buildPlanMode(config);
String planJson = jobManager.getJobPlanJson(apiExplainSqlDTO.getStatement());
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
try {
objectNode = (ObjectNode) mapper.readTree(planJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
} finally {
RunTimeUtil.recovery(jobManager);
return objectNode;
}
}
@Override
public ObjectNode getStreamGraph(APIExplainSqlDTO apiExplainSqlDTO) {
JobConfig config = apiExplainSqlDTO.getJobConfig();
JobManager jobManager = JobManager.buildPlanMode(config);
ObjectNode streamGraph = jobManager.getStreamGraph(apiExplainSqlDTO.getStatement());
RunTimeUtil.recovery(jobManager);
return streamGraph;
}
@Override
public boolean cancel(APICancelDTO apiCancelDTO) {
JobConfig jobConfig = apiCancelDTO.getJobConfig();
JobManager jobManager = JobManager.build(jobConfig);
boolean cancel = jobManager.cancel(apiCancelDTO.getJobId());
RunTimeUtil.recovery(jobManager);
return cancel;
}
@Override
public SavePointResult savepoint(APISavePointDTO apiSavePointDTO) {
JobConfig jobConfig = apiSavePointDTO.getJobConfig();
JobManager jobManager = JobManager.build(jobConfig);
SavePointResult savepoint = jobManager.savepoint(
apiSavePointDTO.getJobId(), apiSavePointDTO.getSavePointType(), apiSavePointDTO.getSavePoint());
RunTimeUtil.recovery(jobManager);
return savepoint;
}
@Override
public APIJobResult executeJar(APIExecuteJarDTO apiExecuteJarDTO) {
JobConfig config = apiExecuteJarDTO.getJobConfig();
JobManager jobManager = JobManager.build(config);
JobResult jobResult = jobManager.executeJar();
APIJobResult apiJobResult = APIJobResult.build(jobResult);
RunTimeUtil.recovery(jobManager);
return apiJobResult;
}
}
@RequiredArgsConstructor
@Slf4j
public class APIServiceImpl implements APIService {}
......@@ -21,6 +21,8 @@ package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.data.constant.CommonConstant;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.enums.Status;
import org.dinky.data.model.Column;
import org.dinky.data.model.DataBase;
......@@ -28,6 +30,8 @@ import org.dinky.data.model.QueryData;
import org.dinky.data.model.Schema;
import org.dinky.data.model.SqlGeneration;
import org.dinky.data.model.Table;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.job.JobResult;
import org.dinky.mapper.DataBaseMapper;
import org.dinky.metadata.driver.Driver;
import org.dinky.metadata.result.JdbcSelectResult;
......@@ -38,6 +42,7 @@ import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
......@@ -240,4 +245,59 @@ public class DataBaseServiceImpl extends SuperServiceImpl<DataBaseMapper, DataBa
database.setCreateTime(null);
return this.save(database);
}
@Override
public List<SqlExplainResult> explainCommonSql(TaskDTO task) {
if (Asserts.isNull(task.getDatabaseId())) {
return Collections.singletonList(SqlExplainResult.fail(task.getStatement(), "please assign data source."));
}
DataBase dataBase = getById(task.getDatabaseId());
if (Asserts.isNull(dataBase)) {
return Collections.singletonList(SqlExplainResult.fail(task.getStatement(), "data source not exist."));
}
List<SqlExplainResult> sqlExplainResults;
try (Driver driver = Driver.build(dataBase.getDriverConfig())) {
sqlExplainResults = driver.explain(task.getStatement());
}
return sqlExplainResults;
}
@Override
public JobResult executeCommonSql(SqlDTO sqlDTO) {
JobResult result = new JobResult();
result.setStatement(sqlDTO.getStatement());
result.setStartTime(LocalDateTime.now());
if (Asserts.isNull(sqlDTO.getDatabaseId())) {
result.setSuccess(false);
result.setError("please assign data source");
result.setEndTime(LocalDateTime.now());
return result;
}
DataBase dataBase = getById(sqlDTO.getDatabaseId());
if (Asserts.isNull(dataBase)) {
result.setSuccess(false);
result.setError("data source not exist.");
result.setEndTime(LocalDateTime.now());
return result;
}
JdbcSelectResult selectResult;
try (Driver driver = Driver.build(dataBase.getDriverConfig())) {
selectResult = driver.executeSql(sqlDTO.getStatement(), sqlDTO.getMaxRowNum());
}
result.setResult(selectResult);
if (selectResult.isSuccess()) {
result.setSuccess(true);
} else {
result.setSuccess(false);
result.setError(selectResult.getError());
}
result.setEndTime(LocalDateTime.now());
return result;
}
}
......@@ -19,7 +19,9 @@
package org.dinky.service.impl;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Savepoints;
import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.mapper.SavepointsMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.SavepointsService;
......@@ -52,4 +54,23 @@ public class SavepointsServiceImpl extends SuperServiceImpl<SavepointsMapper, Sa
public Savepoints getEarliestSavepointByTaskId(Integer taskId) {
return baseMapper.getEarliestSavepointByTaskId(taskId);
}
@Override
public Savepoints getSavePointWithStrategy(TaskDTO task) {
SavePointStrategy savePointStrategy = SavePointStrategy.get(task.getSavePointStrategy());
switch (savePointStrategy) {
case LATEST:
return getLatestSavepointByTaskId(task.getId());
case EARLIEST:
return getEarliestSavepointByTaskId(task.getId());
case CUSTOM:
return new Savepoints() {
{
setPath(task.getSavePointPath());
}
};
default:
return null;
}
}
}
......@@ -19,17 +19,26 @@
package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.TaskVersionConfigureDTO;
import org.dinky.data.model.TaskVersion;
import org.dinky.mapper.TaskVersionMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.TaskVersionService;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.bean.BeanUtil;
@Service
public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper, TaskVersion>
implements TaskVersionService {
......@@ -41,4 +50,41 @@ public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper,
.eq(TaskVersion::getTaskId, taskId)
.orderByDesc(true, TaskVersion::getVersionId));
}
@Override
public void createTaskVersionSnapshot(TaskDTO task) {
List<TaskVersion> taskVersions = getTaskVersionByTaskId(task.getId());
List<Integer> versionIds =
taskVersions.stream().map(TaskVersion::getVersionId).collect(Collectors.toList());
Map<Integer, TaskVersion> versionMap =
taskVersions.stream().collect(Collectors.toMap(TaskVersion::getVersionId, t -> t));
TaskVersion taskVersion = new TaskVersion();
BeanUtil.copyProperties(task, taskVersion);
TaskVersionConfigureDTO taskVersionConfigureDTO = new TaskVersionConfigureDTO();
BeanUtil.copyProperties(task, taskVersionConfigureDTO);
taskVersion.setTaskConfigure(taskVersionConfigureDTO);
taskVersion.setTaskId(taskVersion.getId());
taskVersion.setId(null);
if (Asserts.isNull(task.getVersionId())) {
// FIRST RELEASE, ADD NEW VERSION
taskVersion.setVersionId(1);
task.setVersionId(1);
taskVersion.setCreateTime(LocalDateTime.now());
save(taskVersion);
} else {
// Explain that there is a version, you need to determine whether it is an old version after fallback
TaskVersion version = versionMap.get(task.getVersionId());
version.setId(null);
if (versionIds.contains(task.getVersionId()) && !taskVersion.equals(version)) {
taskVersion.setVersionId(Collections.max(versionIds) + 1);
task.setVersionId(Collections.max(versionIds) + 1);
taskVersion.setCreateTime(LocalDateTime.now());
save(taskVersion);
}
}
}
}
......@@ -20,6 +20,7 @@
package org.dinky.service.impl;
import org.dinky.assertion.Asserts;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder;
import org.dinky.context.UserInfoContextHolder;
import org.dinky.data.dto.LoginDTO;
......@@ -55,6 +56,7 @@ import org.dinky.service.UserTenantService;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
......@@ -366,6 +368,21 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
return roleSelectPermissionsService.listRoleSelectPermissionsByRoleIds(roleIds);
}
@Override
public void buildRowPermission() {
List<RowPermissions> currentRoleSelectPermissions = getCurrentRoleSelectPermissions();
if (Asserts.isNotNullCollection(currentRoleSelectPermissions)) {
ConcurrentHashMap<String, String> permission = new ConcurrentHashMap<>();
for (RowPermissions roleSelectPermissions : currentRoleSelectPermissions) {
if (Asserts.isAllNotNullString(
roleSelectPermissions.getTableName(), roleSelectPermissions.getExpression())) {
permission.put(roleSelectPermissions.getTableName(), roleSelectPermissions.getExpression());
}
}
RowLevelPermissionsContext.set(permission);
}
}
@Override
public void outLogin() {
StpUtil.logout(StpUtil.getLoginIdAsInt());
......
/*
*
* 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.utils;
import org.dinky.context.SpringContextUtils;
import org.dinky.data.enums.CodeEnum;
import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.JobStatus;
import org.dinky.data.enums.TaskOperatingSavepointSelect;
import org.dinky.data.enums.TaskOperatingStatus;
import org.dinky.data.model.Task;
import org.dinky.data.result.Result;
import org.dinky.data.result.TaskOperatingResult;
import org.dinky.service.TaskService;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Dict;
/** @version 1.0 */
public class TaskOneClickOperatingUtil {
private static List<TaskOperatingResult> oneClickOnlineCache = new ArrayList<>(0);
private static List<TaskOperatingResult> oneClickOfflineCache = new ArrayList<>(0);
private static final AtomicBoolean oneClickOnlineThreadStatus = new AtomicBoolean(false);
private static final AtomicBoolean oneClickOfflineThreadStatus = new AtomicBoolean(false);
public static synchronized Result<Void> oneClickOnline(
List<Task> tasks, TaskOperatingSavepointSelect taskOperatingSavepointSelect) {
if (oneClickOnlineThreadStatus.get() || oneClickOfflineThreadStatus.get()) {
return Result.failed("存在一键上线或者下线操作,请稍后重试");
}
final TaskService taskService = SpringContextUtils.getBeanByClass(TaskService.class);
if (CollectionUtils.isEmpty(tasks)) {
final Result<List<Task>> listResult = taskService.queryOnLineTaskByDoneStatus(
Collections.singletonList(JobLifeCycle.RELEASE), JobStatus.getAllDoneStatus(), true, 0);
if (CollectionUtils.isEmpty(listResult.getDatas())) {
return Result.succeed("没有需要上线的任务");
}
tasks = listResult.getDatas();
}
oneClickOnlineCache = tasks.stream()
.map(task -> new TaskOperatingResult(task, taskOperatingSavepointSelect))
.collect(Collectors.toList());
new OneClickOperatingThread(
"oneClickOnlineThread",
oneClickOnlineCache,
oneClickOnlineThreadStatus,
taskService::selectSavepointOnLineTask)
.start();
return Result.succeed("success");
}
public static synchronized Result<Void> onClickOffline(List<Task> tasks) {
if (oneClickOnlineThreadStatus.get() || oneClickOfflineThreadStatus.get()) {
return Result.failed("存在一键上线或者下线操作,请稍后重试");
}
final TaskService taskService = SpringContextUtils.getBeanByClass(TaskService.class);
if (CollectionUtils.isEmpty(tasks)) {
final Result<List<Task>> listResult = taskService.queryOnLineTaskByDoneStatus(
Collections.singletonList(JobLifeCycle.ONLINE),
Collections.singletonList(JobStatus.RUNNING),
false,
0);
if (CollectionUtils.isEmpty(listResult.getDatas())) {
return Result.succeed("没有需要下线的任务");
}
tasks = listResult.getDatas();
}
oneClickOfflineCache = tasks.stream().map(TaskOperatingResult::new).collect(Collectors.toList());
new OneClickOperatingThread(
"oneClickOfflineThread",
oneClickOfflineCache,
oneClickOfflineThreadStatus,
taskService::selectSavepointOffLineTask)
.start();
return Result.succeed("success");
}
public static Result<Dict> queryOneClickOperatingTaskStatus() {
Dict dict = Dict.create()
.set("online", oneClickOnlineCache)
.set("onlineStatus", oneClickOnlineThreadStatus.get())
.set("offline", oneClickOfflineCache)
.set("offlineStatus", oneClickOfflineThreadStatus.get());
return Result.succeed(dict);
}
public static List<Task> parseJsonNode(JsonNode operating) {
final JsonNode tasksJsonNode = operating.withArray("tasks");
if (tasksJsonNode == null || tasksJsonNode.isEmpty()) {
return null;
}
final List<Task> result = new ArrayList<>(tasksJsonNode.size());
for (JsonNode node : tasksJsonNode) {
final Task task = new Task();
task.setId(node.get("id").asInt());
task.setName(node.get("name").asText());
result.add(task);
}
return result;
}
private static class OneClickOperatingThread extends Thread {
private static final Logger LOGGER = LoggerFactory.getLogger(OneClickOperatingThread.class);
private final String threadName;
private final List<TaskOperatingResult> taskOperatingResults;
private final AtomicBoolean threadStatus;
private final Consumer<TaskOperatingResult> consumer;
public OneClickOperatingThread(
String threadName,
List<TaskOperatingResult> taskOperatingResults,
AtomicBoolean threadStatus,
Consumer<TaskOperatingResult> consumer) {
super(threadName);
this.threadName = threadName;
this.threadStatus = threadStatus;
this.threadStatus.set(true);
this.taskOperatingResults = taskOperatingResults;
this.consumer = consumer;
}
@Override
public void run() {
try {
if (CollectionUtils.isEmpty(taskOperatingResults)) {
return;
}
for (TaskOperatingResult taskOperatingResult : taskOperatingResults) {
try {
taskOperatingResult.setStatus(TaskOperatingStatus.OPERATING_BEFORE);
consumer.accept(taskOperatingResult);
} catch (Throwable e) {
exceptionDealWith(taskOperatingResult, e);
}
}
} finally {
this.threadStatus.set(false);
}
}
private void exceptionDealWith(TaskOperatingResult taskOperatingResult, Throwable e) {
taskOperatingResult.setStatus(TaskOperatingStatus.EXCEPTION);
taskOperatingResult.setCode(CodeEnum.EXCEPTION.getCode());
taskOperatingResult.setMessage(ExceptionUtil.stacktraceToString(e));
LOGGER.error(
"[{}], taskId={}, taskName={}, operating exception",
threadName,
taskOperatingResult.getTask().getId(),
taskOperatingResult.getTask().getName(),
e);
}
}
}
......@@ -77,7 +77,7 @@ public enum Dialect {
* @param value {@link Dialect}
* @return If is flink sql, return false, otherwise return true.
*/
public static boolean notFlinkSql(String value) {
public static boolean isCommonSql(String value) {
Dialect dialect = Dialect.get(value);
switch (dialect) {
case SQL:
......
......@@ -28,12 +28,8 @@ import java.util.Arrays;
*/
public enum JobLifeCycle {
UNKNOWN(0, "未知"),
CREATE(1, "创建"),
DEVELOP(2, "开发"),
DEBUG(3, "调试"),
RELEASE(4, "发布"),
ONLINE(5, "上线"),
CANCEL(6, "注销");
DEVELOP(1, "开发"),
ONLINE(2, "上线");
private Integer value;
private String label;
......
......@@ -171,6 +171,10 @@ public enum Status {
TASK_NOT_EXIST(12003, "task.not.exist"),
JOB_INSTANCE_NOT_EXIST(12004, "job.instance.not.exist"),
SAVEPOINT_IS_NULL(12005, "savepoint.is.null"),
TASK_STATUS_IS_NOT_DONE(12006, "task.status.is.not.done"),
TASK_SQL_EXPLAN_FAILED(12007, "task.sql.explain.failed"),
TASK_UPDATE_FAILED(12008, "task.update.failed"),
TASK_IS_ONLINE(12009, "task.is.online"),
/**
* alert instance
......@@ -195,6 +199,7 @@ public enum Status {
CLUSTER_INSTANCE_RECYCLE_SUCCESS(15002, "cluster.instance.recycle.success"),
CLUSTER_INSTANCE_KILL(15003, "cluster.instance.kill"),
CLUSTER_INSTANCE_DEPLOY(15004, "cluster.instance.deploy"),
CLUSTER_NOT_EXIST(15004, "cluster.not.exist"),
/**
* git
......
......@@ -92,6 +92,7 @@ tenant.name.exist=Tenant Already Exists
failed=Failed
added.failed=Added Failed
task.not.exist=Task Not Exist
task.is.online= Task is online, modification is prohibited
cluster.instance.deploy=Deploy Success
clear.failed=Clear Failed
rename.success=Rename Successfully
......@@ -119,6 +120,7 @@ git.sort.failed=Git Sort Failed
query.failed=Query Failed
save.success=Save Successfully
cluster.instance.kill=Kill Success
cluster.not.exist=Cluster Not Exist
operate.failed=Operate Failed
test.connection.failed=Test Connection Failed
switching.tenant.success=Select Tenant Success
......@@ -231,4 +233,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS configuration items, s
#Dinky Gateway
gateway.kubernetes.test.failed= failed to test the Flink configuration:
\ No newline at end of file
gateway.kubernetes.test.failed= failed to test the Flink configuration:
task.status.is.not.done=In the current publishing state, a job is running and the online fails, please stop and go online
task.sql.explain.failed=SQL parsing failed, please check the SQL statement
task.update.failed=Task Update failed
......@@ -92,6 +92,7 @@ tenant.name.exist=租户已存在
failed=获取失败
added.failed=新增失败
task.not.exist=任务不存在
task.is.online=任务已上线,禁止修改
cluster.instance.deploy=部署完成
clear.failed=清除失败
rename.success=重命名成功
......@@ -119,6 +120,7 @@ git.sort.failed=排序失败
query.failed=查询失败
save.success=保存成功
cluster.instance.kill=已杀死该进程/集群
cluster.not.exist=集群不存在
operate.failed=操作失败
test.connection.failed=测试连接失败
switching.tenant.success=选择租户成功
......@@ -229,3 +231,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS 配置项,例如远
#Dinky Gateway
gateway.kubernetes.test.failed=测试 Flink 配置失败:
# Task
task.status.is.not.done=当前发布状态下有作业正在运行,上线失败,请停止后上线
task.sql.explain.failed=sql解析失败,请检查
task.update.failed=Task更新失败
\ No newline at end of file
......@@ -19,6 +19,8 @@
package org.dinky.data.result;
import org.dinky.metadata.result.JdbcSelectResult;
import java.util.concurrent.TimeUnit;
import cn.hutool.cache.Cache;
......@@ -33,6 +35,8 @@ public final class ResultPool {
private ResultPool() {}
private static final Cache<Integer, JdbcSelectResult> COMMON_SQL_SEARCH_CACHE =
new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
private static final Cache<String, SelectResult> results = new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
public static boolean containsKey(String key) {
......@@ -43,6 +47,14 @@ public final class ResultPool {
results.put(result.getJobId(), result);
}
public static void putCommonSqlCache(Integer taskId, JdbcSelectResult result) {
COMMON_SQL_SEARCH_CACHE.put(taskId, result);
}
public static JdbcSelectResult getCommonSqlCache(Integer taskId) {
return COMMON_SQL_SEARCH_CACHE.get(taskId);
}
public static SelectResult get(String key) {
if (containsKey(key)) {
return results.get(key);
......
......@@ -32,6 +32,7 @@ import org.dinky.executor.Executor;
import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
......@@ -362,14 +363,14 @@ public class Explainer {
}
public List<LineageRel> getLineage(String statement) {
JobConfig jobConfig = new JobConfig(
"local",
false,
false,
true,
useStatementSet,
1,
executor.getTableConfig().getConfiguration().toMap());
JobConfig jobConfig = JobConfig.builder()
.type(GatewayType.LOCAL.getLongValue())
.useRemote(false)
.fragment(true)
.statementSet(useStatementSet)
.parallelism(1)
.configJson(executor.getTableConfig().getConfiguration().toMap())
.build();
this.initialize(JobManager.buildPlanMode(jobConfig), jobConfig, statement);
List<LineageRel> lineageRelList = new ArrayList<>();
......
......@@ -176,7 +176,7 @@ public class JobManager {
useGateway = GatewayType.isDeployCluster(config.getType());
handler = JobHandler.build();
}
useStatementSet = config.isUseStatementSet();
useStatementSet = config.isStatementSet();
useRestAPI = SystemConfiguration.getInstances().isUseRestAPI();
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
executorConfig = config.getExecutorSetting();
......
......@@ -21,12 +21,11 @@ package org.dinky.core;
import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.job.JobConfig;
import org.dinky.job.JobManager;
import org.dinky.job.JobResult;
import java.util.HashMap;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
......@@ -45,29 +44,20 @@ public class JobManagerTest {
@Ignore
@Test
public void cancelJobSelect() {
JobConfig config = new JobConfig(
"session-yarn",
true,
true,
true,
true,
"s1",
2,
null,
null,
null,
"测试",
false,
false,
false,
100,
0,
1,
0,
null,
new HashMap<>(),
new HashMap<>());
JobConfig config = JobConfig.builder()
.type(GatewayType.YARN_SESSION.getLongValue())
.useResult(true)
.useChangeLog(true)
.useAutoCancel(true)
.session("s1")
.clusterId(2)
.jobName("Test")
.fragment(false)
.statementSet(false)
.batchModel(false)
.maxRowNum(100)
.parallelism(1)
.build();
if (config.isUseRemote()) {
config.setAddress("192.168.123.157:8081");
}
......
/*
*
* 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.process.exception;
import org.dinky.process.context.ProcessContextHolder;
import org.dinky.utils.LogUtil;
public class ExcuteException extends Exception {
public ExcuteException() {}
public ExcuteException(String message) {
super(message);
ProcessContextHolder.getProcess().error(message);
}
public ExcuteException(String message, Throwable cause) {
super(message, cause);
ProcessContextHolder.getProcess().error(LogUtil.getError(cause));
}
public ExcuteException(Throwable cause) {
super(cause);
ProcessContextHolder.getProcess().error(cause.toString());
}
public ExcuteException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
ProcessContextHolder.getProcess().error(LogUtil.getError(cause));
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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