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
...@@ -19,25 +19,22 @@ ...@@ -19,25 +19,22 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.data.dto.APICancelDTO; import org.dinky.data.annotation.Log;
import org.dinky.data.dto.APIExecuteJarDTO; import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.APIExecuteSqlDTO; import org.dinky.data.enums.BusinessType;
import org.dinky.data.dto.APIExplainSqlDTO;
import org.dinky.data.dto.APISavePointDTO;
import org.dinky.data.dto.APISavePointTaskDTO;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.model.JobInstance; import org.dinky.data.model.JobInstance;
import org.dinky.data.result.APIJobResult;
import org.dinky.data.result.ExplainResult;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SqlExplainResult;
import org.dinky.gateway.result.SavePointResult; import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.JobResult; import org.dinky.job.JobResult;
import org.dinky.service.APIService; import org.dinky.process.exception.ExcuteException;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
import org.dinky.service.StudioService;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
...@@ -49,15 +46,12 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -49,15 +46,12 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
* APIController * APIController
*
* @since 2021/12/11 21:44
*/ */
@SuppressWarnings("AlibabaClassNamingShouldBeCamel") @SuppressWarnings("AlibabaClassNamingShouldBeCamel")
@Slf4j @Slf4j
...@@ -67,237 +61,71 @@ import lombok.extern.slf4j.Slf4j; ...@@ -67,237 +61,71 @@ import lombok.extern.slf4j.Slf4j;
@RequiredArgsConstructor @RequiredArgsConstructor
public class APIController { public class APIController {
private final APIService apiService;
private final StudioService studioService;
private final TaskService taskService; private final TaskService taskService;
private final JobInstanceService jobInstanceService; private final JobInstanceService jobInstanceService;
@GetMapping("/submitTask") @PostMapping("/submitTask")
@ApiOperation("Submit Task") @ApiOperation("Submit Task")
// @Log(title = "Submit Task", businessType = BusinessType.SUBMIT) // @Log(title = "Submit Task", businessType = BusinessType.SUBMIT)
@ApiImplicitParam(name = "id", value = "Task Id", required = true, dataType = "Integer") public Result<JobResult> submitTask(@RequestBody TaskDTO taskDTO) throws ExcuteException {
public Result<JobResult> submitTask(@RequestParam Integer id) { JobResult jobResult = taskService.submitTask(taskDTO.getId(), null);
taskService.initTenantByTaskId(id); if (jobResult.isSuccess()) {
return Result.succeed(taskService.submitTask(id), Status.EXECUTE_SUCCESS); return Result.succeed(jobResult, Status.EXECUTE_SUCCESS);
} } else {
return Result.failed(jobResult, jobResult.getError());
@PostMapping("/executeSql") }
@ApiOperation("Execute Sql")
// @Log(title = "Execute Sql", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "apiExecuteSqlDTO",
value = "API Execute Sql DTO",
required = true,
dataType = "APIExecuteSqlDTO",
dataTypeClass = APIExecuteSqlDTO.class)
public Result<APIJobResult> executeSql(@RequestBody APIExecuteSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.executeSql(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/explainSql")
@ApiOperation("Explain Sql")
// @Log(title = "Explain Sql", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "apiExecuteSqlDTO",
value = "API Execute Sql DTO",
required = true,
dataType = "APIExecuteSqlDTO",
dataTypeClass = APIExecuteSqlDTO.class)
public Result<ExplainResult> explainSql(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.explainSql(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
} }
@PostMapping("/getJobPlan") @GetMapping("/cancel")
@ApiOperation("Get Job Plan")
@ApiImplicitParam(
name = "apiExecuteSqlDTO",
value = "API Execute Sql DTO",
required = true,
dataType = "APIExecuteSqlDTO",
dataTypeClass = APIExecuteSqlDTO.class)
public Result<ObjectNode> getJobPlan(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.getJobPlan(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/getStreamGraph")
@ApiOperation("Get Stream Graph")
@ApiImplicitParam(
name = "apiExecuteSqlDTO",
value = "API Execute Sql DTO",
required = true,
dataType = "APIExecuteSqlDTO",
dataTypeClass = APIExecuteSqlDTO.class)
public Result<ObjectNode> getStreamGraph(@RequestBody APIExplainSqlDTO apiExecuteSqlDTO) {
return Result.succeed(apiService.getStreamGraph(apiExecuteSqlDTO), Status.EXECUTE_SUCCESS);
}
@GetMapping("/getJobData")
@ApiOperation("Get Job Data")
@ApiImplicitParam(
name = "jobId",
value = "Job Id",
required = true,
dataType = "String",
dataTypeClass = String.class)
public Result<SelectResult> getJobData(@RequestParam String jobId) {
return Result.succeed(studioService.getJobData(jobId));
}
@PostMapping("/cancel")
// @Log(title = "Cancel Flink Job", businessType = BusinessType.TRIGGER) // @Log(title = "Cancel Flink Job", businessType = BusinessType.TRIGGER)
@ApiOperation("Cancel Flink Job") @ApiOperation("Cancel Flink Job")
@ApiImplicitParam( public Result<Boolean> cancel(@RequestParam Integer id) {
name = "apiCancelDTO", return Result.succeed(taskService.cancelTaskJob(taskService.getTaskInfoById(id)), Status.EXECUTE_SUCCESS);
value = "API Cancel DTO", }
required = true,
dataType = "APICancelDTO", /**
dataTypeClass = APICancelDTO.class) * 重启任务
public Result<Boolean> cancel(@RequestBody APICancelDTO apiCancelDTO) { */
return Result.succeed(apiService.cancel(apiCancelDTO), Status.EXECUTE_SUCCESS); @GetMapping(value = "/restartTask")
@ApiOperation("Restart Task")
// @Log(title = "Restart Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<JobResult> restartTask(@RequestParam Integer id, @RequestParam String savePointPath)
throws ExcuteException {
return Result.succeed(taskService.restartTask(id, savePointPath));
} }
@PostMapping("/savepoint") @PostMapping("/savepoint")
// @Log(title = "Savepoint Trigger", businessType = BusinessType.TRIGGER) // @Log(title = "Savepoint Trigger", businessType = BusinessType.TRIGGER)
@ApiOperation("Savepoint Trigger") @ApiOperation("Savepoint Trigger")
@ApiImplicitParam( public Result<SavePointResult> savepoint(@RequestParam Integer taskId, @RequestParam String savePointType) {
name = "apiSavePointDTO",
value = "API SavePoint DTO",
required = true,
dataType = "APISavePointDTO",
dataTypeClass = APISavePointDTO.class)
public Result<SavePointResult> savepoint(@RequestBody APISavePointDTO apiSavePointDTO) {
return Result.succeed(apiService.savepoint(apiSavePointDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/executeJar")
@ApiOperation("Execute Jar")
// @Log(title = "Execute Jar", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "apiExecuteJarDTO",
value = "API Execute Jar DTO",
required = true,
dataType = "APIExecuteJarDTO",
dataTypeClass = APIExecuteJarDTO.class)
public Result<APIJobResult> executeJar(@RequestBody APIExecuteJarDTO apiExecuteJarDTO) {
return Result.succeed(apiService.executeJar(apiExecuteJarDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/savepointTask")
@ApiOperation("Savepoint Task")
// @Log(title = "Savepoint Task", businessType = BusinessType.TRIGGER)
@ApiImplicitParam(
name = "apiSavePointTaskDTO",
value = "API SavePoint Task DTO",
required = true,
dataType = "APISavePointTaskDTO",
dataTypeClass = APISavePointTaskDTO.class)
public Result<Boolean> savepointTask(@RequestBody APISavePointTaskDTO apiSavePointTaskDTO) {
return Result.succeed( return Result.succeed(
taskService.savepointTask(apiSavePointTaskDTO.getTaskId(), apiSavePointTaskDTO.getType()), "执行成功"); taskService.savepointTaskJob(taskService.getTaskInfoById(taskId), savePointType),
Status.EXECUTE_SUCCESS);
} }
/** 重启任务 */ @PostMapping("/explainSql")
@GetMapping("/restartTask") @ApiOperation("Explain Sql")
@ApiOperation("Restart Task") public Result<List<SqlExplainResult>> explainSql(@RequestBody TaskDTO taskDTO) throws NotSupportExplainExcepition {
// @Log(title = "Restart Task", businessType = BusinessType.EXECUTE) return Result.succeed(taskService.explainTask(taskDTO), Status.EXECUTE_SUCCESS);
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class)
public Result<JobResult> restartTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return Result.succeed(taskService.restartTask(id, null), Status.RESTART_SUCCESS);
}
/** 选择保存点重启任务 */
@GetMapping("/selectSavePointRestartTask")
@ApiOperation("Select SavePoint Restart Task")
// @Log(title = "Select SavePoint Restart Task", businessType = BusinessType.EXECUTE)
@ApiImplicitParams({
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class),
@ApiImplicitParam(
name = "savePointPath",
value = "SavePoint Path",
required = true,
dataType = "String",
dataTypeClass = String.class)
})
public Result<JobResult> restartTask(@RequestParam Integer id, @RequestParam String savePointPath) {
taskService.initTenantByTaskId(id);
return Result.succeed(taskService.restartTask(id, savePointPath), Status.RESTART_SUCCESS);
}
/** 上线任务 */
@GetMapping("/onLineTask")
@ApiOperation("Online Task")
// @Log(title = "Online Task", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class)
public Result<JobResult> onLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.onLineTask(id);
}
/** 下线任务 */
@GetMapping("/offLineTask")
@ApiOperation("Offline Task")
// @Log(title = "Offline Task", businessType = BusinessType.EXECUTE)
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class)
public Result<Void> offLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.offLineTask(id, null);
} }
/** 重新上线任务 */ @PostMapping("/getJobPlan")
@GetMapping("/reOnLineTask") @ApiOperation("Get Job Plan")
@ApiOperation("ReOnline Task") public Result<ObjectNode> getJobPlan(@RequestBody TaskDTO taskDTO) {
// @Log(title = "ReOnline Task", businessType = BusinessType.EXECUTE) return Result.succeed(taskService.getJobPlan(taskDTO), Status.EXECUTE_SUCCESS);
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class)
public Result<JobResult> reOnLineTask(@RequestParam Integer id) {
taskService.initTenantByTaskId(id);
return taskService.reOnLineTask(id, null);
} }
/** 选择保存点重新上线任务 */ @PostMapping("/getStreamGraph")
@GetMapping("/selectSavePointReOnLineTask") @ApiOperation("Get Stream Graph")
@ApiOperation("Select SavePoint ReOnline Task") public Result<ObjectNode> getStreamGraph(@RequestBody TaskDTO taskDTO) {
// @Log(title = "Select SavePoint ReOnline Task", businessType = BusinessType.EXECUTE) return Result.succeed(taskService.getStreamGraph(taskDTO), Status.EXECUTE_SUCCESS);
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
dataTypeClass = Integer.class)
public Result<JobResult> selectSavePointReOnLineTask(@RequestParam Integer id, @RequestParam String savePointPath) {
taskService.initTenantByTaskId(id);
return taskService.reOnLineTask(id, savePointPath);
} }
/** 获取Job实例的信息 */ /**
* 获取Job实例的信息
*/
@GetMapping("/getJobInstance") @GetMapping("/getJobInstance")
@ApiOperation("Get Job Instance") @ApiOperation("Get Job Instance")
// @Log(title = "Get Job Instance", businessType = BusinessType.QUERY)
@ApiImplicitParam( @ApiImplicitParam(
name = "id", name = "id",
value = "Job Instance Id", value = "Job Instance Id",
...@@ -309,10 +137,8 @@ public class APIController { ...@@ -309,10 +137,8 @@ public class APIController {
return Result.succeed(jobInstanceService.getById(id)); return Result.succeed(jobInstanceService.getById(id));
} }
/** 通过 taskId 获取 Task 对应的 Job 实例的信息 */
@GetMapping("/getJobInstanceByTaskId") @GetMapping("/getJobInstanceByTaskId")
@ApiOperation("Get Job Instance By Task Id") @ApiOperation("Get Job Instance By Task Id")
// @Log(title = "Get Job Instance By Task Id", businessType = BusinessType.QUERY)
@ApiImplicitParam( @ApiImplicitParam(
name = "id", name = "id",
value = "Task Id", value = "Task Id",
...@@ -323,4 +149,18 @@ public class APIController { ...@@ -323,4 +149,18 @@ public class APIController {
taskService.initTenantByTaskId(id); taskService.initTenantByTaskId(id);
return Result.succeed(jobInstanceService.getJobInstanceByTaskId(id)); return Result.succeed(jobInstanceService.getJobInstanceByTaskId(id));
} }
@GetMapping(value = "/exportSql")
@ApiOperation("Export Sql")
@Log(title = "Export Sql", businessType = BusinessType.EXPORT)
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
paramType = "query",
dataTypeClass = Integer.class)
public Result<String> exportSql(@RequestParam Integer id) {
return Result.succeed(taskService.exportSql(id));
}
} }
...@@ -23,7 +23,6 @@ import org.dinky.assertion.Asserts; ...@@ -23,7 +23,6 @@ import org.dinky.assertion.Asserts;
import org.dinky.data.annotation.Log; import org.dinky.data.annotation.Log;
import org.dinky.data.dto.StudioCADTO; import org.dinky.data.dto.StudioCADTO;
import org.dinky.data.dto.StudioDDLDTO; import org.dinky.data.dto.StudioDDLDTO;
import org.dinky.data.dto.StudioExecuteDTO;
import org.dinky.data.dto.StudioMetaStoreDTO; import org.dinky.data.dto.StudioMetaStoreDTO;
import org.dinky.data.enums.BusinessType; import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
...@@ -33,9 +32,7 @@ import org.dinky.data.model.Schema; ...@@ -33,9 +32,7 @@ import org.dinky.data.model.Schema;
import org.dinky.data.result.IResult; import org.dinky.data.result.IResult;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.lineage.LineageResult; import org.dinky.explainer.lineage.LineageResult;
import org.dinky.job.JobResult;
import org.dinky.metadata.result.JdbcSelectResult; import org.dinky.metadata.result.JdbcSelectResult;
import org.dinky.service.StudioService; import org.dinky.service.StudioService;
...@@ -49,7 +46,6 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -49,7 +46,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
...@@ -72,75 +68,6 @@ public class StudioController { ...@@ -72,75 +68,6 @@ public class StudioController {
private final StudioService studioService; 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") @PostMapping("/executeDDL")
@ApiOperation("Execute SQL DDL") @ApiOperation("Execute SQL DDL")
@Log(title = "Execute SQL DDL", businessType = BusinessType.EXECUTE) @Log(title = "Execute SQL DDL", businessType = BusinessType.EXECUTE)
...@@ -162,6 +89,7 @@ public class StudioController { ...@@ -162,6 +89,7 @@ public class StudioController {
public Result<SelectResult> getJobData(@RequestParam String jobId) { public Result<SelectResult> getJobData(@RequestParam String jobId) {
return Result.succeed(studioService.getJobData(jobId)); return Result.succeed(studioService.getJobData(jobId));
} }
/** 根据jobId获取数据 */ /** 根据jobId获取数据 */
@GetMapping("/getCommonSqlData") @GetMapping("/getCommonSqlData")
@ApiOperation("Get Common Sql Data") @ApiOperation("Get Common Sql Data")
...@@ -203,54 +131,6 @@ public class StudioController { ...@@ -203,54 +131,6 @@ public class StudioController {
return Result.succeed(jobs.toArray(new JsonNode[0])); 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 */ /** 获取 Meta Store Catalog 和 Database */
@PostMapping("/getMSCatalogs") @PostMapping("/getMSCatalogs")
@ApiOperation("Get Catalog List") @ApiOperation("Get Catalog List")
......
...@@ -20,21 +20,21 @@ ...@@ -20,21 +20,21 @@
package org.dinky.controller; package org.dinky.controller;
import org.dinky.data.annotation.Log; import org.dinky.data.annotation.Log;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.TaskRollbackVersionDTO; import org.dinky.data.dto.TaskRollbackVersionDTO;
import org.dinky.data.enums.BusinessType; import org.dinky.data.enums.BusinessType;
import org.dinky.data.enums.JobLifeCycle; import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.JobStatus;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.enums.TaskOperatingSavepointSelect; import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.model.Task; import org.dinky.data.model.Task;
import org.dinky.data.result.ProTableResult; import org.dinky.data.result.ProTableResult;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.gateway.result.SavePointResult;
import org.dinky.job.JobResult; import org.dinky.job.JobResult;
import org.dinky.process.exception.ExcuteException;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.utils.TaskOneClickOperatingUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
...@@ -47,8 +47,8 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -47,8 +47,8 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.lang.tree.Tree;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
...@@ -56,11 +56,6 @@ import io.swagger.annotations.ApiOperation; ...@@ -56,11 +56,6 @@ import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/**
* 任务 Controller
*
* @since 2021-05-24
*/
@Slf4j @Slf4j
@RestController @RestController
@Api(tags = "Task Controller") @Api(tags = "Task Controller")
...@@ -70,7 +65,69 @@ public class TaskController { ...@@ -70,7 +65,69 @@ public class TaskController {
private final TaskService taskService; private final TaskService taskService;
/** 新增或者更新 */ @GetMapping("/submitTask")
@ApiOperation("Submit Task")
@Log(title = "Submit Task", businessType = BusinessType.SUBMIT)
public Result<JobResult> submitTask(@RequestParam Integer id) throws ExcuteException {
JobResult jobResult = taskService.submitTask(id, null);
if (jobResult.isSuccess()) {
return Result.succeed(jobResult, Status.EXECUTE_SUCCESS);
} else {
return Result.failed(jobResult, jobResult.getError());
}
}
@GetMapping("/cancel")
@Log(title = "Cancel Flink Job", businessType = BusinessType.TRIGGER)
@ApiOperation("Cancel Flink Job")
public Result<Boolean> cancel(@RequestParam Integer id) {
return Result.succeed(taskService.cancelTaskJob(taskService.getTaskInfoById(id)), Status.EXECUTE_SUCCESS);
}
/** 重启任务 */
@GetMapping(value = "/restartTask")
@ApiOperation("Restart Task")
@Log(title = "Restart Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<JobResult> restartTask(@RequestParam Integer id, @RequestParam String savePointPath)
throws ExcuteException {
return Result.succeed(taskService.restartTask(id, savePointPath));
}
@GetMapping("/savepoint")
@Log(title = "Savepoint Trigger", businessType = BusinessType.TRIGGER)
@ApiOperation("Savepoint Trigger")
public Result<SavePointResult> savepoint(@RequestParam Integer taskId, @RequestParam String savePointType) {
return Result.succeed(
taskService.savepointTaskJob(taskService.getTaskInfoById(taskId), savePointType),
Status.EXECUTE_SUCCESS);
}
@GetMapping("/onLineTask")
@Log(title = "onLineTask", businessType = BusinessType.TRIGGER)
@ApiOperation("onLineTask")
public Result<Boolean> onLineTask(@RequestParam Integer taskId) {
return Result.succeed(taskService.changeTaskLifeRecyle(taskId, JobLifeCycle.ONLINE));
}
@GetMapping("/offLineTask")
@Log(title = "offLineTask", businessType = BusinessType.TRIGGER)
@ApiOperation("offLineTask")
public Result<Boolean> offLineTask(@RequestParam Integer taskId) {
return Result.succeed(taskService.changeTaskLifeRecyle(taskId, JobLifeCycle.DEVELOP));
}
@PostMapping("/explainSql")
@ApiOperation("Explain Sql")
public Result<List<SqlExplainResult>> explainSql(@RequestBody TaskDTO taskDTO) throws NotSupportExplainExcepition {
return Result.succeed(taskService.explainTask(taskDTO), Status.EXECUTE_SUCCESS);
}
@PostMapping("/getJobPlan")
@ApiOperation("Get Job Plan")
public Result<ObjectNode> getJobPlan(@RequestBody TaskDTO taskDTO) {
return Result.succeed(taskService.getJobPlan(taskDTO), Status.EXECUTE_SUCCESS);
}
@PutMapping @PutMapping
@ApiOperation("Insert Or Update Task") @ApiOperation("Insert Or Update Task")
@Log(title = "Insert Or Update Task", businessType = BusinessType.INSERT_OR_UPDATE) @Log(title = "Insert Or Update Task", businessType = BusinessType.INSERT_OR_UPDATE)
...@@ -89,7 +146,6 @@ public class TaskController { ...@@ -89,7 +146,6 @@ public class TaskController {
} }
} }
/** 动态查询列表 */
@PostMapping @PostMapping
@ApiOperation("Query Task List") @ApiOperation("Query Task List")
@ApiImplicitParam( @ApiImplicitParam(
...@@ -103,41 +159,6 @@ public class TaskController { ...@@ -103,41 +159,6 @@ public class TaskController {
return taskService.selectForProTable(para); return taskService.selectForProTable(para);
} }
/** 批量执行 */
@PostMapping(value = "/submit")
@ApiOperation("Batch Execute Task")
@Log(title = "Batch Execute Task", businessType = BusinessType.UPDATE)
@ApiImplicitParam(
name = "para",
value = "Task Id List",
required = true,
dataType = "JsonNode",
paramType = "body",
dataTypeClass = JsonNode.class)
public Result<List<JobResult>> submit(@RequestBody JsonNode para) {
// todo: 没有批量提交 此处需要重构
if (para.size() > 0) {
List<JobResult> results = new ArrayList<>();
List<Integer> error = new ArrayList<>();
for (final JsonNode item : para) {
Integer id = item.asInt();
JobResult result = taskService.submitTask(id);
if (!result.isSuccess()) {
error.add(id);
}
results.add(result);
}
if (error.size() == 0) {
return Result.succeed(results, "执行成功");
} else {
return Result.succeed(results, "执行部分成功,但" + error + "执行失败,共" + error.size() + "次失败。");
}
} else {
return Result.failed("请选择要执行的记录");
}
}
/** 获取指定ID的信息 */
@GetMapping @GetMapping
@ApiOperation("Get Task Info By Id") @ApiOperation("Get Task Info By Id")
@ApiImplicitParam( @ApiImplicitParam(
...@@ -147,41 +168,16 @@ public class TaskController { ...@@ -147,41 +168,16 @@ public class TaskController {
dataType = "Integer", dataType = "Integer",
paramType = "query", paramType = "query",
dataTypeClass = Integer.class) dataTypeClass = Integer.class)
public Result<Task> getOneById(@RequestParam Integer id) { public Result<TaskDTO> getOneById(@RequestParam Integer id) {
Task task = taskService.getTaskInfoById(id); return Result.succeed(taskService.getTaskInfoById(id));
return Result.succeed(task);
} }
/** 获取所有可用的 FlinkSQLEnv */
@GetMapping(value = "/listFlinkSQLEnv") @GetMapping(value = "/listFlinkSQLEnv")
@ApiOperation("Get All FlinkSQLEnv") @ApiOperation("Get All FlinkSQLEnv")
public Result<List<Task>> listFlinkSQLEnv() { public Result<List<Task>> listFlinkSQLEnv() {
return Result.succeed(taskService.listFlinkSQLEnv()); return Result.succeed(taskService.listFlinkSQLEnv());
} }
/** 导出 sql */
@GetMapping(value = "/exportSql")
@ApiOperation("Export Sql")
@Log(title = "Export Sql", businessType = BusinessType.EXPORT)
@ApiImplicitParam(
name = "id",
value = "Task Id",
required = true,
dataType = "Integer",
paramType = "query",
dataTypeClass = Integer.class)
public Result<String> exportSql(@RequestParam Integer id) {
return Result.succeed(taskService.exportSql(id));
}
/** 发布任务 */
@GetMapping(value = "/releaseTask")
@ApiOperation("Release Task")
@Log(title = "Release Task", businessType = BusinessType.UPDATE)
public Result<Void> releaseTask(@RequestParam Integer id) {
return taskService.releaseTask(id);
}
@PostMapping("/rollbackTask") @PostMapping("/rollbackTask")
@ApiOperation("Rollback Task") @ApiOperation("Rollback Task")
@Log(title = "Rollback Task", businessType = BusinessType.UPDATE) @Log(title = "Rollback Task", businessType = BusinessType.UPDATE)
...@@ -189,79 +185,12 @@ public class TaskController { ...@@ -189,79 +185,12 @@ public class TaskController {
return taskService.rollbackTask(dto); return taskService.rollbackTask(dto);
} }
/** 维护任务 */
@GetMapping(value = "/developTask")
@ApiOperation("Develop Task")
@Log(title = "Develop Task", businessType = BusinessType.UPDATE)
public Result<Boolean> developTask(@RequestParam Integer id) {
return Result.succeed(taskService.developTask(id), Status.OPERATE_SUCCESS);
}
/** 上线任务 */
@GetMapping(value = "/onLineTask")
@ApiOperation("OnLine Task")
@Log(title = "OnLine Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<JobResult> onLineTask(@RequestParam Integer id) {
return taskService.onLineTask(id);
}
/** 下线任务 */
@GetMapping(value = "/offLineTask")
@ApiOperation("OffLine Task")
@Log(title = "OffLine Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<Void> offLineTask(@RequestParam Integer id, @RequestParam String type) {
return taskService.offLineTask(id, type);
}
/** 注销任务 */
@GetMapping(value = "/cancelTask")
@ApiOperation("Cancel Task")
@Log(title = "Cancel Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<Void> cancelTask(@RequestParam Integer id) {
return taskService.cancelTask(id);
}
/** 恢复任务 */
@GetMapping(value = "/recoveryTask")
@ApiOperation("Recovery Task")
@Log(title = "Recovery Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<Boolean> recoveryTask(@RequestParam Integer id) {
return Result.succeed(taskService.recoveryTask(id), Status.OPERATE_SUCCESS);
}
/** 重启任务 */
@GetMapping(value = "/restartTask")
@ApiOperation("Restart Task")
@Log(title = "Restart Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<JobResult> restartTask(@RequestParam Integer id, @RequestParam Boolean isOnLine) {
if (isOnLine) {
return taskService.reOnLineTask(id, null);
} else {
return Result.succeed(taskService.restartTask(id, null), Status.RESTART_SUCCESS);
}
}
/** 选择保存点重启任务 */
@GetMapping(value = "/selectSavePointRestartTask")
@ApiOperation("Select Save Point Restart Task")
@Log(title = "Select Save Point Restart Task", businessType = BusinessType.REMOTE_OPERATION)
public Result<JobResult> selectSavePointRestartTask(
@RequestParam Integer id, @RequestParam Boolean isOnLine, @RequestParam String savePointPath) {
if (isOnLine) {
return taskService.reOnLineTask(id, savePointPath);
} else {
return Result.succeed(taskService.restartTask(id, savePointPath), Status.RESTART_SUCCESS);
}
}
/** 获取当前的 API 的地址 */
@GetMapping(value = "/getTaskAPIAddress") @GetMapping(value = "/getTaskAPIAddress")
@ApiOperation("Get Task API Address") @ApiOperation("Get Task API Address")
public Result<String> getTaskAPIAddress() { public Result<String> getTaskAPIAddress() {
return Result.succeed(taskService.getTaskAPIAddress(), Status.RESTART_SUCCESS); return Result.succeed(taskService.getTaskAPIAddress(), Status.RESTART_SUCCESS);
} }
/** 导出json */
@GetMapping(value = "/exportJsonByTaskId") @GetMapping(value = "/exportJsonByTaskId")
@ApiOperation("Export Task To Sign Json") @ApiOperation("Export Task To Sign Json")
@Log(title = "Export Task To Sign Json", businessType = BusinessType.EXPORT) @Log(title = "Export Task To Sign Json", businessType = BusinessType.EXPORT)
...@@ -269,7 +198,6 @@ public class TaskController { ...@@ -269,7 +198,6 @@ public class TaskController {
return Result.succeed(taskService.exportJsonByTaskId(id)); return Result.succeed(taskService.exportJsonByTaskId(id));
} }
/** 导出json数组 */
@PostMapping(value = "/exportJsonByTaskIds") @PostMapping(value = "/exportJsonByTaskIds")
@ApiOperation("Export Task To Array Json") @ApiOperation("Export Task To Array Json")
@Log(title = "Export Task To Array Json", businessType = BusinessType.EXPORT) @Log(title = "Export Task To Array Json", businessType = BusinessType.EXPORT)
...@@ -277,7 +205,6 @@ public class TaskController { ...@@ -277,7 +205,6 @@ public class TaskController {
return Result.succeed(taskService.exportJsonByTaskIds(para)); return Result.succeed(taskService.exportJsonByTaskIds(para));
} }
/** json文件上传 导入task */
@PostMapping(value = "/uploadTaskJson") @PostMapping(value = "/uploadTaskJson")
@ApiOperation("Upload Task Json") @ApiOperation("Upload Task Json")
@Log(title = "Upload Task Json", businessType = BusinessType.UPLOAD) @Log(title = "Upload Task Json", businessType = BusinessType.UPLOAD)
...@@ -285,83 +212,9 @@ public class TaskController { ...@@ -285,83 +212,9 @@ public class TaskController {
return taskService.uploadTaskJson(file); return taskService.uploadTaskJson(file);
} }
/**
* 查询所有目录
*
* @return {@link Result}<{@link Tree}<{@link Integer}>>
*/
@GetMapping("/queryAllCatalogue") @GetMapping("/queryAllCatalogue")
@ApiOperation("Query All Catalogue") @ApiOperation("Query All Catalogue")
public Result<Tree<Integer>> queryAllCatalogue() { public Result<Tree<Integer>> queryAllCatalogue() {
return taskService.queryAllCatalogue(); return taskService.queryAllCatalogue();
} }
/**
* 查询对应操作的任务列表
*
* @param operating 操作
* @param catalogueId 目录id
* @return {@link Result}<{@link List}<{@link Task}>>
*/
@GetMapping("/queryOnClickOperatingTask")
@ApiOperation("Query On Click Operating Task")
public Result<List<Task>> queryOnClickOperatingTask(
@RequestParam("operating") Integer operating, @RequestParam("catalogueId") Integer catalogueId) {
if (operating == null) {
return Result.failed(Status.OPERATE_FAILED);
}
switch (operating) {
case 1:
return taskService.queryOnLineTaskByDoneStatus(
Collections.singletonList(JobLifeCycle.RELEASE),
JobStatus.getAllDoneStatus(),
true,
catalogueId);
case 2:
return taskService.queryOnLineTaskByDoneStatus(
Collections.singletonList(JobLifeCycle.ONLINE),
Collections.singletonList(JobStatus.RUNNING),
false,
catalogueId);
default:
return Result.failed(Status.OPERATE_FAILED);
}
}
/**
* 一键操作任务
*
* @param operating 操作
* @return {@link Result}<{@link Void}>
*/
@PostMapping("/onClickOperatingTask")
@ApiOperation("On Click Operating Task")
public Result<Void> onClickOperatingTask(@RequestBody JsonNode operating) {
if (operating == null || operating.get("operating") == null) {
return Result.failed(Status.OPERATE_FAILED);
}
switch (operating.get("operating").asInt()) {
case 1:
final JsonNode savepointSelect = operating.get("taskOperatingSavepointSelect");
return TaskOneClickOperatingUtil.oneClickOnline(
TaskOneClickOperatingUtil.parseJsonNode(operating),
TaskOperatingSavepointSelect.valueByCode(
savepointSelect == null ? 0 : savepointSelect.asInt()));
case 2:
return TaskOneClickOperatingUtil.onClickOffline(TaskOneClickOperatingUtil.parseJsonNode(operating));
default:
return Result.failed(Status.OPERATE_FAILED);
}
}
/**
* 查询一键操作任务状态
*
* @return {@link Result}<{@link Dict}>
*/
@GetMapping("/queryOneClickOperatingTaskStatus")
@ApiOperation("Query One Click Operating Task Status")
public Result<Dict> queryOneClickOperatingTaskStatus() {
return TaskOneClickOperatingUtil.queryOneClickOperatingTaskStatus();
}
} }
...@@ -21,6 +21,7 @@ package org.dinky.data.dto; ...@@ -21,6 +21,7 @@ package org.dinky.data.dto;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.gateway.config.GatewayConfig; import org.dinky.gateway.config.GatewayConfig;
import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import java.util.Map; import java.util.Map;
...@@ -119,25 +120,23 @@ public class APIExecuteSqlDTO extends AbstractStatementDTO { ...@@ -119,25 +120,23 @@ public class APIExecuteSqlDTO extends AbstractStatementDTO {
public JobConfig getJobConfig() { public JobConfig getJobConfig() {
int savePointStrategy = Asserts.isNotNullString(savePointPath) ? 3 : 0; int savePointStrategy = Asserts.isNotNullString(savePointPath) ? 3 : 0;
return JobConfig.builder()
return new JobConfig( .type(type)
type, .useResult(useResult)
useResult, .useChangeLog(useChangeLog)
useChangeLog, .useAutoCancel(useAutoCancel)
useAutoCancel, .useRemote(true)
false, .address(address)
null, .jobName(jobName)
true, .fragment(isFragment())
address, .statementSet(useStatementSet)
jobName, .maxRowNum(maxRowNum)
isFragment(), .checkpoint(checkPoint)
useStatementSet, .parallelism(parallelism)
maxRowNum, .savePointStrategy(SavePointStrategy.get(savePointStrategy))
checkPoint, .savePointPath(savePointPath)
parallelism, .configJson(configuration)
savePointStrategy, .gatewayConfig(gatewayConfig)
savePointPath, .build();
configuration,
gatewayConfig);
} }
} }
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.data.dto; package org.dinky.data.dto;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import java.util.Map; import java.util.Map;
...@@ -55,6 +56,13 @@ public class APIExplainSqlDTO extends AbstractStatementDTO { ...@@ -55,6 +56,13 @@ public class APIExplainSqlDTO extends AbstractStatementDTO {
private Map<String, String> configuration; private Map<String, String> configuration;
public JobConfig getJobConfig() { 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; ...@@ -23,6 +23,7 @@ import java.util.Map;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/** /**
* AbstractStatementDTO * AbstractStatementDTO
...@@ -30,6 +31,7 @@ import io.swagger.annotations.ApiModelProperty; ...@@ -30,6 +31,7 @@ import io.swagger.annotations.ApiModelProperty;
* @since 2021/12/29 * @since 2021/12/29
*/ */
@ApiModel(value = "AbstractStatementDTO", description = "Abstract Statement Data Transfer Object") @ApiModel(value = "AbstractStatementDTO", description = "Abstract Statement Data Transfer Object")
@Data
public class AbstractStatementDTO { public class AbstractStatementDTO {
@ApiModelProperty(value = "Statement", dataType = "String", example = "SELECT * FROM table", notes = "SQL语句") @ApiModelProperty(value = "Statement", dataType = "String", example = "SELECT * FROM table", notes = "SQL语句")
...@@ -47,36 +49,4 @@ public class AbstractStatementDTO { ...@@ -47,36 +49,4 @@ public class AbstractStatementDTO {
example = "{\"key\": \"value\"}", example = "{\"key\": \"value\"}",
notes = "变量集合") notes = "变量集合")
private Map<String, String> variables; 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; ...@@ -21,6 +21,7 @@ package org.dinky.data.dto;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Getter; import lombok.Getter;
...@@ -85,6 +86,8 @@ public class StudioDDLDTO { ...@@ -85,6 +86,8 @@ public class StudioDDLDTO {
private Integer maxRowNum = 10000; private Integer maxRowNum = 10000;
public JobConfig getJobConfig() { 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 { ...@@ -65,27 +65,15 @@ public class StudioMetaStoreDTO extends AbstractStatementDTO {
private Integer databaseId; private Integer databaseId;
public JobConfig getJobConfig() { public JobConfig getJobConfig() {
return new JobConfig( return JobConfig.builder()
GatewayType.LOCAL.getLongValue(), .type(GatewayType.LOCAL.getLongValue())
true, .useResult(true)
false, .useChangeLog(false)
false, .useAutoCancel(false)
false, .fragment(isFragment())
null, .statementSet(false)
null, .batchModel(false)
null, .maxRowNum(0)
null, .build();
null,
null,
isFragment(),
false,
false,
0,
null,
null,
null,
null,
null,
null);
} }
} }
...@@ -19,12 +19,20 @@ ...@@ -19,12 +19,20 @@
package org.dinky.data.dto; package org.dinky.data.dto;
import org.dinky.config.Dialect;
import org.dinky.data.model.Task;
import org.dinky.data.model.TaskExtConfig; import org.dinky.data.model.TaskExtConfig;
import org.dinky.data.typehandler.TaskExtConfigTypeHandler;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import org.apache.ibatis.type.JdbcType;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.baomidou.mybatisplus.annotation.TableField;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Getter; import lombok.Getter;
...@@ -34,13 +42,18 @@ import lombok.extern.slf4j.Slf4j; ...@@ -34,13 +42,18 @@ import lombok.extern.slf4j.Slf4j;
/** /**
* StudioExecuteDTO * StudioExecuteDTO
* *
* @since 2021/5/30 11:09
*/ */
@Getter @Getter
@Setter @Setter
@Slf4j @Slf4j
@ApiModel(value = "StudioExecuteDTO", description = "DTO for executing SQL queries") @ApiModel(value = "StudioExecuteDTO", description = "DTO for executing SQL queries")
public class StudioExecuteDTO extends AbstractStatementDTO { public class TaskDTO extends AbstractStatementDTO {
@ApiModelProperty(value = "Name", required = true, dataType = "String", example = "Name")
private String name;
@ApiModelProperty(value = "Dialect", dataType = "String", notes = "Dialect for the task")
private String dialect;
@ApiModelProperty( @ApiModelProperty(
value = "Run Mode", value = "Run Mode",
...@@ -49,33 +62,32 @@ public class StudioExecuteDTO extends AbstractStatementDTO { ...@@ -49,33 +62,32 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
notes = "The execution mode for the SQL query") notes = "The execution mode for the SQL query")
private String type; private String type;
@ApiModelProperty( @ApiModelProperty(value = "Check Point", dataType = "Integer", example = "1", notes = "Check point for the task")
value = "Dialect", private Integer checkPoint;
dataType = "String",
example = "MySQL",
notes = "The SQL dialect for the query")
private String dialect;
@ApiModelProperty( @ApiModelProperty(
value = "Use Result", value = "Save Point Strategy",
dataType = "boolean", dataType = "Integer",
example = "true", example = "1",
notes = "Flag indicating whether to use the query result") notes = "The save point strategy")
private boolean useResult; private Integer savePointStrategy;
@ApiModelProperty( @ApiModelProperty(
value = "Use Change Log", value = "Save Point Path",
dataType = "boolean", dataType = "String",
example = "false", example = "/savepoints",
notes = "Flag indicating whether to use change logs") notes = "The path for save points")
private boolean useChangeLog; private String savePointPath;
@ApiModelProperty(value = "Parallelism", dataType = "Integer", example = "4", notes = "The parallelism level")
private Integer parallelism;
@ApiModelProperty( @ApiModelProperty(
value = "Use Auto Cancel", value = "Fragment",
dataType = "boolean", dataType = "Boolean",
example = "false", example = "true",
notes = "Flag indicating whether to use auto-canceling") notes = "Fragment option for the task")
private boolean useAutoCancel; private Boolean fragment;
@ApiModelProperty( @ApiModelProperty(
value = "Use Statement Set", value = "Use Statement Set",
...@@ -91,16 +103,6 @@ public class StudioExecuteDTO extends AbstractStatementDTO { ...@@ -91,16 +103,6 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
notes = "Flag indicating whether to use batch processing") notes = "Flag indicating whether to use batch processing")
private boolean batchModel; private boolean batchModel;
@ApiModelProperty(
value = "Use Session",
dataType = "boolean",
example = "false",
notes = "Flag indicating whether to use a session")
private boolean useSession;
@ApiModelProperty(value = "Session", dataType = "String", example = "session_id", notes = "The session identifier")
private String session;
@ApiModelProperty( @ApiModelProperty(
value = "Cluster ID", value = "Cluster ID",
dataType = "Integer", dataType = "Integer",
...@@ -125,79 +127,143 @@ public class StudioExecuteDTO extends AbstractStatementDTO { ...@@ -125,79 +127,143 @@ public class StudioExecuteDTO extends AbstractStatementDTO {
@ApiModelProperty(value = "JAR ID", dataType = "Integer", example = "4", notes = "The identifier of the JAR") @ApiModelProperty(value = "JAR ID", dataType = "Integer", example = "4", notes = "The identifier of the JAR")
private Integer jarId; private Integer jarId;
@ApiModelProperty(value = "Job Name", dataType = "String", example = "MyJob", notes = "The name of the job")
private String jobName;
@ApiModelProperty(value = "Task ID", dataType = "Integer", example = "5", notes = "The identifier of the task")
private Integer taskId;
@ApiModelProperty(value = "ID", dataType = "Integer", example = "6", notes = "The identifier of the execution")
private Integer id;
@ApiModelProperty( @ApiModelProperty(
value = "Max Row Number", value = "Alert Group ID",
dataType = "Integer", dataType = "Integer",
example = "100", example = "7001",
notes = "The maximum number of rows to return") notes = "ID of the alert group associated with the task")
private Integer maxRowNum; private Integer alertGroupId;
@ApiModelProperty(value = "Check Point", dataType = "Integer", example = "0", notes = "The check point value") @ApiModelProperty(value = "Note", dataType = "String", notes = "Additional notes for the task")
private Integer checkPoint; private String note;
@ApiModelProperty(value = "Parallelism", dataType = "Integer", example = "4", notes = "The parallelism level") @ApiModelProperty(value = "Step", dataType = "Integer", example = "1", notes = "Step for the task")
private Integer parallelism; private Integer step;
@ApiModelProperty( @ApiModelProperty(
value = "Save Point Strategy", value = "Job Instance ID",
dataType = "Integer", dataType = "Integer",
example = "1", example = "8001",
notes = "The save point strategy") notes = "ID of the job instance associated with the task")
private Integer savePointStrategy; private Integer jobInstanceId;
@ApiModelProperty( @ApiModelProperty(
value = "Save Point Path", value = "Job status",
dataType = "String", dataType = "String",
example = "/savepoints", example = "RUNNING",
notes = "The path for save points") notes = "THE_RUNNING_STATUS_OF_THE_CURRENT_TASK")
private String savePointPath; private String status;
@ApiModelProperty(
value = "Version ID",
dataType = "Integer",
example = "9001",
notes = "ID of the version associated with the task")
private Integer versionId;
@ApiModelProperty(value = "Enabled", required = true, dataType = "Boolean", example = "true")
private Boolean enabled;
@ApiModelProperty(value = "Statement", dataType = "String", notes = "SQL statement for the task")
private String statement;
@ApiModelProperty(value = "Cluster Name", dataType = "String", notes = "Name of the associated cluster")
@TableField(exist = false)
private String clusterName;
@ApiModelProperty( @ApiModelProperty(
value = "Configuration JSON", value = "Configuration JSON",
dataType = "Object", dataType = "TaskExtConfig",
example = "{}", notes = "Extended configuration in JSON format for the task")
notes = "The JSON configuration for the query") @TableField(typeHandler = TaskExtConfigTypeHandler.class, jdbcType = JdbcType.VARCHAR)
private TaskExtConfig configJson; 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;
@ApiModelProperty(
value = "UseResult",
dataType = "boolean",
example = "true",
notes = "Flagindicatingwhethertousethequeryresult")
private boolean useResult;
@ApiModelProperty(
value = "UseChangeLog",
dataType = "boolean",
example = "false",
notes = "Flagindicatingwhethertousechangelogs")
private boolean useChangeLog;
@ApiModelProperty(
value = "Use Auto Cancel",
dataType = "boolean",
example = "false",
notes = "Flag indicating whether to use auto-canceling")
private boolean useAutoCancel;
@ApiModelProperty(value = "Session", dataType = "String", example = "session_id", notes = "The session identifier")
private String session;
@ApiModelProperty(value = "Job Name", dataType = "String", example = "MyJob", notes = "The name of the job")
private String jobName;
@ApiModelProperty(value = "ID", dataType = "Integer", example = "6", notes = "The identifier of the execution")
private Integer id;
@ApiModelProperty(
value = "Max Row Number",
dataType = "Integer",
example = "100",
notes = "The maximum number of rows to return")
private Integer maxRowNum;
public JobConfig getJobConfig() { public JobConfig getJobConfig() {
Map<String, String> parsedConfig = Map<String, String> parsedConfig =
this.configJson == null ? new HashMap<>(0) : this.configJson.getCustomConfigMaps(); this.configJson == null ? new HashMap<>(0) : this.configJson.getCustomConfigMaps();
return new JobConfig( JobConfig jobConfig = new JobConfig();
type, BeanUtil.copyProperties(this, jobConfig);
useResult, jobConfig.setConfigJson(parsedConfig);
useChangeLog, jobConfig.setJarTask(isJarTask());
useAutoCancel, jobConfig.setTaskId(id);
useSession, jobConfig.setJobName(name);
session,
clusterId, return jobConfig;
clusterConfigurationId, }
jarId,
taskId, public Task buildTask() {
jobName, Task task = new Task();
isFragment(), BeanUtil.copyProperties(this, task);
statementSet, return task;
batchModel,
maxRowNum,
checkPoint,
parallelism,
savePointStrategy,
savePointPath,
getVariables(),
parsedConfig);
} }
public Integer getTaskId() { public boolean isJarTask() {
return taskId == null ? getId() : taskId; return Dialect.isJarDialect(dialect);
} }
} }
/*
*
* 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 @@ ...@@ -19,23 +19,13 @@
package org.dinky.data.model; package org.dinky.data.model;
import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect;
import org.dinky.data.typehandler.TaskExtConfigTypeHandler; import org.dinky.data.typehandler.TaskExtConfigTypeHandler;
import org.dinky.job.JobConfig;
import org.dinky.mybatis.model.SuperEntity; import org.dinky.mybatis.model.SuperEntity;
import org.apache.ibatis.type.JdbcType; 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.TableField;
import com.baomidou.mybatisplus.annotation.TableName; 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.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
...@@ -73,11 +63,7 @@ public class Task extends SuperEntity<Task> { ...@@ -73,11 +63,7 @@ public class Task extends SuperEntity<Task> {
@ApiModelProperty(value = "Check Point", dataType = "Integer", example = "1", notes = "Check point for the task") @ApiModelProperty(value = "Check Point", dataType = "Integer", example = "1", notes = "Check point for the task")
private Integer checkPoint; private Integer checkPoint;
@ApiModelProperty( @ApiModelProperty(value = "Save point strategy", dataType = "SavePointStrategy", notes = "Save point strategy")
value = "Save Point Strategy",
dataType = "Integer",
example = "2",
notes = "Save point strategy for the task")
private Integer savePointStrategy; private Integer savePointStrategy;
@ApiModelProperty(value = "Save Point Path", dataType = "String", notes = "Save point path for the task") @ApiModelProperty(value = "Save Point Path", dataType = "String", notes = "Save point path for the task")
...@@ -149,6 +135,13 @@ public class Task extends SuperEntity<Task> { ...@@ -149,6 +135,13 @@ public class Task extends SuperEntity<Task> {
notes = "ID of the alert group associated with the task") notes = "ID of the alert group associated with the task")
private Integer alertGroupId; 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") @ApiModelProperty(value = "Note", dataType = "String", notes = "Additional notes for the task")
private String note; private String note;
...@@ -170,126 +163,5 @@ public class Task extends SuperEntity<Task> { ...@@ -170,126 +163,5 @@ public class Task extends SuperEntity<Task> {
private Integer versionId; private Integer versionId;
@ApiModelProperty(value = "Statement", dataType = "String", notes = "SQL statement for the task") @ApiModelProperty(value = "Statement", dataType = "String", notes = "SQL statement for the task")
@TableField(exist = false)
private String statement; 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; ...@@ -22,7 +22,7 @@ package org.dinky.data.model;
import org.dinky.data.dto.TaskVersionConfigureDTO; import org.dinky.data.dto.TaskVersionConfigureDTO;
import java.io.Serializable; import java.io.Serializable;
import java.util.Date; import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
...@@ -83,5 +83,5 @@ public class TaskVersion implements Serializable { ...@@ -83,5 +83,5 @@ public class TaskVersion implements Serializable {
@ApiModelProperty(value = "Create Time", dataType = "Date", notes = "Timestamp when the version was created") @ApiModelProperty(value = "Create Time", dataType = "Date", notes = "Timestamp when the version was created")
@TableField(value = "create_time") @TableField(value = "create_time")
private Date createTime; private LocalDateTime createTime;
} }
...@@ -29,6 +29,7 @@ import org.dinky.context.FreeMarkerHolder; ...@@ -29,6 +29,7 @@ import org.dinky.context.FreeMarkerHolder;
import org.dinky.context.SpringContextUtils; import org.dinky.context.SpringContextUtils;
import org.dinky.daemon.pool.DefaultThreadPool; import org.dinky.daemon.pool.DefaultThreadPool;
import org.dinky.data.dto.AlertRuleDTO; import org.dinky.data.dto.AlertRuleDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.model.AlertGroup; import org.dinky.data.model.AlertGroup;
import org.dinky.data.model.AlertHistory; import org.dinky.data.model.AlertHistory;
...@@ -36,7 +37,6 @@ import org.dinky.data.model.AlertInstance; ...@@ -36,7 +37,6 @@ import org.dinky.data.model.AlertInstance;
import org.dinky.data.model.JobInfoDetail; import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobInstance; import org.dinky.data.model.JobInstance;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Task;
import org.dinky.data.options.AlertRuleOptions; import org.dinky.data.options.AlertRuleOptions;
import org.dinky.service.AlertGroupService; import org.dinky.service.AlertGroupService;
import org.dinky.service.AlertHistoryService; import org.dinky.service.AlertHistoryService;
...@@ -214,7 +214,7 @@ public class JobAlertHandler { ...@@ -214,7 +214,7 @@ public class JobAlertHandler {
private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) { private void executeAlertAction(Facts facts, AlertRuleDTO alertRuleDTO) {
JobInfoDetail jobInfoDetail = facts.get(AlertRuleOptions.JOB_ALERT_RULE_JOB_DETAIL); JobInfoDetail jobInfoDetail = facts.get(AlertRuleOptions.JOB_ALERT_RULE_JOB_DETAIL);
JobInstance jobInstance = jobInfoDetail.getInstance(); JobInstance jobInstance = jobInfoDetail.getInstance();
Task task = taskService.getById(jobInfoDetail.getInstance().getTaskId()); TaskDTO task = taskService.getTaskInfoById(jobInfoDetail.getInstance().getTaskId());
String taskUrl = StrFormatter.format( String taskUrl = StrFormatter.format(
"{}/#/devops/job-detail?id={}", "{}/#/devops/job-detail?id={}",
......
...@@ -19,35 +19,9 @@ ...@@ -19,35 +19,9 @@
package org.dinky.service; 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 * APIService
* *
* @since 2021/12/11 21:45 * @since 2021/12/11 21:45
*/ */
public interface APIService { 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);
}
...@@ -19,11 +19,15 @@ ...@@ -19,11 +19,15 @@
package org.dinky.service; 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.Column;
import org.dinky.data.model.DataBase; import org.dinky.data.model.DataBase;
import org.dinky.data.model.QueryData; import org.dinky.data.model.QueryData;
import org.dinky.data.model.Schema; import org.dinky.data.model.Schema;
import org.dinky.data.model.SqlGeneration; 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.metadata.result.JdbcSelectResult;
import org.dinky.mybatis.service.ISuperService; import org.dinky.mybatis.service.ISuperService;
...@@ -136,4 +140,8 @@ public interface DataBaseService extends ISuperService<DataBase> { ...@@ -136,4 +140,8 @@ public interface DataBaseService extends ISuperService<DataBase> {
* @return {@link Boolean} * @return {@link Boolean}
*/ */
Boolean copyDatabase(DataBase database); Boolean copyDatabase(DataBase database);
List<SqlExplainResult> explainCommonSql(TaskDTO task);
JobResult executeCommonSql(SqlDTO sqlDTO);
} }
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.service; package org.dinky.service;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Savepoints; import org.dinky.data.model.Savepoints;
import org.dinky.mybatis.service.ISuperService; import org.dinky.mybatis.service.ISuperService;
...@@ -36,4 +37,6 @@ public interface SavepointsService extends ISuperService<Savepoints> { ...@@ -36,4 +37,6 @@ public interface SavepointsService extends ISuperService<Savepoints> {
Savepoints getLatestSavepointByTaskId(Integer taskId); Savepoints getLatestSavepointByTaskId(Integer taskId);
Savepoints getEarliestSavepointByTaskId(Integer taskId); Savepoints getEarliestSavepointByTaskId(Integer taskId);
Savepoints getSavePointWithStrategy(TaskDTO task);
} }
...@@ -19,25 +19,20 @@ ...@@ -19,25 +19,20 @@
package org.dinky.service; package org.dinky.service;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.StudioCADTO; import org.dinky.data.dto.StudioCADTO;
import org.dinky.data.dto.StudioDDLDTO; import org.dinky.data.dto.StudioDDLDTO;
import org.dinky.data.dto.StudioExecuteDTO;
import org.dinky.data.dto.StudioMetaStoreDTO; import org.dinky.data.dto.StudioMetaStoreDTO;
import org.dinky.data.model.Catalog; import org.dinky.data.model.Catalog;
import org.dinky.data.model.FlinkColumn; import org.dinky.data.model.FlinkColumn;
import org.dinky.data.model.Schema; import org.dinky.data.model.Schema;
import org.dinky.data.result.IResult; import org.dinky.data.result.IResult;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
import org.dinky.data.result.SqlExplainResult;
import org.dinky.explainer.lineage.LineageResult; import org.dinky.explainer.lineage.LineageResult;
import org.dinky.job.JobResult;
import org.dinky.metadata.result.JdbcSelectResult; import org.dinky.metadata.result.JdbcSelectResult;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
/** /**
* StudioService * StudioService
...@@ -46,18 +41,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -46,18 +41,8 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
*/ */
public interface StudioService { public interface StudioService {
JobResult executeSql(StudioExecuteDTO studioExecuteDTO);
JobResult executeCommonSql(SqlDTO sqlDTO);
IResult executeDDL(StudioDDLDTO studioDDLDTO); IResult executeDDL(StudioDDLDTO studioDDLDTO);
List<SqlExplainResult> explainSql(StudioExecuteDTO studioExecuteDTO);
ObjectNode getStreamGraph(StudioExecuteDTO studioExecuteDTO);
ObjectNode getJobPlan(StudioExecuteDTO studioExecuteDTO);
JdbcSelectResult getCommonSqlData(Integer taskId); JdbcSelectResult getCommonSqlData(Integer taskId);
SelectResult getJobData(String jobId); SelectResult getJobData(String jobId);
...@@ -66,10 +51,6 @@ public interface StudioService { ...@@ -66,10 +51,6 @@ public interface StudioService {
List<JsonNode> listFlinkJobs(Integer clusterId); 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); List<Catalog> getMSCatalogs(StudioMetaStoreDTO studioMetaStoreDTO);
Schema getMSSchemaInfo(StudioMetaStoreDTO studioMetaStoreDTO); Schema getMSSchemaInfo(StudioMetaStoreDTO studioMetaStoreDTO);
......
...@@ -19,24 +19,27 @@ ...@@ -19,24 +19,27 @@
package org.dinky.service; 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.dto.TaskRollbackVersionDTO;
import org.dinky.data.enums.JobLifeCycle; import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.JobStatus; import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobModelOverview; import org.dinky.data.model.JobModelOverview;
import org.dinky.data.model.JobTypeOverView; import org.dinky.data.model.JobTypeOverView;
import org.dinky.data.model.Task; import org.dinky.data.model.Task;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.SqlExplainResult; 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.job.JobResult;
import org.dinky.mybatis.service.ISuperService; import org.dinky.mybatis.service.ISuperService;
import org.dinky.process.exception.ExcuteException;
import java.util.List; import java.util.List;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.lang.tree.Tree;
...@@ -47,45 +50,37 @@ import cn.hutool.core.lang.tree.Tree; ...@@ -47,45 +50,37 @@ import cn.hutool.core.lang.tree.Tree;
*/ */
public interface TaskService extends ISuperService<Task> { 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); ObjectNode getStreamGraph(TaskDTO taskDTO);
List<Task> listFlinkSQLEnv();
Task initDefaultFlinkSQLEnv(Integer tenantId);
String exportSql(Integer id); String exportSql(Integer id);
Task getUDFByClassName(String className); ObjectNode getJobPlan(TaskDTO task);
List<Task> getAllUDF();
Result<Void> releaseTask(Integer id);
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(); String getTaskAPIAddress();
...@@ -101,17 +96,8 @@ public interface TaskService extends ISuperService<Task> { ...@@ -101,17 +96,8 @@ public interface TaskService extends ISuperService<Task> {
Result<Tree<Integer>> queryAllCatalogue(); 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); Task getTaskByNameAndTenantId(String name, Integer tenantId);
JobStatus checkJobStatus(JobInfoDetail jobInfoDetail);
List<JobTypeOverView> getTaskOnlineRate(); List<JobTypeOverView> getTaskOnlineRate();
JobModelOverview getJobStreamingOrBatchModelOverview(); JobModelOverview getJobStreamingOrBatchModelOverview();
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.service; package org.dinky.service;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.TaskVersion; import org.dinky.data.model.TaskVersion;
import org.dinky.mybatis.service.ISuperService; import org.dinky.mybatis.service.ISuperService;
...@@ -32,4 +33,6 @@ public interface TaskVersionService extends ISuperService<TaskVersion> { ...@@ -32,4 +33,6 @@ public interface TaskVersionService extends ISuperService<TaskVersion> {
* @return java.util.List<org.dinky.data.model.TaskVersion> * @return java.util.List<org.dinky.data.model.TaskVersion>
*/ */
List<TaskVersion> getTaskVersionByTaskId(Integer taskId); List<TaskVersion> getTaskVersionByTaskId(Integer taskId);
void createTaskVersionSnapshot(TaskDTO task);
} }
...@@ -149,6 +149,8 @@ public interface UserService extends ISuperService<User> { ...@@ -149,6 +149,8 @@ public interface UserService extends ISuperService<User> {
*/ */
List<RowPermissions> getCurrentRoleSelectPermissions(); List<RowPermissions> getCurrentRoleSelectPermissions();
void buildRowPermission();
/** user loginout */ /** user loginout */
void outLogin(); void outLogin();
......
...@@ -19,25 +19,12 @@ ...@@ -19,25 +19,12 @@
package org.dinky.service.impl; 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.service.APIService;
import org.dinky.utils.RunTimeUtil;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException; import lombok.RequiredArgsConstructor;
import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j;
import com.fasterxml.jackson.databind.node.ObjectNode;
/** /**
* APIServiceImpl * APIServiceImpl
...@@ -45,79 +32,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode; ...@@ -45,79 +32,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
* @since 2021/12/11 21:46 * @since 2021/12/11 21:46
*/ */
@Service @Service
public class APIServiceImpl implements APIService { @RequiredArgsConstructor
@Slf4j
@Override public class APIServiceImpl implements APIService {}
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;
}
}
...@@ -21,6 +21,8 @@ package org.dinky.service.impl; ...@@ -21,6 +21,8 @@ package org.dinky.service.impl;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.constant.CommonConstant; 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.enums.Status;
import org.dinky.data.model.Column; import org.dinky.data.model.Column;
import org.dinky.data.model.DataBase; import org.dinky.data.model.DataBase;
...@@ -28,6 +30,8 @@ import org.dinky.data.model.QueryData; ...@@ -28,6 +30,8 @@ import org.dinky.data.model.QueryData;
import org.dinky.data.model.Schema; import org.dinky.data.model.Schema;
import org.dinky.data.model.SqlGeneration; import org.dinky.data.model.SqlGeneration;
import org.dinky.data.model.Table; 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.mapper.DataBaseMapper;
import org.dinky.metadata.driver.Driver; import org.dinky.metadata.driver.Driver;
import org.dinky.metadata.result.JdbcSelectResult; import org.dinky.metadata.result.JdbcSelectResult;
...@@ -38,6 +42,7 @@ import org.apache.commons.lang3.StringUtils; ...@@ -38,6 +42,7 @@ import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
...@@ -240,4 +245,59 @@ public class DataBaseServiceImpl extends SuperServiceImpl<DataBaseMapper, DataBa ...@@ -240,4 +245,59 @@ public class DataBaseServiceImpl extends SuperServiceImpl<DataBaseMapper, DataBa
database.setCreateTime(null); database.setCreateTime(null);
return this.save(database); 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 @@ ...@@ -19,7 +19,9 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.model.Savepoints; import org.dinky.data.model.Savepoints;
import org.dinky.gateway.enums.SavePointStrategy;
import org.dinky.mapper.SavepointsMapper; import org.dinky.mapper.SavepointsMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.SavepointsService; import org.dinky.service.SavepointsService;
...@@ -52,4 +54,23 @@ public class SavepointsServiceImpl extends SuperServiceImpl<SavepointsMapper, Sa ...@@ -52,4 +54,23 @@ public class SavepointsServiceImpl extends SuperServiceImpl<SavepointsMapper, Sa
public Savepoints getEarliestSavepointByTaskId(Integer taskId) { public Savepoints getEarliestSavepointByTaskId(Integer taskId) {
return baseMapper.getEarliestSavepointByTaskId(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;
}
}
} }
...@@ -22,179 +22,60 @@ package org.dinky.service.impl; ...@@ -22,179 +22,60 @@ package org.dinky.service.impl;
import org.dinky.api.FlinkAPI; import org.dinky.api.FlinkAPI;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect; import org.dinky.config.Dialect;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.data.dto.AbstractStatementDTO;
import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.StudioCADTO; import org.dinky.data.dto.StudioCADTO;
import org.dinky.data.dto.StudioDDLDTO; import org.dinky.data.dto.StudioDDLDTO;
import org.dinky.data.dto.StudioExecuteDTO;
import org.dinky.data.dto.StudioMetaStoreDTO; import org.dinky.data.dto.StudioMetaStoreDTO;
import org.dinky.data.model.Catalog; import org.dinky.data.model.Catalog;
import org.dinky.data.model.Cluster; import org.dinky.data.model.Cluster;
import org.dinky.data.model.DataBase; import org.dinky.data.model.DataBase;
import org.dinky.data.model.FlinkColumn; import org.dinky.data.model.FlinkColumn;
import org.dinky.data.model.RowPermissions;
import org.dinky.data.model.Savepoints;
import org.dinky.data.model.Schema; import org.dinky.data.model.Schema;
import org.dinky.data.model.Table; import org.dinky.data.model.Table;
import org.dinky.data.model.Task;
import org.dinky.data.result.DDLResult; import org.dinky.data.result.DDLResult;
import org.dinky.data.result.IResult; import org.dinky.data.result.IResult;
import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
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.result.SavePointResult;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.job.JobResult;
import org.dinky.metadata.driver.Driver; import org.dinky.metadata.driver.Driver;
import org.dinky.metadata.result.JdbcSelectResult; import org.dinky.metadata.result.JdbcSelectResult;
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.model.ProcessEntity; import org.dinky.process.model.ProcessEntity;
import org.dinky.service.ClusterConfigurationService;
import org.dinky.service.ClusterInstanceService; import org.dinky.service.ClusterInstanceService;
import org.dinky.service.DataBaseService; import org.dinky.service.DataBaseService;
import org.dinky.service.FragmentVariableService;
import org.dinky.service.SavepointsService;
import org.dinky.service.StudioService; import org.dinky.service.StudioService;
import org.dinky.service.TaskService; import org.dinky.service.TaskService;
import org.dinky.service.UserService;
import org.dinky.sql.FlinkQuery; import org.dinky.sql.FlinkQuery;
import org.dinky.utils.RunTimeUtil; import org.dinky.utils.RunTimeUtil;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.cache.Cache;
import cn.hutool.cache.impl.TimedCache;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/** StudioServiceImpl */ /** StudioServiceImpl */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class StudioServiceImpl implements StudioService { public class StudioServiceImpl implements StudioService {
private static final Logger logger = LoggerFactory.getLogger(StudioServiceImpl.class);
/** Common sql query result cache */
private static final Cache<Integer, JdbcSelectResult> COMMON_SQL_SEARCH_CACHE =
new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
private final ClusterInstanceService clusterInstanceService; private final ClusterInstanceService clusterInstanceService;
private final ClusterConfigurationService clusterConfigurationService;
private final SavepointsService savepointsService;
private final DataBaseService dataBaseService; private final DataBaseService dataBaseService;
private final TaskService taskService; private final TaskService taskService;
private final FragmentVariableService fragmentVariableService;
private final UserService userService;
private void addFlinkSQLEnv(AbstractStatementDTO statementDTO) {
ProcessEntity process = ProcessContextHolder.getProcess();
process.info("Start initialize FlinkSQLEnv:");
if (statementDTO.isFragment()) {
process.config("Variable opened.");
// initialize global variables
process.info("Initializing global variables...");
statementDTO.setVariables(fragmentVariableService.listEnabledVariables());
process.infoSuccess();
// initialize database variables
process.info("Initializing database variables...");
String flinkWithSql = dataBaseService.getEnabledFlinkWithSql();
if (Asserts.isNotNullString(flinkWithSql)) {
statementDTO.setStatement(flinkWithSql + "\n" + statementDTO.getStatement());
process.infoSuccess();
} else {
process.info("No variables are loaded.");
}
}
// initialize flinksql environment, such as flink catalog
if (Asserts.isNotNull(statementDTO.getEnvId())
&& !statementDTO.getEnvId().equals(0)) {
process.config("FlinkSQLEnv opened.");
process.info("Initializing FlinkSQLEnv...");
Task task = taskService.getTaskInfoById(statementDTO.getEnvId());
if (Asserts.isNotNull(task) && Asserts.isNotNullString(task.getStatement())) {
statementDTO.setStatement(task.getStatement() + "\n" + statementDTO.getStatement());
process.infoSuccess();
} else {
process.info("No FlinkSQLEnv are loaded.");
}
}
process.info("Initializing data permissions...");
List<RowPermissions> currentRoleSelectPermissions = userService.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);
}
process.info("Finish initialize FlinkSQLEnv.");
}
private void buildSession(JobConfig config) {
// If you are using a shared session, configure the current jobManager address
if (!config.isUseSession()) {
config.setAddress(
clusterInstanceService.buildEnvironmentAddress(config.isUseRemote(), config.getClusterId()));
}
}
@Override
public JobResult executeSql(StudioExecuteDTO studioExecuteDTO) {
if (Dialect.notFlinkSql(studioExecuteDTO.getDialect())) {
JobResult jobResult = executeCommonSql(SqlDTO.build(
studioExecuteDTO.getStatement(),
studioExecuteDTO.getDatabaseId(),
studioExecuteDTO.getMaxRowNum()));
COMMON_SQL_SEARCH_CACHE.put(studioExecuteDTO.getTaskId(), (JdbcSelectResult) jobResult.getResult());
return jobResult;
} else {
return executeFlinkSql(studioExecuteDTO);
}
}
private JobResult executeFlinkSql(StudioExecuteDTO studioExecuteDTO) {
ProcessEntity process = ProcessContextHolder.registerProcess(
ProcessEntity.init(ProcessType.FLINK_EXECUTE, StpUtil.getLoginIdAsInt()));
addFlinkSQLEnv(studioExecuteDTO);
process.info("Initializing Flink job config...");
JobConfig config = studioExecuteDTO.getJobConfig();
buildSession(config);
JobManager jobManager = JobManager.build(config);
process.start();
JobResult jobResult = jobManager.executeSql(studioExecuteDTO.getStatement());
process.finish("Execute Flink SQL succeed.");
RunTimeUtil.recovery(jobManager);
return jobResult;
}
private IResult executeMSFlinkSql(StudioMetaStoreDTO studioMetaStoreDTO) { private IResult executeMSFlinkSql(StudioMetaStoreDTO studioMetaStoreDTO) {
addFlinkSQLEnv(studioMetaStoreDTO); String envSql = taskService.buildEnvSql(studioMetaStoreDTO);
studioMetaStoreDTO.setStatement(studioMetaStoreDTO.getStatement() + envSql);
JobConfig config = studioMetaStoreDTO.getJobConfig(); JobConfig config = studioMetaStoreDTO.getJobConfig();
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
IResult jobResult = jobManager.executeDDL(studioMetaStoreDTO.getStatement()); IResult jobResult = jobManager.executeDDL(studioMetaStoreDTO.getStatement());
...@@ -203,148 +84,17 @@ public class StudioServiceImpl implements StudioService { ...@@ -203,148 +84,17 @@ public class StudioServiceImpl implements StudioService {
} }
@Override @Override
public JobResult executeCommonSql(SqlDTO sqlDTO) { public JdbcSelectResult getCommonSqlData(Integer taskId) {
ProcessEntity process = ProcessContextHolder.registerProcess( return ResultPool.getCommonSqlCache(taskId);
ProcessEntity.init(ProcessType.SQL_EXECUTE, StpUtil.getLoginIdAsInt()));
JobResult result = new JobResult();
result.setStatement(sqlDTO.getStatement());
result.setStartTimeNow();
process.info("Initializing database connection...");
if (Asserts.isNull(sqlDTO.getDatabaseId())) {
result.setSuccess(false);
result.setError("please select a database.");
result.setEndTimeNow();
return result;
}
DataBase dataBase = dataBaseService.getById(sqlDTO.getDatabaseId());
if (Asserts.isNull(dataBase)) {
process.error("The database does not exist.");
result.setSuccess(false);
result.setError("The database does not exist.");
result.setEndTimeNow();
return result;
}
JdbcSelectResult selectResult;
try (Driver driver = Driver.build(dataBase.getDriverConfig())) {
process.infoSuccess();
process.start();
selectResult = driver.executeSql(sqlDTO.getStatement(), sqlDTO.getMaxRowNum());
}
process.finish("Execute sql succeed.");
result.setResult(selectResult);
if (selectResult.isSuccess()) {
result.setSuccess(true);
} else {
result.setSuccess(false);
result.setError(selectResult.getError());
}
result.setEndTimeNow();
return result;
} }
@Override @Override
public IResult executeDDL(StudioDDLDTO studioDDLDTO) { public IResult executeDDL(StudioDDLDTO studioDDLDTO) {
JobConfig config = studioDDLDTO.getJobConfig(); JobConfig config = studioDDLDTO.getJobConfig();
if (!config.isUseSession()) {
config.setAddress(
clusterInstanceService.buildEnvironmentAddress(config.isUseRemote(), studioDDLDTO.getClusterId()));
}
JobManager jobManager = JobManager.build(config); JobManager jobManager = JobManager.build(config);
return jobManager.executeDDL(studioDDLDTO.getStatement()); return jobManager.executeDDL(studioDDLDTO.getStatement());
} }
@Override
public List<SqlExplainResult> explainSql(StudioExecuteDTO studioExecuteDTO) {
if (Dialect.notFlinkSql(studioExecuteDTO.getDialect())) {
return explainCommonSql(studioExecuteDTO);
} else {
return explainFlinkSql(studioExecuteDTO);
}
}
private List<SqlExplainResult> explainFlinkSql(StudioExecuteDTO studioExecuteDTO) {
ProcessEntity process = ProcessContextHolder.registerProcess(
ProcessEntity.init(ProcessType.FLINK_EXPLAIN, StpUtil.getLoginIdAsInt()));
addFlinkSQLEnv(studioExecuteDTO);
process.info("Initializing Flink job config...");
JobConfig config = studioExecuteDTO.getJobConfig();
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to
// local.
config.buildLocal();
buildSession(config);
JobManager jobManager = JobManager.build(config);
process.start();
List<SqlExplainResult> sqlExplainResults =
jobManager.explainSql(studioExecuteDTO.getStatement()).getSqlExplainResults();
process.finish();
return sqlExplainResults;
}
private List<SqlExplainResult> explainCommonSql(StudioExecuteDTO studioExecuteDTO) {
ProcessEntity process = ProcessContextHolder.registerProcess(
ProcessEntity.init(ProcessType.SQL_EXPLAIN, StpUtil.getLoginIdAsInt()));
process.info("Initializing database connection...");
if (Asserts.isNull(studioExecuteDTO.getDatabaseId())) {
process.error("The database does not exist.");
return Collections.singletonList(
SqlExplainResult.fail(studioExecuteDTO.getStatement(), "Please specify the database."));
}
DataBase dataBase = dataBaseService.getById(studioExecuteDTO.getDatabaseId());
if (Asserts.isNull(dataBase)) {
process.error("The database does not exist.");
return Collections.singletonList(
SqlExplainResult.fail(studioExecuteDTO.getStatement(), "The database does not exist."));
}
try (Driver driver = Driver.build(dataBase.getDriverConfig())) {
process.infoSuccess();
process.start();
List<SqlExplainResult> explain = driver.explain(studioExecuteDTO.getStatement());
process.finish();
return explain;
}
}
@Override
public ObjectNode getStreamGraph(StudioExecuteDTO studioExecuteDTO) {
addFlinkSQLEnv(studioExecuteDTO);
JobConfig config = studioExecuteDTO.getJobConfig();
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to
// local.
config.buildLocal();
buildSession(config);
JobManager jobManager = JobManager.buildPlanMode(config);
return jobManager.getStreamGraph(studioExecuteDTO.getStatement());
}
@Override
public ObjectNode getJobPlan(StudioExecuteDTO studioExecuteDTO) {
addFlinkSQLEnv(studioExecuteDTO);
JobConfig config = studioExecuteDTO.getJobConfig();
// If you are using explainSql | getStreamGraph | getJobPlan, make the dialect change to
// local.
config.buildLocal();
buildSession(config);
JobManager jobManager = JobManager.build(config);
String planJson = jobManager.getJobPlanJson(studioExecuteDTO.getStatement());
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.createObjectNode();
try {
objectNode = (ObjectNode) mapper.readTree(planJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
} finally {
return objectNode;
}
}
@Override
public JdbcSelectResult getCommonSqlData(Integer taskId) {
return COMMON_SQL_SEARCH_CACHE.get(taskId);
}
@Override @Override
public SelectResult getJobData(String jobId) { public SelectResult getJobData(String jobId) {
return JobManager.getJobData(jobId); return JobManager.getJobData(jobId);
...@@ -373,7 +123,8 @@ public class StudioServiceImpl implements StudioService { ...@@ -373,7 +123,8 @@ public class StudioServiceImpl implements StudioService {
studioCADTO.getStatement(), studioCADTO.getDialect().toLowerCase(), dataBase.getDriverConfig()); studioCADTO.getStatement(), studioCADTO.getDialect().toLowerCase(), dataBase.getDriverConfig());
} }
} else { } else {
addFlinkSQLEnv(studioCADTO); String envSql = taskService.buildEnvSql(studioCADTO);
studioCADTO.setStatement(studioCADTO.getStatement() + envSql);
return LineageBuilder.getColumnLineageByLogicalPlan(studioCADTO.getStatement()); return LineageBuilder.getColumnLineageByLogicalPlan(studioCADTO.getStatement());
} }
} }
...@@ -385,73 +136,15 @@ public class StudioServiceImpl implements StudioService { ...@@ -385,73 +136,15 @@ public class StudioServiceImpl implements StudioService {
try { try {
return FlinkAPI.build(cluster.getJobManagerHost()).listJobs(); return FlinkAPI.build(cluster.getJobManagerHost()).listJobs();
} catch (Exception e) { } catch (Exception e) {
logger.info("查询作业时集群不存在"); log.info("查询作业时集群不存在");
} }
return new ArrayList<>(); return new ArrayList<>();
} }
@Override
public boolean cancelFlinkJob(Integer clusterId, String jobId) {
Cluster cluster = clusterInstanceService.getById(clusterId);
Asserts.checkNotNull(cluster, "该集群不存在");
JobConfig jobConfig = new JobConfig();
jobConfig.setAddress(cluster.getJobManagerHost());
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
FlinkClusterConfig gatewayConfig =
clusterConfigurationService.getFlinkClusterCfg(cluster.getClusterConfigurationId());
jobConfig.buildGatewayConfig(gatewayConfig);
}
JobManager jobManager = JobManager.build(jobConfig);
return jobManager.cancel(jobId);
}
@Override
public boolean savepointTrigger(
Integer taskId, Integer clusterId, String jobId, String savePointType, String name) {
Cluster cluster = clusterInstanceService.getById(clusterId);
Asserts.checkNotNull(cluster, "该集群不存在");
JobConfig jobConfig = new JobConfig();
jobConfig.setAddress(cluster.getJobManagerHost());
jobConfig.setType(cluster.getType());
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
// 如果用户选择用dinky平台来托管集群信息 说明任务一定是从dinky发起提交的
FlinkClusterConfig gatewayConfig =
clusterConfigurationService.getFlinkClusterCfg(cluster.getClusterConfigurationId());
jobConfig.buildGatewayConfig(gatewayConfig);
jobConfig.getGatewayConfig().getClusterConfig().setAppId(cluster.getName());
jobConfig.setTaskId(cluster.getTaskId());
} else {
// 用户选择外部的平台来托管集群信息,但是集群上的任务不一定是通过dinky提交的
jobConfig.setTaskId(taskId);
}
JobManager jobManager = JobManager.build(jobConfig);
SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null);
if (Asserts.isNotNull(savePointResult)) {
if (jobConfig.getTaskId().equals(0)) {
return true;
}
for (JobInfo item : savePointResult.getJobInfos()) {
if (Asserts.isEqualsIgnoreCase(jobId, item.getJobId()) && Asserts.isNotNull(jobConfig.getTaskId())) {
Savepoints savepoints = new Savepoints();
savepoints.setName(name);
savepoints.setType(savePointType);
savepoints.setPath(item.getSavePoint());
savepoints.setTaskId(jobConfig.getTaskId());
savepointsService.save(savepoints);
}
}
return true;
}
return false;
}
@Override @Override
public List<Catalog> getMSCatalogs(StudioMetaStoreDTO studioMetaStoreDTO) { public List<Catalog> getMSCatalogs(StudioMetaStoreDTO studioMetaStoreDTO) {
List<Catalog> catalogs = new ArrayList<>(); List<Catalog> catalogs = new ArrayList<>();
if (Dialect.notFlinkSql(studioMetaStoreDTO.getDialect())) { if (Dialect.isCommonSql(studioMetaStoreDTO.getDialect())) {
DataBase dataBase = dataBaseService.getById(studioMetaStoreDTO.getDatabaseId()); DataBase dataBase = dataBaseService.getById(studioMetaStoreDTO.getDatabaseId());
if (!Asserts.isNull(dataBase)) { if (!Asserts.isNull(dataBase)) {
Catalog defaultCatalog = Catalog.build(FlinkQuery.defaultCatalog()); Catalog defaultCatalog = Catalog.build(FlinkQuery.defaultCatalog());
...@@ -496,7 +189,7 @@ public class StudioServiceImpl implements StudioService { ...@@ -496,7 +189,7 @@ public class StudioServiceImpl implements StudioService {
public Schema getMSSchemaInfo(StudioMetaStoreDTO studioMetaStoreDTO) { public Schema getMSSchemaInfo(StudioMetaStoreDTO studioMetaStoreDTO) {
Schema schema = Schema.build(studioMetaStoreDTO.getDatabase()); Schema schema = Schema.build(studioMetaStoreDTO.getDatabase());
List<Table> tables = new ArrayList<>(); List<Table> tables = new ArrayList<>();
if (Dialect.notFlinkSql(studioMetaStoreDTO.getDialect())) { if (Dialect.isCommonSql(studioMetaStoreDTO.getDialect())) {
DataBase dataBase = dataBaseService.getById(studioMetaStoreDTO.getDatabaseId()); DataBase dataBase = dataBaseService.getById(studioMetaStoreDTO.getDatabaseId());
if (Asserts.isNotNull(dataBase)) { if (Asserts.isNotNull(dataBase)) {
Driver driver = Driver.build(dataBase.getDriverConfig()); Driver driver = Driver.build(dataBase.getDriverConfig());
...@@ -539,7 +232,7 @@ public class StudioServiceImpl implements StudioService { ...@@ -539,7 +232,7 @@ public class StudioServiceImpl implements StudioService {
@Override @Override
public List<FlinkColumn> getMSFlinkColumns(StudioMetaStoreDTO studioMetaStoreDTO) { public List<FlinkColumn> getMSFlinkColumns(StudioMetaStoreDTO studioMetaStoreDTO) {
List<FlinkColumn> columns = new ArrayList<>(); List<FlinkColumn> columns = new ArrayList<>();
if (!Dialect.notFlinkSql(studioMetaStoreDTO.getDialect())) { if (!Dialect.isCommonSql(studioMetaStoreDTO.getDialect())) {
String baseStatement = FlinkQuery.useCatalog(studioMetaStoreDTO.getCatalog()) String baseStatement = FlinkQuery.useCatalog(studioMetaStoreDTO.getCatalog())
+ FlinkQuery.separator() + FlinkQuery.separator()
+ FlinkQuery.useDatabase(studioMetaStoreDTO.getDatabase()) + FlinkQuery.useDatabase(studioMetaStoreDTO.getDatabase())
......
...@@ -19,22 +19,21 @@ ...@@ -19,22 +19,21 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.assertion.Assert;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.config.Dialect; import org.dinky.config.Dialect;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.data.constant.CommonConstant; import org.dinky.data.constant.CommonConstant;
import org.dinky.data.dto.JobDataDto; import org.dinky.data.dto.AbstractStatementDTO;
import org.dinky.data.dto.SqlDTO; import org.dinky.data.dto.SqlDTO;
import org.dinky.data.dto.TaskDTO;
import org.dinky.data.dto.TaskRollbackVersionDTO; import org.dinky.data.dto.TaskRollbackVersionDTO;
import org.dinky.data.dto.TaskVersionConfigureDTO;
import org.dinky.data.enums.JobLifeCycle; import org.dinky.data.enums.JobLifeCycle;
import org.dinky.data.enums.JobStatus; import org.dinky.data.enums.JobStatus;
import org.dinky.data.enums.Status; import org.dinky.data.enums.Status;
import org.dinky.data.enums.TaskOperatingSavepointSelect;
import org.dinky.data.enums.TaskOperatingStatus;
import org.dinky.data.exception.BusException; import org.dinky.data.exception.BusException;
import org.dinky.data.exception.NotSupportExplainExcepition;
import org.dinky.data.exception.SqlExplainExcepition;
import org.dinky.data.exception.TaskNotDoneException;
import org.dinky.data.model.AlertGroup; import org.dinky.data.model.AlertGroup;
import org.dinky.data.model.Catalogue; import org.dinky.data.model.Catalogue;
import org.dinky.data.model.Cluster; import org.dinky.data.model.Cluster;
...@@ -45,25 +44,20 @@ import org.dinky.data.model.JobInfoDetail; ...@@ -45,25 +44,20 @@ import org.dinky.data.model.JobInfoDetail;
import org.dinky.data.model.JobInstance; import org.dinky.data.model.JobInstance;
import org.dinky.data.model.JobModelOverview; import org.dinky.data.model.JobModelOverview;
import org.dinky.data.model.JobTypeOverView; import org.dinky.data.model.JobTypeOverView;
import org.dinky.data.model.RowPermissions;
import org.dinky.data.model.Savepoints; import org.dinky.data.model.Savepoints;
import org.dinky.data.model.Statement;
import org.dinky.data.model.SystemConfiguration; import org.dinky.data.model.SystemConfiguration;
import org.dinky.data.model.Task; import org.dinky.data.model.Task;
import org.dinky.data.model.TaskExtConfig; import org.dinky.data.model.TaskExtConfig;
import org.dinky.data.model.TaskVersion; import org.dinky.data.model.TaskVersion;
import org.dinky.data.model.UDFTemplate; import org.dinky.data.model.UDFTemplate;
import org.dinky.data.result.Result; import org.dinky.data.result.Result;
import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SqlExplainResult; import org.dinky.data.result.SqlExplainResult;
import org.dinky.data.result.TaskOperatingResult;
import org.dinky.function.compiler.CustomStringJavaCompiler; import org.dinky.function.compiler.CustomStringJavaCompiler;
import org.dinky.function.pool.UdfCodePool; import org.dinky.function.pool.UdfCodePool;
import org.dinky.function.util.UDFUtil; import org.dinky.function.util.UDFUtil;
import org.dinky.gateway.Gateway;
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.model.FlinkClusterConfig; 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;
...@@ -72,11 +66,11 @@ import org.dinky.job.JobConfig; ...@@ -72,11 +66,11 @@ import org.dinky.job.JobConfig;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.job.JobResult; import org.dinky.job.JobResult;
import org.dinky.mapper.TaskMapper; import org.dinky.mapper.TaskMapper;
import org.dinky.metadata.driver.Driver;
import org.dinky.metadata.result.JdbcSelectResult; 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.ExcuteException;
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.CatalogueService; import org.dinky.service.CatalogueService;
...@@ -84,9 +78,7 @@ import org.dinky.service.ClusterConfigurationService; ...@@ -84,9 +78,7 @@ import org.dinky.service.ClusterConfigurationService;
import org.dinky.service.ClusterInstanceService; import org.dinky.service.ClusterInstanceService;
import org.dinky.service.DataBaseService; import org.dinky.service.DataBaseService;
import org.dinky.service.FragmentVariableService; import org.dinky.service.FragmentVariableService;
import org.dinky.service.HistoryService;
import org.dinky.service.JarService; import org.dinky.service.JarService;
import org.dinky.service.JobHistoryService;
import org.dinky.service.JobInstanceService; import org.dinky.service.JobInstanceService;
import org.dinky.service.SavepointsService; import org.dinky.service.SavepointsService;
import org.dinky.service.StatementService; import org.dinky.service.StatementService;
...@@ -95,6 +87,8 @@ import org.dinky.service.TaskVersionService; ...@@ -95,6 +87,8 @@ import org.dinky.service.TaskVersionService;
import org.dinky.service.UDFTemplateService; import org.dinky.service.UDFTemplateService;
import org.dinky.service.UserService; import org.dinky.service.UserService;
import org.dinky.utils.FragmentVariableUtils; import org.dinky.utils.FragmentVariableUtils;
import org.dinky.utils.JsonUtils;
import org.dinky.utils.RunTimeUtil;
import org.dinky.utils.UDFUtils; import org.dinky.utils.UDFUtils;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
...@@ -104,19 +98,15 @@ import java.io.IOException; ...@@ -104,19 +98,15 @@ import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.annotation.Resource; import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -127,292 +117,305 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; ...@@ -127,292 +117,305 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cn.dev33.satoken.stp.StpUtil; import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
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.text.StrFormatter;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/** /**
* TaskServiceImpl * TaskServiceImpl
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j
public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implements TaskService { public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implements TaskService {
private final SavepointsService savepointsService;
private final StatementService statementService; private final StatementService statementService;
private final ClusterInstanceService clusterInstanceService; private final ClusterInstanceService clusterInstanceService;
private final ClusterConfigurationService clusterCfgService; private final ClusterConfigurationService clusterCfgService;
private final SavepointsService savepointsService;
private final JarService jarService; private final JarService jarService;
private final DataBaseService dataBaseService; private final DataBaseService dataBaseService;
private final JobInstanceService jobInstanceService; private final JobInstanceService jobInstanceService;
private final JobHistoryService jobHistoryService;
private final AlertGroupService alertGroupService; private final AlertGroupService alertGroupService;
private final HistoryService historyService;
private final TaskVersionService taskVersionService; private final TaskVersionService taskVersionService;
private final FragmentVariableService fragmentVariableService; private final FragmentVariableService fragmentVariableService;
private final UDFTemplateService udfTemplateService; private final UDFTemplateService udfTemplateService;
private final DataSourceProperties dataSourceProperties; private final DataSourceProperties dsProperties;
private final UserService userService; private final UserService userService;
@Resource @Resource
@Lazy @Lazy
private CatalogueService catalogueService; private CatalogueService catalogueService;
private static final ObjectMapper mapper = new ObjectMapper(); private String[] buildParams(int id) {
return String.format(
private String driver() { "--id %d --driver %s --url %s --username %s --password %s --dinkyAddr %s",
return dataSourceProperties.getDriverClassName(); id,
dsProperties.getDriverClassName(),
dsProperties.getUrl(),
dsProperties.getUsername(),
dsProperties.getPassword(),
SystemConfiguration.getInstances().getDinkyAddr())
.split(" ");
} }
private String url() { private void preCheckTask(TaskDTO task) throws TaskNotDoneException, SqlExplainExcepition {
return dataSourceProperties.getUrl();
}
private String username() { Assert.notNull(task, Status.TASK_NOT_EXIST.getMessage());
return dataSourceProperties.getUsername();
}
private String password() { if (!Dialect.isCommonSql(task.getDialect())
return dataSourceProperties.getPassword(); && Asserts.isNotNull(task.getJobInstanceId())
} && task.getJobInstanceId() > 0) {
String status = jobInstanceService.getById(task.getJobInstanceId()).getStatus();
if (!JobStatus.isDone(status)) {
throw new TaskNotDoneException(Status.TASK_STATUS_IS_NOT_DONE.getMessage());
}
}
@Value("server.port") List<SqlExplainResult> sqlExplainResults = explainTask(task);
private String serverPort; for (SqlExplainResult sqlExplainResult : sqlExplainResults) {
if (!sqlExplainResult.isParseTrue() || !sqlExplainResult.isExplainTrue()) {
throw new SqlExplainExcepition(StrFormatter.format(
"task [{}] sql explain failed, sql [{}], error: [{}]",
task.getName(),
sqlExplainResult.getSql(),
sqlExplainResult.getError()));
}
}
}
private String[] buildParas(Integer id) { public JobResult executeJob(TaskDTO task) {
return buildParas(id, StrUtil.NULL); ProcessEntity process = ProcessContextHolder.getProcess();
if (Dialect.isCommonSql(task.getDialect())) {
process.info("Preparing to execute common sql...");
JobResult jobResult =
dataBaseService.executeCommonSql(SqlDTO.build(task.getStatement(), task.getDatabaseId(), null));
ResultPool.putCommonSqlCache(task.getId(), (JdbcSelectResult) jobResult.getResult());
return jobResult;
} else {
process.info("Initializing Flink job config...");
JobManager jobManager = JobManager.build(buildJobConfig(task));
return jobManager.executeSql(task.getStatement());
}
} }
private String[] buildParas(Integer id, String dinkyAddr) { private JobConfig buildJobConfig(TaskDTO task) {
return String.format( task.setStatement(buildEnvSql(task) + task.getStatement());
"--id %d --driver %s --url %s --username %s --password %s --dinkyAddr %s", JobConfig config = task.getJobConfig();
id, driver(), url(), username(), password(), dinkyAddr)
.split(" "); Savepoints savepoints = savepointsService.getSavePointWithStrategy(task);
if (Asserts.isNotNull(savepoints)) {
config.setSavePointPath(savepoints.getPath());
config.getConfigJson().put("execution.savepoint.path", savepoints.getPath()); // todo: 写工具类处理相关配置
}
if (GatewayType.get(task.getType()).isDeployCluster()) {
FlinkClusterConfig flinkClusterCfg =
clusterCfgService.getFlinkClusterCfg(config.getClusterConfigurationId());
flinkClusterCfg.getAppConfig().setUserJarParas(buildParams(config.getTaskId()));
config.buildGatewayConfig(flinkClusterCfg);
} else {
String address = clusterInstanceService.buildEnvironmentAddress(config.isUseRemote(), task.getClusterId());
config.setAddress(address);
}
return config;
} }
@Override @Override
public JobResult submitTask(Integer id) { public String buildEnvSql(AbstractStatementDTO task) {
Task task = this.getTaskInfoById(id); ProcessEntity process = ProcessContextHolder.getProcess();
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage()); process.info("Start initialize FlinkSQLEnv:");
String sql = CommonConstant.LineSep;
if (Dialect.notFlinkSql(task.getDialect())) { if (task.isFragment()) {
return executeCommonSql(SqlDTO.build(task.getStatement(), task.getDatabaseId(), null)); String flinkWithSql = dataBaseService.getEnabledFlinkWithSql();
if (Asserts.isNotNullString(flinkWithSql)) {
sql += flinkWithSql + CommonConstant.LineSep;
}
task.setVariables(fragmentVariableService.listEnabledVariables());
} }
int envId = Optional.ofNullable(task.getEnvId()).orElse(-1);
if (envId != -1) {
TaskDTO envTask = this.getTaskInfoById(task.getEnvId());
if (Asserts.isNotNull(envTask) && Asserts.isNotNullString(envTask.getStatement())) {
sql += envTask.getStatement() + CommonConstant.LineSep;
}
}
process.info("Initializing data permissions...");
userService.buildRowPermission();
process.info("Finish initialize FlinkSQLEnv.");
return sql;
}
@Override
public JobResult submitTask(Integer id, String savePointPath) throws ExcuteException {
initTenantByTaskId(id);
ProcessEntity process = StpUtil.isLogin() ProcessEntity process = StpUtil.isLogin()
? ProcessContextHolder.registerProcess( ? ProcessContextHolder.registerProcess(
ProcessEntity.init(ProcessType.FLINK_SUBMIT, StpUtil.getLoginIdAsInt())) ProcessEntity.init(ProcessType.FLINK_SUBMIT, StpUtil.getLoginIdAsInt()))
: ProcessEntity.NULL_PROCESS; : ProcessEntity.NULL_PROCESS;
process.start();
process.info("Initializing Flink job config..."); TaskDTO task = this.getTaskInfoById(id);
JobConfig config = buildJobConfig(task);
// if (GatewayType.KUBERNETES_APPLICATION.equalsValue(config.getType())) { if (StringUtils.isNotBlank(savePointPath)) {
// loadDocker(id, config.getClusterConfigurationId(), config.getGatewayConfig()); task.setSavePointStrategy(SavePointStrategy.CUSTOM.getValue());
// } task.setSavePointPath(savePointPath);
}
JobManager jobManager = JobManager.build(config); preCheckTask(task);
process.start();
JobResult jobResult; JobResult jobResult = executeJob(task);
if (config.isJarTask()) { process.info("execute job finished,status is ", jobResult.getStatus());
jobResult = jobManager.executeJar();
if (jobResult.isSuccess()) { if (Job.JobStatus.SUCCESS == jobResult.getStatus()) {
process.finish("Submit Flink SQL finished, JobManager Web Interface: http://" process.info("Job Submit success");
+ jobResult.getJobManagerAddress()); task.setJobInstanceId(jobResult.getJobInstanceId());
} else { if (!this.updateById(task.buildTask())) {
// 如果提交失败,则只打印出关键的错误信息 throw new BusException(Status.TASK_UPDATE_FAILED.getMessage());
process.error("Submit Flink SQL " + jobResult.getStatus());
if (Asserts.isNotNull(jobResult.getError())) {
process.error(jobResult.getError().split("\n")[0]);
Arrays.stream(jobResult.getError().split("\n"))
.filter(row -> row.contains("Caused by"))
.forEach(row -> process.error(row));
}
} }
} else { } else {
jobResult = jobManager.executeSql(task.getStatement()); process.error("Job Submit failed, error: " + jobResult.getError());
process.finish("Submit Flink SQL finished.");
} }
return jobResult;
}
private void loadDocker(Integer taskId, Integer clusterConfigurationId, GatewayConfig gatewayConfig) { process.finish();
// Map<String, Object> dockerConfig = clusterCfgService return jobResult;
// .getClusterConfigById(clusterConfigurationId)
// .getFlinkClusterCfg()
// .getKubernetesConfig()
// .getDockerConfig();
//
// if (dockerConfig == null) {
// return;
// }
//
// String[] params = buildParas(
// taskId, dockerConfig.getOrDefault("dinky.remote.addr", "").toString());
//
// gatewayConfig.getAppConfig().setUserJarParas(params);
//
// Docker docker = Docker.build(dockerConfig);
// if (docker == null || StringUtils.isBlank(docker.getInstance())) {
// return;
// }
//
// DockerClientUtils dockerClientUtils = new DockerClientUtils(docker);
// String tag = dockerClientUtils.getDocker().getTag();
// if (StrUtil.isNotBlank(tag)) {
// gatewayConfig.getFlinkConfig().getConfiguration().put("kubernetes.container.image", tag);
// }
} }
@Override @Override
public JobResult submitTaskToOnline(Task dtoTask, Integer id) { public JobResult restartTask(Integer id, String savePointPath) throws ExcuteException {
final Task task = dtoTask == null ? this.getTaskInfoById(id) : dtoTask; TaskDTO task = this.getTaskInfoById(id);
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage()); Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage());
task.setStep(JobLifeCycle.ONLINE.getValue()); if (!Dialect.isCommonSql(task.getDialect()) && Asserts.isNotNull(task.getJobInstanceId())) {
String status = jobInstanceService.getById(task.getJobInstanceId()).getStatus();
if (Dialect.notFlinkSql(task.getDialect())) { if (!JobStatus.isDone(status)) {
return executeCommonSql(SqlDTO.build(task.getStatement(), task.getDatabaseId(), null)); cancelTaskJob(task);
} }
JobConfig config = buildJobConfig(task);
JobManager jobManager = JobManager.build(config);
if (config.isJarTask()) {
return jobManager.executeJar();
} }
return jobManager.executeSql(task.getStatement()); return submitTask(id, savePointPath);
} }
@Override @Override
public JobResult restartTask(Integer id, String savePointPath) { public boolean cancelTaskJob(TaskDTO task) {
Task task = this.getTaskInfoById(id); JobInstance jobInstance = jobInstanceService.getById(task.getJobInstanceId());
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage()); Assert.notNull(jobInstance, Status.JOB_INSTANCE_NOT_EXIST.getMessage());
if (checkJobInstanceId(task)) { Cluster cluster = clusterInstanceService.getById(jobInstance.getClusterId());
savepointJobInstance(task.getJobInstanceId(), SavePointType.CANCEL.getValue()); Assert.notNull(cluster, Status.CLUSTER_NOT_EXIST.getMessage());
}
if (Dialect.notFlinkSql(task.getDialect())) {
return executeCommonSql(SqlDTO.build(task.getStatement(), task.getDatabaseId(), null));
}
if (StringUtils.isBlank(savePointPath)) {
task.setSavePointStrategy(SavePointStrategy.LATEST.getValue());
} else {
task.setSavePointStrategy(SavePointStrategy.CUSTOM.getValue());
task.setSavePointPath(savePointPath);
updateById(task);
}
JobConfig config = buildJobConfig(task); JobManager jobManager = JobManager.build(buildJobConfig(task));
JobManager jobManager = JobManager.build(config); boolean cancelled = jobManager.cancel(jobInstance.getJid());
if (!config.isJarTask()) { JobInfoDetail jobInfoDetail = jobInstanceService.refreshJobInfoDetail(jobInstance.getId());
return jobManager.executeSql(task.getStatement()); return cancelled;
} else {
return jobManager.executeJar();
}
} }
private JobResult executeCommonSql(SqlDTO sqlDTO) { @Override
JobResult result = new JobResult(); public SavePointResult savepointTaskJob(TaskDTO task, String savePointType) {
result.setStatement(sqlDTO.getStatement()); JobInstance jobInstance = jobInstanceService.getById(task.getJobInstanceId());
result.setStartTime(LocalDateTime.now()); Assert.notNull(jobInstance, Status.JOB_INSTANCE_NOT_EXIST.getMessage());
if (Asserts.isNull(sqlDTO.getDatabaseId())) {
result.setSuccess(false);
result.setError("please assign data source");
result.setEndTime(LocalDateTime.now());
return result;
}
DataBase dataBase = dataBaseService.getById(sqlDTO.getDatabaseId());
if (Asserts.isNull(dataBase)) {
result.setSuccess(false);
result.setError("data source not exist.");
result.setEndTime(LocalDateTime.now());
return result;
}
JdbcSelectResult selectResult; JobManager jobManager = JobManager.build(buildJobConfig(task));
try (Driver driver = Driver.build(dataBase.getDriverConfig())) { String jobId = jobInstance.getJid();
selectResult = driver.executeSql(sqlDTO.getStatement(), sqlDTO.getMaxRowNum());
}
result.setResult(selectResult); SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null);
if (selectResult.isSuccess()) { Assert.notNull(savePointResult.getJobInfos());
result.setSuccess(true); for (JobInfo item : savePointResult.getJobInfos()) {
} else { if (Asserts.isEqualsIgnoreCase(jobId, item.getJobId()) && Asserts.isNotNull(jobInstance.getTaskId())) {
result.setSuccess(false); Savepoints savepoints = new Savepoints();
result.setError(selectResult.getError()); savepoints.setName(savePointType);
savepoints.setType(savePointType);
savepoints.setPath(item.getSavePoint());
savepoints.setTaskId(task.getId());
savepointsService.save(savepoints);
}
} }
result.setEndTime(LocalDateTime.now()); return savePointResult;
return result;
} }
@Override @Override
public List<SqlExplainResult> explainTask(Integer id) { public List<SqlExplainResult> explainTask(TaskDTO task) throws NotSupportExplainExcepition {
Task task = getTaskInfoById(id); if (Dialect.isCommonSql(task.getDialect())) {
if (Dialect.notFlinkSql(task.getDialect())) { return dataBaseService.explainCommonSql(task);
return explainCommonSqlTask(task); } else if (task.getDialect().equals(Dialect.FLINK_SQL.getValue())) {
JobConfig config = buildJobConfig(task);
config.buildLocal();
JobManager jobManager = JobManager.buildPlanMode(config);
return jobManager.explainSql(task.getStatement()).getSqlExplainResults();
} }
throw new NotSupportExplainExcepition(StrFormatter.format(
"task [{}] dialect [{}] is can not explain, skip sqlExplain verify",
task.getName(),
task.getDialect()));
}
return explainFlinkSqlTask(task); @Override
public ObjectNode getJobPlan(TaskDTO task) {
JobManager jobManager = JobManager.buildPlanMode(buildJobConfig(task));
String planJson = jobManager.getJobPlanJson(task.getStatement());
return JsonUtils.parseObject(planJson);
} }
private List<SqlExplainResult> explainFlinkSqlTask(Task task) { @Override
JobConfig config = buildJobConfig(task); public ObjectNode getStreamGraph(TaskDTO taskDTO) {
config.buildLocal(); JobConfig config = taskDTO.getJobConfig();
JobManager jobManager = JobManager.buildPlanMode(config); JobManager jobManager = JobManager.buildPlanMode(config);
return jobManager.explainSql(task.getStatement()).getSqlExplainResults(); ObjectNode streamGraph = jobManager.getStreamGraph(taskDTO.getStatement());
RunTimeUtil.recovery(jobManager);
return streamGraph;
} }
private List<SqlExplainResult> explainCommonSqlTask(Task task) { @Override
if (Asserts.isNull(task.getDatabaseId())) { public String exportSql(Integer id) {
return Collections.singletonList(SqlExplainResult.fail(task.getStatement(), "please assign data source.")); TaskDTO task = this.getTaskInfoById(id);
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage());
if (Dialect.isCommonSql(task.getDialect())) {
return task.getStatement();
} }
DataBase dataBase = dataBaseService.getById(task.getDatabaseId()); JobConfig config = buildJobConfig(task);
if (Asserts.isNull(dataBase)) {
return Collections.singletonList(SqlExplainResult.fail(task.getStatement(), "data source not exist.")); // 加密敏感信息
if (config.getVariables() != null) {
for (Map.Entry<String, String> entry : config.getVariables().entrySet()) {
if (FragmentVariableUtils.isSensitive(entry.getKey())) {
entry.setValue(FragmentVariableUtils.HIDDEN_CONTENT);
}
}
} }
List<SqlExplainResult> sqlExplainResults; JobManager jobManager = JobManager.build(config);
try (Driver driver = Driver.build(dataBase.getDriverConfig())) { if (config.isJarTask()) {
sqlExplainResults = driver.explain(task.getStatement()); return "";
} }
return sqlExplainResults;
return jobManager.exportSql(task.getStatement());
} }
@Override @Override
public Task getTaskInfoById(Integer id) { public TaskDTO getTaskInfoById(Integer id) {
Task task = this.getById(id); Task mTask = this.getById(id);
if (task == null) { Assert.notNull(mTask, Status.TASK_NOT_EXIST.getMessage());
return null; TaskDTO taskDTO = new TaskDTO();
} BeanUtil.copyProperties(mTask, taskDTO);
if (task.getClusterId() != null) {
Cluster cluster = clusterInstanceService.getById(task.getClusterId()); if (taskDTO.getClusterId() != null) {
Cluster cluster = clusterInstanceService.getById(taskDTO.getClusterId());
if (cluster != null) { if (cluster != null) {
task.setClusterName(cluster.getAlias()); taskDTO.setClusterName(cluster.getAlias());
} }
} }
if (taskDTO.getJobInstanceId() != null) {
Statement statement = statementService.getById(id); JobInstance jobInstance = jobInstanceService.getById(taskDTO.getJobInstanceId());
if (statement != null) { if (jobInstance != null) {
task.setStatement(statement.getStatement()); taskDTO.setStatus(jobInstance.getStatus());
} }
JobInstance jobInstance = jobInstanceService.getJobInstanceByTaskId(id);
if (Asserts.isNotNull(jobInstance) && !JobStatus.isDone(jobInstance.getStatus())) {
task.setJobInstanceId(jobInstance.getId());
} else {
task.setJobInstanceId(0);
} }
return task; return taskDTO;
} }
@Override @Override
...@@ -422,8 +425,23 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -422,8 +425,23 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
TenantContextHolder.set(tenantId); TenantContextHolder.set(tenantId);
} }
@Override
public boolean changeTaskLifeRecyle(Integer taskId, JobLifeCycle lifeCycle) {
TaskDTO taskInfoById = getTaskInfoById(taskId);
taskInfoById.setStep(lifeCycle.getValue());
if (lifeCycle == JobLifeCycle.ONLINE) {
taskVersionService.createTaskVersionSnapshot(taskInfoById);
}
return saveOrUpdate(taskInfoById.buildTask());
}
@Override @Override
public boolean saveOrUpdateTask(Task task) { public boolean saveOrUpdateTask(Task task) {
if (JobLifeCycle.ONLINE.equalsValue(task.getStep())) {
throw new BusException(Status.TASK_IS_ONLINE.getMessage());
}
if (Dialect.isUDF(task.getDialect())) { if (Dialect.isUDF(task.getDialect())) {
TaskExtConfig taskConfigJson = task.getConfigJson(); TaskExtConfig taskConfigJson = task.getConfigJson();
...@@ -456,56 +474,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -456,56 +474,20 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
UdfCodePool.addOrUpdate(UDFUtils.taskToUDF(task)); UdfCodePool.addOrUpdate(UDFUtils.taskToUDF(task));
} }
// if modify task else create task return this.saveOrUpdate(task);
if (task.getId() != null) {
Task taskInfo = getById(task.getId());
Assert.check(taskInfo);
if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) {
throw new BusException(
"该作业已" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ",禁止修改!");
}
task.setStep(JobLifeCycle.DEVELOP.getValue());
this.updateById(task);
if (task.getStatement() != null) {
Statement statement = new Statement();
statement.setId(task.getId());
statement.setStatement(task.getStatement());
statementService.updateById(statement);
}
} else {
task.setStep(JobLifeCycle.CREATE.getValue());
if (task.getCheckPoint() == null) {
task.setCheckPoint(0);
}
if (task.getParallelism() == null) {
task.setParallelism(1);
}
if (task.getClusterId() == null) {
task.setClusterId(0);
}
this.save(task);
Statement statement = new Statement();
statement.setId(task.getId());
if (task.getStatement() == null) {
task.setStatement("");
}
statement.setStatement(task.getStatement());
statementService.insert(statement);
}
return true;
} }
@Override @Override
public List<Task> listFlinkSQLEnv() { public List<Task> listFlinkSQLEnv() {
return this.list(new QueryWrapper<Task>() return this.list(new QueryWrapper<Task>()
.eq("dialect", Dialect.FLINK_SQL_ENV.getValue()) .lambda()
.eq("enabled", 1)); .eq(Task::getDialect, Dialect.FLINK_SQL_ENV.getValue())
.eq(Task::getEnabled, 1));
} }
@Override @Override
public Task initDefaultFlinkSQLEnv(Integer tenantId) { public Task initDefaultFlinkSQLEnv(Integer tenantId) {
TenantContextHolder.set(tenantId);
String separator = SystemConfiguration.getInstances().getSqlSeparator(); String separator = SystemConfiguration.getInstances().getSqlSeparator();
separator = separator.replace("\\r", "\r").replace("\\n", "\n"); separator = separator.replace("\\r", "\r").replace("\\n", "\n");
String name = "DefaultCatalog"; String name = "DefaultCatalog";
...@@ -520,15 +502,16 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -520,15 +502,16 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
+ "'password' = '%s',\n" + "'password' = '%s',\n"
+ " 'url' = '%s'\n" + " 'url' = '%s'\n"
+ ")%suse catalog my_catalog%s", + ")%suse catalog my_catalog%s",
username(), password(), url(), separator, separator); dsProperties.getUsername(), dsProperties.getPassword(), dsProperties.getUrl(), separator, separator);
if (null != defaultFlinkSQLEnvTask) { if (null != defaultFlinkSQLEnvTask) {
statementEquals(tenantId, defaultFlinkSQLEnvTask, sql); defaultFlinkSQLEnvTask.setStatement(sql);
saveOrUpdateTask(defaultFlinkSQLEnvTask);
return defaultFlinkSQLEnvTask; return defaultFlinkSQLEnvTask;
} }
defaultFlinkSQLEnvTask = new Task(); defaultFlinkSQLEnvTask = new Task();
defaultFlinkSQLEnvTask.setName("DefaultCatalog"); defaultFlinkSQLEnvTask.setName(name);
defaultFlinkSQLEnvTask.setDialect(Dialect.FLINK_SQL_ENV.getValue()); defaultFlinkSQLEnvTask.setDialect(Dialect.FLINK_SQL_ENV.getValue());
defaultFlinkSQLEnvTask.setStatement(sql); defaultFlinkSQLEnvTask.setStatement(sql);
defaultFlinkSQLEnvTask.setFragment(true); defaultFlinkSQLEnvTask.setFragment(true);
...@@ -536,59 +519,14 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -536,59 +519,14 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
defaultFlinkSQLEnvTask.setEnabled(true); defaultFlinkSQLEnvTask.setEnabled(true);
saveOrUpdate(defaultFlinkSQLEnvTask); saveOrUpdate(defaultFlinkSQLEnvTask);
Statement statement = new Statement();
statement.setId(defaultFlinkSQLEnvTask.getId());
statement.setTenantId(tenantId);
statement.setStatement(sql);
statementService.saveOrUpdate(statement);
return defaultFlinkSQLEnvTask; return defaultFlinkSQLEnvTask;
} }
/**
* 数据库信息发生修改后,catalog ddl也随之改变
*
* @param tenantId
* @param defaultFlinkSQLEnvTask
* @param sql
*/
private void statementEquals(Integer tenantId, Task defaultFlinkSQLEnvTask, String sql) {
TenantContextHolder.set(tenantId);
// 对比catalog ddl,不相同则更新dinky_task_statement表
boolean equals = StringUtils.equals(
sql, statementService.getById(defaultFlinkSQLEnvTask.getId()).getStatement());
if (!equals) {
Statement statement = new Statement();
statement.setId(defaultFlinkSQLEnvTask.getId());
statement.setTenantId(tenantId);
statement.setStatement(sql);
statementService.saveOrUpdate(statement);
}
}
@Override @Override
public Task getTaskByNameAndTenantId(String name, Integer tenantId) { public Task getTaskByNameAndTenantId(String name, Integer tenantId) {
return baseMapper.getTaskByNameAndTenantId(name, tenantId); return baseMapper.getTaskByNameAndTenantId(name, tenantId);
} }
@Override
public JobStatus checkJobStatus(JobInfoDetail jobInfoDetail) {
if (Asserts.isNull(jobInfoDetail.getClusterConfiguration())) {
return JobStatus.UNKNOWN;
}
Integer clusterId = jobInfoDetail.getClusterConfiguration().getId();
String appId = jobInfoDetail.getCluster().getName();
FlinkClusterConfig clusterConfig = clusterCfgService.getFlinkClusterCfg(clusterId);
GatewayConfig gatewayConfig = GatewayConfig.build(clusterConfig);
gatewayConfig.getClusterConfig().setAppId(appId);
Gateway gateway = Gateway.build(gatewayConfig);
return gateway.getJobStatusById(appId);
}
@Override @Override
public List<JobTypeOverView> getTaskOnlineRate() { public List<JobTypeOverView> getTaskOnlineRate() {
return baseMapper.getTaskOnlineRate(); return baseMapper.getTaskOnlineRate();
...@@ -599,44 +537,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -599,44 +537,6 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
return baseMapper.getJobStreamingOrBatchModelOverview(); return baseMapper.getJobStreamingOrBatchModelOverview();
} }
@Override
public String exportSql(Integer id) {
Task task = getTaskInfoById(id);
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage());
if (Dialect.notFlinkSql(task.getDialect())) {
return task.getStatement();
}
JobConfig config = buildJobConfig(task);
// 加密敏感信息
if (config.getVariables() != null) {
for (Map.Entry<String, String> entry : config.getVariables().entrySet()) {
if (FragmentVariableUtils.isSensitive(entry.getKey())) {
entry.setValue(FragmentVariableUtils.HIDDEN_CONTENT);
}
}
}
JobManager jobManager = JobManager.build(config);
if (config.isJarTask()) {
return "";
}
return jobManager.exportSql(task.getStatement());
}
@Override
public Task getUDFByClassName(String className) {
Task task = getOne(new QueryWrapper<Task>()
.in("dialect", Dialect.JAVA, Dialect.SCALA, Dialect.PYTHON)
.eq("enabled", 1)
.eq("save_point_path", className));
Asserts.checkNull(task, StrUtil.format("class: {} ,not exists!", className));
task.setStatement(statementService.getById(task.getId()).getStatement());
return task;
}
@Override @Override
public List<Task> getAllUDF() { public List<Task> getAllUDF() {
List<Task> tasks = list(new QueryWrapper<Task>() List<Task> tasks = list(new QueryWrapper<Task>()
...@@ -645,89 +545,18 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -645,89 +545,18 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
.isNotNull("save_point_path")); .isNotNull("save_point_path"));
return tasks.stream() return tasks.stream()
.peek(task -> { .peek(task -> {
Assert.check(task); Assert.notNull(task, Status.TASK_NOT_EXIST.getMessage());
task.setStatement(statementService.getById(task.getId()).getStatement()); task.setStatement(statementService.getById(task.getId()).getStatement());
}) })
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@Override
public Result<Void> releaseTask(Integer id) {
Task task = getTaskInfoById(id);
Assert.check(task);
if (!JobLifeCycle.DEVELOP.equalsValue(task.getStep())) {
return Result.succeed("publish success!");
}
// KubernetesApplication is not sql, skip sqlExplain verify
if (!Dialect.KUBERNETES_APPLICATION.equalsVal(task.getDialect())) {
List<SqlExplainResult> sqlExplainResults = explainTask(id);
for (SqlExplainResult sqlExplainResult : sqlExplainResults) {
if (!sqlExplainResult.isParseTrue() || !sqlExplainResult.isExplainTrue()) {
return Result.failed("syntax or logic check error, publish failed");
}
}
}
task.setStep(JobLifeCycle.RELEASE.getValue());
Task newTask = createTaskVersionSnapshot(task);
if (updateById(newTask)) {
return Result.succeed("publish success!");
} else {
return Result.failed("publish failed, due to unknown reason");
}
}
public Task createTaskVersionSnapshot(Task task) {
List<TaskVersion> taskVersions = taskVersionService.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())) {
// 首次发布,新增版本
taskVersion.setVersionId(1);
task.setVersionId(1);
taskVersionService.save(taskVersion);
} else {
// 说明存在版本,需要判断是否 是回退后的老版本
// 1、版本号存在
// 2、md5值与上一个版本一致
TaskVersion version = versionMap.get(task.getVersionId());
version.setId(null);
if (versionIds.contains(task.getVersionId()) && !taskVersion.equals(version)) {
// || !versionIds.contains(task.getVersionId()) && !taskVersion.equals(version)
taskVersion.setVersionId(Collections.max(versionIds) + 1);
task.setVersionId(Collections.max(versionIds) + 1);
taskVersionService.save(taskVersion);
}
}
return task;
}
@Override @Override
public Result<Void> rollbackTask(TaskRollbackVersionDTO dto) { public Result<Void> rollbackTask(TaskRollbackVersionDTO dto) {
if (Asserts.isNull(dto.getVersionId()) || Asserts.isNull(dto.getId())) { if (Asserts.isNull(dto.getVersionId()) || Asserts.isNull(dto.getId())) {
return Result.failed("the version is error"); return Result.failed("the version is error");
} }
Task taskInfo = getTaskInfoById(dto.getId());
if (JobLifeCycle.RELEASE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.ONLINE.equalsValue(taskInfo.getStep())
|| JobLifeCycle.CANCEL.equalsValue(taskInfo.getStep())) {
return Result.failed(
"this job had" + JobLifeCycle.get(taskInfo.getStep()).getLabel() + ", refuse to rollback!");
}
LambdaQueryWrapper<TaskVersion> queryWrapper = new LambdaQueryWrapper<TaskVersion>() LambdaQueryWrapper<TaskVersion> queryWrapper = new LambdaQueryWrapper<TaskVersion>()
.eq(TaskVersion::getTaskId, dto.getId()) .eq(TaskVersion::getTaskId, dto.getId())
.eq(TaskVersion::getVersionId, dto.getVersionId()); .eq(TaskVersion::getVersionId, dto.getVersionId());
...@@ -740,270 +569,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -740,270 +569,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
updateTask.setId(taskVersion.getTaskId()); updateTask.setId(taskVersion.getTaskId());
updateTask.setStep(JobLifeCycle.DEVELOP.getValue()); updateTask.setStep(JobLifeCycle.DEVELOP.getValue());
baseMapper.updateById(updateTask); baseMapper.updateById(updateTask);
Statement statement = new Statement();
statement.setStatement(taskVersion.getStatement());
statement.setId(taskVersion.getTaskId());
statementService.updateById(statement);
return Result.succeed("version rollback success!"); return Result.succeed("version rollback success!");
} }
@Override
public boolean developTask(Integer id) {
Task task = getTaskInfoById(id);
Assert.check(task);
if (JobLifeCycle.RELEASE.equalsValue(task.getStep())) {
task.setStep(JobLifeCycle.DEVELOP.getValue());
return updateById(task);
}
return false;
}
@Override
public Result<JobResult> onLineTask(Integer id) {
final Task task = getTaskInfoById(id);
Assert.check(task);
if (JobLifeCycle.RELEASE.equalsValue(task.getStep())) {
if (checkJobInstanceId(task)) {
return Result.failed("当前发布状态下有作业正在运行,上线失败,请停止后上线");
}
final JobResult jobResult = submitTaskToOnline(task, id);
if (Job.JobStatus.SUCCESS == jobResult.getStatus()) {
task.setStep(JobLifeCycle.ONLINE.getValue());
task.setJobInstanceId(jobResult.getJobInstanceId());
if (updateById(task)) {
return Result.succeed(jobResult, "上线成功");
}
return Result.failed("由于未知原因,上线失败");
}
return Result.failed("上线失败,原因:" + jobResult.getError());
}
if (JobLifeCycle.ONLINE.equalsValue(task.getStep())) {
return Result.failed("上线失败,当前作业已上线。");
}
return Result.failed("上线失败,当前作业未发布。");
}
private static boolean checkJobInstanceId(Task task) {
return Asserts.isNotNull(task.getJobInstanceId()) && task.getJobInstanceId() != 0;
}
@Override
public Result<JobResult> reOnLineTask(Integer id, String savePointPath) {
final Task task = this.getTaskInfoById(id);
Asserts.checkNull(task, Status.TASK_NOT_EXIST.getMessage());
if (checkJobInstanceId(task)) {
savepointJobInstance(task.getJobInstanceId(), SavePointType.CANCEL.getValue());
}
if (StringUtils.isNotBlank(savePointPath)) {
task.setSavePointStrategy(SavePointStrategy.CUSTOM.getValue());
task.setSavePointPath(savePointPath);
}
final JobResult jobResult = submitTaskToOnline(task, id);
if (Job.JobStatus.SUCCESS == jobResult.getStatus()) {
task.setStep(JobLifeCycle.ONLINE.getValue());
task.setJobInstanceId(jobResult.getJobInstanceId());
if (updateById(task)) {
return Result.succeed(jobResult, "重新上线成功");
}
return Result.failed("由于未知原因,重新上线失败");
}
return Result.failed("重新上线失败,原因:" + jobResult.getError());
}
@Override
public Result<Void> offLineTask(Integer id, String type) {
Task task = getTaskInfoById(id);
Assert.check(task);
if (Asserts.isNullString(type)) {
type = SavePointType.CANCEL.getValue();
}
savepointTask(id, type);
if (!JobLifeCycle.ONLINE.equalsValue(task.getStep())) {
return Result.succeed("停止成功");
}
task.setStep(JobLifeCycle.RELEASE.getValue());
updateById(task);
return Result.succeed("下线成功");
}
@Override
public Result<Void> cancelTask(Integer id) {
Task task = getTaskInfoById(id);
Assert.check(task);
if (JobLifeCycle.ONLINE != JobLifeCycle.get(task.getStep())) {
if (checkJobInstanceId(task)) {
return Result.failed("当前有作业正在运行,注销失败,请停止后注销");
}
task.setStep(JobLifeCycle.CANCEL.getValue());
if (updateById(task)) {
return Result.succeed("注销成功");
}
return Result.failed("由于未知原因,注销失败");
}
return Result.failed("当前有作业已上线,无法注销,请下线后注销");
}
@Override
public boolean recoveryTask(Integer id) {
Task task = getTaskInfoById(id);
Assert.check(task);
if (JobLifeCycle.CANCEL == JobLifeCycle.get(task.getStep())) {
task.setStep(JobLifeCycle.DEVELOP.getValue());
return updateById(task);
}
return false;
}
private boolean savepointJobInstance(Integer jobInstanceId, String savePointType) {
JobInstance jobInstance = jobInstanceService.getById(jobInstanceId);
if (Asserts.isNull(jobInstance)) {
return true;
}
Cluster cluster = clusterInstanceService.getById(jobInstance.getClusterId());
Asserts.checkNotNull(cluster, "该集群不存在");
Task task = this.getTaskInfoById(jobInstance.getTaskId());
JobConfig jobConfig = task.buildSubmitConfig();
jobConfig.setType(cluster.getType());
if (Asserts.isNotNull(cluster.getClusterConfigurationId())) {
FlinkClusterConfig flinkClusterConfig = buildGatewayCfgObj(jobConfig);
jobConfig.buildGatewayConfig(flinkClusterConfig);
}
jobConfig.setAddress(cluster.getJobManagerHost());
JobManager jobManager = JobManager.build(jobConfig);
String jobId = jobInstance.getJid();
if ("canceljob".equals(savePointType)) {
return jobManager.cancel(jobId);
}
SavePointResult savePointResult = jobManager.savepoint(jobId, savePointType, null);
if (Asserts.isNotNull(savePointResult.getJobInfos())) {
for (JobInfo item : savePointResult.getJobInfos()) {
if (Asserts.isEqualsIgnoreCase(jobId, item.getJobId()) && Asserts.isNotNull(jobConfig.getTaskId())) {
Savepoints savepoints = new Savepoints();
savepoints.setName(savePointType);
savepoints.setType(savePointType);
savepoints.setPath(item.getSavePoint());
savepoints.setTaskId(jobConfig.getTaskId());
savepointsService.save(savepoints);
}
}
return true;
}
return false;
}
@Override
public boolean savepointTask(Integer taskId, String savePointType) {
Task task = getTaskInfoById(taskId);
return savepointJobInstance(task.getJobInstanceId(), savePointType);
}
private JobConfig buildJobConfig(Task task) {
if (!task.isJarTask()) {
String envSql = buildEnvSql(task);
task.setStatement(envSql + task.getStatement());
}
JobConfig config = task.buildSubmitConfig();
Savepoints savepoints = buildSavepoint(config);
if (Asserts.isNotNull(savepoints)) {
config.setSavePointPath(savepoints.getPath());
config.getConfigJson().put("execution.savepoint.path", savepoints.getPath()); // todo: 写工具类处理相关配置
}
if (!GatewayType.get(task.getType()).isDeployCluster()) {
String address = clusterInstanceService.buildEnvironmentAddress(config.isUseRemote(), task.getClusterId());
config.setAddress(address);
} else {
config.buildGatewayConfig(buildGatewayCfgObj(config));
}
config.setVariables(fragmentVariableService.listEnabledVariables());
buildRowPermission();
return config;
}
private Savepoints buildSavepoint(JobConfig config) {
switch (config.getSavePointStrategy()) {
case LATEST:
return savepointsService.getLatestSavepointByTaskId(config.getTaskId());
case EARLIEST:
return savepointsService.getEarliestSavepointByTaskId(config.getTaskId());
case CUSTOM:
return new Savepoints() {
{
setPath(config.getSavePointPath());
}
};
default:
return null;
}
}
private FlinkClusterConfig buildGatewayCfgObj(JobConfig config) {
FlinkClusterConfig flinkClusterCfg = clusterCfgService.getFlinkClusterCfg(config.getClusterConfigurationId());
flinkClusterCfg.getAppConfig().setUserJarParas(buildParas(config.getTaskId()));
flinkClusterCfg.getFlinkConfig().getConfiguration().putAll(config.getConfigJson());
// if (config.isJarTask()) {
// JSONObject clusterObj = new JSONObject(flinkClusterCfg);
// JSONObject taskObj = new JSONObject(task.getStatement());
// return JsonUtils.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 = userService.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 @Override
public String getTaskAPIAddress() { public String getTaskAPIAddress() {
return SystemConfiguration.getInstances().getDinkyAddr().getValue(); return SystemConfiguration.getInstances().getDinkyAddr().getValue();
...@@ -1016,7 +584,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1016,7 +584,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
@Override @Override
public String exportJsonByTaskId(Integer taskId) { public String exportJsonByTaskId(Integer taskId) {
Task task = getTaskInfoById(taskId); TaskDTO task = getTaskInfoById(taskId);
if (Asserts.isNotNull(task.getClusterId())) { if (Asserts.isNotNull(task.getClusterId())) {
Cluster cluster = clusterInstanceService.getById(task.getClusterId()); Cluster cluster = clusterInstanceService.getById(task.getClusterId());
if (Asserts.isNotNull(cluster)) { if (Asserts.isNotNull(cluster)) {
...@@ -1025,7 +593,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1025,7 +593,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
// path // path
ObjectNode jsonNode = (ObjectNode) task.parseJsonNode(mapper); ObjectNode jsonNode = (ObjectNode) JsonUtils.toJsonNode(task);
jsonNode.put("path", getTaskPathByTaskId(taskId)); jsonNode.put("path", getTaskPathByTaskId(taskId));
// clusterConfigurationName // clusterConfigurationName
...@@ -1085,7 +653,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1085,7 +653,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
if (file.isEmpty() || file.getSize() <= 0 || fileName == null || "".equals(fileName)) { if (file.isEmpty() || file.getSize() <= 0 || fileName == null || "".equals(fileName)) {
return Result.failed("传入的文件数据为空"); return Result.failed("传入的文件数据为空");
} }
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(getStrByJsonFile(file)); JsonNode jsonNode = mapper.readTree(getStrByJsonFile(file));
return buildTaskByJsonNode(jsonNode, mapper); return buildTaskByJsonNode(jsonNode, mapper);
} }
...@@ -1101,9 +669,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1101,9 +669,9 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
int errorNumber = 0; int errorNumber = 0;
List<Task> tasks = new ArrayList<>(); List<TaskDTO> tasks = new ArrayList<>();
for (JsonNode json : jsonNodes) { for (JsonNode json : jsonNodes) {
Task task = mapper.treeToValue(json, Task.class); TaskDTO task = mapper.treeToValue(json, TaskDTO.class);
if (Asserts.isNotNull(task.getClusterName())) { if (Asserts.isNotNull(task.getClusterName())) {
Cluster cluster = Cluster cluster =
clusterInstanceService.getOne(new QueryWrapper<Cluster>().eq("name", task.getClusterName())); clusterInstanceService.getOne(new QueryWrapper<Cluster>().eq("name", task.getClusterName()));
...@@ -1152,12 +720,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1152,12 +720,7 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
continue; continue;
} }
Integer step = task.getStep(); this.saveOrUpdateTask(task.buildTask());
this.saveOrUpdateTask(task);
if (!JobLifeCycle.CREATE.getValue().equals(step)) {
task.setStep(step);
updateById(task);
}
if (Asserts.isNotNull(task.getEnvName())) { if (Asserts.isNotNull(task.getEnvName())) {
tasks.add(task); tasks.add(task);
} }
...@@ -1165,11 +728,11 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1165,11 +728,11 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
catalogueService.saveOrUpdate(catalogue); catalogueService.saveOrUpdate(catalogue);
} }
for (Task task : tasks) { for (TaskDTO task : tasks) {
Task task1 = getOne(new QueryWrapper<Task>().eq("name", task.getEnvName())); Task task1 = getOne(new QueryWrapper<Task>().eq("name", task.getEnvName()));
if (Asserts.isNotNull(task1)) { if (Asserts.isNotNull(task1)) {
task.setEnvId(task1.getId()); task.setEnvId(task1.getId());
this.saveOrUpdateTask(task); this.saveOrUpdateTask(task.buildTask());
} }
} }
...@@ -1249,116 +812,4 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen ...@@ -1249,116 +812,4 @@ public class TaskServiceImpl extends SuperServiceImpl<TaskMapper, Task> implemen
} }
return treeNodes; return treeNodes;
} }
@Override
public Result<List<Task>> queryOnLineTaskByDoneStatus(
List<JobLifeCycle> jobLifeCycle, List<JobStatus> jobStatuses, boolean includeNull, Integer catalogueId) {
final Tree<Integer> node =
queryAllCatalogue().getDatas().getNode(Objects.isNull(catalogueId) ? 0 : catalogueId);
final List<Integer> parentIds = new ArrayList<>(0);
parentIds.add(node.getId());
childrenNodeParse(node, parentIds);
final List<Task> taskList = getTasks(jobLifeCycle, jobStatuses, includeNull, parentIds);
return Result.succeed(taskList);
}
private List<Task> getTasks(
List<JobLifeCycle> jobLifeCycle,
List<JobStatus> jobStatuses,
boolean includeNull,
List<Integer> parentIds) {
return this.baseMapper.queryOnLineTaskByDoneStatus(
parentIds,
jobLifeCycle.stream()
.filter(Objects::nonNull)
.map(JobLifeCycle::getValue)
.collect(Collectors.toList()),
includeNull,
jobStatuses.stream().map(JobStatus::name).collect(Collectors.toList()));
}
private void childrenNodeParse(Tree<Integer> node, List<Integer> parentIds) {
final List<Tree<Integer>> children = node.getChildren();
if (CollectionUtils.isEmpty(children)) {
return;
}
for (Tree<Integer> child : children) {
parentIds.add(child.getId());
if (!child.hasChild()) {
continue;
}
childrenNodeParse(child, parentIds);
}
}
@Override
public void selectSavepointOnLineTask(TaskOperatingResult taskOperatingResult) {
final JobInstance jobInstanceByTaskId = jobInstanceService.getJobInstanceByTaskId(
taskOperatingResult.getTask().getId());
if (jobInstanceByTaskId == null) {
startGoingLiveTask(taskOperatingResult, null);
return;
}
if (!JobStatus.isDone(jobInstanceByTaskId.getStatus())) {
taskOperatingResult.setStatus(TaskOperatingStatus.TASK_STATUS_NO_DONE);
return;
}
if (taskOperatingResult.getTaskOperatingSavepointSelect().equals(TaskOperatingSavepointSelect.DEFAULT_CONFIG)) {
startGoingLiveTask(taskOperatingResult, null);
return;
}
findTheConditionSavePointToOnline(taskOperatingResult, jobInstanceByTaskId);
}
private void findTheConditionSavePointToOnline(
TaskOperatingResult taskOperatingResult, JobInstance jobInstanceByTaskId) {
final JobDataDto jobHistory = jobHistoryService.getJobHistoryDto(jobInstanceByTaskId.getId());
if (jobHistory != null) {
final JsonNode jsonNodes = jobHistory.getCheckpoints();
final ArrayNode history = jsonNodes.withArray("history");
if (!history.isEmpty()) {
startGoingLiveTask(taskOperatingResult, findTheConditionSavePoint(history));
return;
}
}
startGoingLiveTask(taskOperatingResult, null);
}
private void startGoingLiveTask(TaskOperatingResult taskOperatingResult, String savepointPath) {
taskOperatingResult.setStatus(TaskOperatingStatus.OPERATING);
final Result result = reOnLineTask(taskOperatingResult.getTask().getId(), savepointPath);
taskOperatingResult.parseResult(result);
}
private String findTheConditionSavePoint(ArrayNode history) {
JsonNode latestCompletedJsonNode = null;
for (JsonNode item : history) {
if (!"COMPLETED".equals(item.get("status").asText())) {
continue;
}
if (latestCompletedJsonNode == null) {
latestCompletedJsonNode = item;
continue;
}
if (latestCompletedJsonNode.get("id").asInt() < item.get("id").asInt(-1)) {
latestCompletedJsonNode = item;
}
}
return latestCompletedJsonNode == null
? null
: latestCompletedJsonNode.get("external_path").asText();
}
@Override
public void selectSavepointOffLineTask(TaskOperatingResult taskOperatingResult) {
taskOperatingResult.setStatus(TaskOperatingStatus.OPERATING);
final Result result = offLineTask(taskOperatingResult.getTask().getId(), SavePointType.CANCEL.getValue());
taskOperatingResult.parseResult(result);
}
} }
...@@ -19,17 +19,26 @@ ...@@ -19,17 +19,26 @@
package org.dinky.service.impl; 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.data.model.TaskVersion;
import org.dinky.mapper.TaskVersionMapper; import org.dinky.mapper.TaskVersionMapper;
import org.dinky.mybatis.service.impl.SuperServiceImpl; import org.dinky.mybatis.service.impl.SuperServiceImpl;
import org.dinky.service.TaskVersionService; import org.dinky.service.TaskVersionService;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.bean.BeanUtil;
@Service @Service
public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper, TaskVersion> public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper, TaskVersion>
implements TaskVersionService { implements TaskVersionService {
...@@ -41,4 +50,41 @@ public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper, ...@@ -41,4 +50,41 @@ public class TaskVersionServiceImpl extends SuperServiceImpl<TaskVersionMapper,
.eq(TaskVersion::getTaskId, taskId) .eq(TaskVersion::getTaskId, taskId)
.orderByDesc(true, TaskVersion::getVersionId)); .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 @@ ...@@ -20,6 +20,7 @@
package org.dinky.service.impl; package org.dinky.service.impl;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.context.RowLevelPermissionsContext;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.context.UserInfoContextHolder; import org.dinky.context.UserInfoContextHolder;
import org.dinky.data.dto.LoginDTO; import org.dinky.data.dto.LoginDTO;
...@@ -55,6 +56,7 @@ import org.dinky.service.UserTenantService; ...@@ -55,6 +56,7 @@ import org.dinky.service.UserTenantService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -366,6 +368,21 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen ...@@ -366,6 +368,21 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
return roleSelectPermissionsService.listRoleSelectPermissionsByRoleIds(roleIds); 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 @Override
public void outLogin() { public void outLogin() {
StpUtil.logout(StpUtil.getLoginIdAsInt()); 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 { ...@@ -77,7 +77,7 @@ public enum Dialect {
* @param value {@link Dialect} * @param value {@link Dialect}
* @return If is flink sql, return false, otherwise return true. * @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); Dialect dialect = Dialect.get(value);
switch (dialect) { switch (dialect) {
case SQL: case SQL:
......
...@@ -28,12 +28,8 @@ import java.util.Arrays; ...@@ -28,12 +28,8 @@ import java.util.Arrays;
*/ */
public enum JobLifeCycle { public enum JobLifeCycle {
UNKNOWN(0, "未知"), UNKNOWN(0, "未知"),
CREATE(1, "创建"), DEVELOP(1, "开发"),
DEVELOP(2, "开发"), ONLINE(2, "上线");
DEBUG(3, "调试"),
RELEASE(4, "发布"),
ONLINE(5, "上线"),
CANCEL(6, "注销");
private Integer value; private Integer value;
private String label; private String label;
......
...@@ -171,6 +171,10 @@ public enum Status { ...@@ -171,6 +171,10 @@ public enum Status {
TASK_NOT_EXIST(12003, "task.not.exist"), TASK_NOT_EXIST(12003, "task.not.exist"),
JOB_INSTANCE_NOT_EXIST(12004, "job.instance.not.exist"), JOB_INSTANCE_NOT_EXIST(12004, "job.instance.not.exist"),
SAVEPOINT_IS_NULL(12005, "savepoint.is.null"), 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 * alert instance
...@@ -195,6 +199,7 @@ public enum Status { ...@@ -195,6 +199,7 @@ public enum Status {
CLUSTER_INSTANCE_RECYCLE_SUCCESS(15002, "cluster.instance.recycle.success"), CLUSTER_INSTANCE_RECYCLE_SUCCESS(15002, "cluster.instance.recycle.success"),
CLUSTER_INSTANCE_KILL(15003, "cluster.instance.kill"), CLUSTER_INSTANCE_KILL(15003, "cluster.instance.kill"),
CLUSTER_INSTANCE_DEPLOY(15004, "cluster.instance.deploy"), CLUSTER_INSTANCE_DEPLOY(15004, "cluster.instance.deploy"),
CLUSTER_NOT_EXIST(15004, "cluster.not.exist"),
/** /**
* git * git
......
...@@ -92,6 +92,7 @@ tenant.name.exist=Tenant Already Exists ...@@ -92,6 +92,7 @@ tenant.name.exist=Tenant Already Exists
failed=Failed failed=Failed
added.failed=Added Failed added.failed=Added Failed
task.not.exist=Task Not Exist task.not.exist=Task Not Exist
task.is.online= Task is online, modification is prohibited
cluster.instance.deploy=Deploy Success cluster.instance.deploy=Deploy Success
clear.failed=Clear Failed clear.failed=Clear Failed
rename.success=Rename Successfully rename.success=Rename Successfully
...@@ -119,6 +120,7 @@ git.sort.failed=Git Sort Failed ...@@ -119,6 +120,7 @@ git.sort.failed=Git Sort Failed
query.failed=Query Failed query.failed=Query Failed
save.success=Save Successfully save.success=Save Successfully
cluster.instance.kill=Kill Success cluster.instance.kill=Kill Success
cluster.not.exist=Cluster Not Exist
operate.failed=Operate Failed operate.failed=Operate Failed
test.connection.failed=Test Connection Failed test.connection.failed=Test Connection Failed
switching.tenant.success=Select Tenant Success switching.tenant.success=Select Tenant Success
...@@ -231,4 +233,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS configuration items, s ...@@ -231,4 +233,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS configuration items, s
#Dinky Gateway #Dinky Gateway
gateway.kubernetes.test.failed= failed to test the Flink configuration: gateway.kubernetes.test.failed= failed to test the Flink configuration:
\ No newline at end of file
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=租户已存在 ...@@ -92,6 +92,7 @@ tenant.name.exist=租户已存在
failed=获取失败 failed=获取失败
added.failed=新增失败 added.failed=新增失败
task.not.exist=任务不存在 task.not.exist=任务不存在
task.is.online=任务已上线,禁止修改
cluster.instance.deploy=部署完成 cluster.instance.deploy=部署完成
clear.failed=清除失败 clear.failed=清除失败
rename.success=重命名成功 rename.success=重命名成功
...@@ -119,6 +120,7 @@ git.sort.failed=排序失败 ...@@ -119,6 +120,7 @@ git.sort.failed=排序失败
query.failed=查询失败 query.failed=查询失败
save.success=保存成功 save.success=保存成功
cluster.instance.kill=已杀死该进程/集群 cluster.instance.kill=已杀死该进程/集群
cluster.not.exist=集群不存在
operate.failed=操作失败 operate.failed=操作失败
test.connection.failed=测试连接失败 test.connection.failed=测试连接失败
switching.tenant.success=选择租户成功 switching.tenant.success=选择租户成功
...@@ -229,3 +231,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS 配置项,例如远 ...@@ -229,3 +231,8 @@ sys.resource.settings.hdfs.fs.defaultFS.note=fs.defaultFS 配置项,例如远
#Dinky Gateway #Dinky Gateway
gateway.kubernetes.test.failed=测试 Flink 配置失败: 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 @@ ...@@ -19,6 +19,8 @@
package org.dinky.data.result; package org.dinky.data.result;
import org.dinky.metadata.result.JdbcSelectResult;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import cn.hutool.cache.Cache; import cn.hutool.cache.Cache;
...@@ -33,6 +35,8 @@ public final class ResultPool { ...@@ -33,6 +35,8 @@ public final class ResultPool {
private 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)); private static final Cache<String, SelectResult> results = new TimedCache<>(TimeUnit.MINUTES.toMillis(10));
public static boolean containsKey(String key) { public static boolean containsKey(String key) {
...@@ -43,6 +47,14 @@ public final class ResultPool { ...@@ -43,6 +47,14 @@ public final class ResultPool {
results.put(result.getJobId(), result); 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) { public static SelectResult get(String key) {
if (containsKey(key)) { if (containsKey(key)) {
return results.get(key); return results.get(key);
......
...@@ -32,6 +32,7 @@ import org.dinky.executor.Executor; ...@@ -32,6 +32,7 @@ import org.dinky.executor.Executor;
import org.dinky.explainer.printTable.PrintStatementExplainer; import org.dinky.explainer.printTable.PrintStatementExplainer;
import org.dinky.function.data.model.UDF; import org.dinky.function.data.model.UDF;
import org.dinky.function.util.UDFUtil; import org.dinky.function.util.UDFUtil;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.interceptor.FlinkInterceptor; import org.dinky.interceptor.FlinkInterceptor;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
...@@ -362,14 +363,14 @@ public class Explainer { ...@@ -362,14 +363,14 @@ public class Explainer {
} }
public List<LineageRel> getLineage(String statement) { public List<LineageRel> getLineage(String statement) {
JobConfig jobConfig = new JobConfig( JobConfig jobConfig = JobConfig.builder()
"local", .type(GatewayType.LOCAL.getLongValue())
false, .useRemote(false)
false, .fragment(true)
true, .statementSet(useStatementSet)
useStatementSet, .parallelism(1)
1, .configJson(executor.getTableConfig().getConfiguration().toMap())
executor.getTableConfig().getConfiguration().toMap()); .build();
this.initialize(JobManager.buildPlanMode(jobConfig), jobConfig, statement); this.initialize(JobManager.buildPlanMode(jobConfig), jobConfig, statement);
List<LineageRel> lineageRelList = new ArrayList<>(); List<LineageRel> lineageRelList = new ArrayList<>();
......
...@@ -22,6 +22,7 @@ package org.dinky.job; ...@@ -22,6 +22,7 @@ package org.dinky.job;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.data.constant.NetConstant; import org.dinky.data.constant.NetConstant;
import org.dinky.executor.ExecutorConfig; import org.dinky.executor.ExecutorConfig;
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.enums.GatewayType;
import org.dinky.gateway.enums.SavePointStrategy; import org.dinky.gateway.enums.SavePointStrategy;
...@@ -35,25 +36,59 @@ import java.util.Map; ...@@ -35,25 +36,59 @@ import java.util.Map;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Getter; import lombok.AllArgsConstructor;
import lombok.Setter; import lombok.Builder;
import lombok.Data;
/** /**
* JobConfig * JobConfig
* *
* @since 2021/6/27 18:45 * @since 2021/6/27 18:45
*/ */
@Getter @Data
@Setter @Builder
@AllArgsConstructor
@ApiModel(value = "JobConfig", description = "Configuration details of a job") @ApiModel(value = "JobConfig", description = "Configuration details of a job")
public class JobConfig { public class JobConfig {
@ApiModelProperty(value = "Flink run mode", dataType = "String", example = "batch", notes = "Flink run mode") @ApiModelProperty(value = "Flink run mode", dataType = "String", example = "batch", notes = "Flink run mode")
private String type; private String type;
@ApiModelProperty(value = "Check Point", dataType = "Integer", example = "1", notes = "Check point for the task")
private Integer checkpoint;
@ApiModelProperty(value = "Save point strategy", dataType = "SavePointStrategy", notes = "Save point strategy")
private SavePointStrategy savePointStrategy;
@ApiModelProperty(value = "Save Point Path", dataType = "String", notes = "Save point path for the task")
private String savePointPath;
@ApiModelProperty(value = "Parallelism level", dataType = "Integer", example = "4", notes = "Parallelism level")
private Integer parallelism;
@ApiModelProperty(value = "Cluster ID", dataType = "Integer", example = "456", notes = "Cluster ID")
private Integer clusterId;
@ApiModelProperty(
value = "Cluster configuration ID",
dataType = "Integer",
example = "789",
notes = "Cluster configuration ID")
private Integer clusterConfigurationId;
@ApiModelProperty(value = "JAR file ID", dataType = "Integer", example = "101", notes = "JAR file ID")
private Integer jarId;
@ApiModelProperty(value = "Task JobLifeCycle", dataType = "Integer", example = "2", notes = "Task JobLifeCycle") @ApiModelProperty(value = "Task JobLifeCycle", dataType = "Integer", example = "2", notes = "Task JobLifeCycle")
private Integer step; private Integer step;
@ApiModelProperty(
value = "JSON configuration",
dataType = "Map<String, String>",
example = "{\"config1\": \"value1\", \"config2\": \"value2\"}",
notes = "JSON configuration")
private Map<String, String> configJson;
@ApiModelProperty( @ApiModelProperty(
value = "Flag indicating whether to use the result", value = "Flag indicating whether to use the result",
dataType = "boolean", dataType = "boolean",
...@@ -75,13 +110,6 @@ public class JobConfig { ...@@ -75,13 +110,6 @@ public class JobConfig {
notes = "Flag indicating whether to use auto-cancel") notes = "Flag indicating whether to use auto-cancel")
private boolean useAutoCancel; private boolean useAutoCancel;
@ApiModelProperty(
value = "Flag indicating whether to use session",
dataType = "boolean",
example = "true",
notes = "Flag indicating whether to use session")
private boolean useSession;
@ApiModelProperty( @ApiModelProperty(
value = "Session information", value = "Session information",
dataType = "String", dataType = "String",
...@@ -96,19 +124,6 @@ public class JobConfig { ...@@ -96,19 +124,6 @@ public class JobConfig {
notes = "Flag indicating whether to use remote execution") notes = "Flag indicating whether to use remote execution")
private boolean useRemote; private boolean useRemote;
@ApiModelProperty(value = "Cluster ID", dataType = "Integer", example = "456", notes = "Cluster ID")
private Integer clusterId;
@ApiModelProperty(
value = "Cluster configuration ID",
dataType = "Integer",
example = "789",
notes = "Cluster configuration ID")
private Integer clusterConfigurationId;
@ApiModelProperty(value = "JAR file ID", dataType = "Integer", example = "101", notes = "JAR file ID")
private Integer jarId;
@ApiModelProperty( @ApiModelProperty(
value = "Flag indicating whether it's a JAR task", value = "Flag indicating whether it's a JAR task",
dataType = "boolean", dataType = "boolean",
...@@ -148,21 +163,21 @@ public class JobConfig { ...@@ -148,21 +163,21 @@ public class JobConfig {
dataType = "boolean", dataType = "boolean",
example = "true", example = "true",
notes = "Flag indicating whether to use SQL fragment") notes = "Flag indicating whether to use SQL fragment")
private boolean useSqlFragment; private boolean fragment;
@ApiModelProperty( @ApiModelProperty(
value = "Flag indicating whether to use statement set", value = "Flag indicating whether to use statement set",
dataType = "boolean", dataType = "boolean",
example = "false", example = "false",
notes = "Flag indicating whether to use statement set") notes = "Flag indicating whether to use statement set")
private boolean useStatementSet; private boolean statementSet;
@ApiModelProperty( @ApiModelProperty(
value = "Flag indicating whether to use batch model", value = "Flag indicating whether to use batch model",
dataType = "boolean", dataType = "boolean",
example = "true", example = "true",
notes = "Flag indicating whether to use batch model") notes = "Flag indicating whether to use batch model")
private boolean useBatchModel; private boolean batchModel;
@ApiModelProperty( @ApiModelProperty(
value = "Maximum number of rows", value = "Maximum number of rows",
...@@ -171,26 +186,6 @@ public class JobConfig { ...@@ -171,26 +186,6 @@ public class JobConfig {
notes = "Maximum number of rows") notes = "Maximum number of rows")
private Integer maxRowNum; private Integer maxRowNum;
@ApiModelProperty(
value = "Checkpoint interval",
dataType = "Integer",
example = "5000",
notes = "Checkpoint interval")
private Integer checkpoint;
@ApiModelProperty(value = "Parallelism level", dataType = "Integer", example = "4", notes = "Parallelism level")
private Integer parallelism;
@ApiModelProperty(value = "Save point strategy", dataType = "SavePointStrategy", notes = "Save point strategy")
private SavePointStrategy savePointStrategy;
@ApiModelProperty(
value = "Path for save points",
dataType = "String",
example = "/savepoints",
notes = "Path for save points")
private String savePointPath;
@ApiModelProperty(value = "Gateway configuration", dataType = "GatewayConfig", notes = "Gateway configuration") @ApiModelProperty(value = "Gateway configuration", dataType = "GatewayConfig", notes = "Gateway configuration")
private GatewayConfig gatewayConfig; private GatewayConfig gatewayConfig;
...@@ -201,15 +196,8 @@ public class JobConfig { ...@@ -201,15 +196,8 @@ public class JobConfig {
notes = "Map of variables") notes = "Map of variables")
private Map<String, String> variables; private Map<String, String> variables;
@ApiModelProperty(
value = "JSON configuration",
dataType = "Map<String, String>",
example = "{\"config1\": \"value1\", \"config2\": \"value2\"}",
notes = "JSON configuration")
private Map<String, String> configJson;
public JobConfig() { public JobConfig() {
this.configJson = new HashMap<String, String>(); this.configJson = new HashMap<>();
} }
public void setAddress(String address) { public void setAddress(String address) {
...@@ -227,174 +215,14 @@ public class JobConfig { ...@@ -227,174 +215,14 @@ public class JobConfig {
} }
} }
public JobConfig(
String type,
boolean useSession,
boolean useRemote,
boolean useSqlFragment,
boolean useStatementSet,
Integer parallelism,
Map<String, String> configJson) {
this.type = type;
this.useSession = useSession;
this.useRemote = useRemote;
this.useSqlFragment = useSqlFragment;
this.useStatementSet = useStatementSet;
this.parallelism = parallelism;
this.configJson = configJson;
}
public JobConfig(
String type,
boolean useResult,
boolean useChangeLog,
boolean useAutoCancel,
boolean useSession,
String session,
Integer clusterId,
Integer clusterConfigurationId,
Integer jarId,
Integer taskId,
String jobName,
boolean useSqlFragment,
boolean useStatementSet,
boolean useBatchModel,
Integer maxRowNum,
Integer checkpoint,
Integer parallelism,
Integer savePointStrategyValue,
String savePointPath,
Map<String, String> variables,
Map<String, String> configJson) {
this.type = type;
this.useResult = useResult;
this.useChangeLog = useChangeLog;
this.useAutoCancel = useAutoCancel;
this.useSession = useSession;
this.session = session;
this.useRemote = true;
this.clusterId = clusterId;
this.clusterConfigurationId = clusterConfigurationId;
this.jarId = jarId;
this.taskId = taskId;
this.jobName = jobName;
this.useSqlFragment = useSqlFragment;
this.useStatementSet = useStatementSet;
this.useBatchModel = useBatchModel;
this.maxRowNum = maxRowNum;
this.checkpoint = checkpoint;
this.parallelism = parallelism;
this.savePointStrategy = SavePointStrategy.get(savePointStrategyValue);
this.savePointPath = savePointPath;
this.variables = variables;
this.configJson = configJson;
}
public JobConfig(
String type,
boolean useResult,
boolean useChangeLog,
boolean useAutoCancel,
boolean useSession,
String session,
boolean useRemote,
String address,
String jobName,
boolean useSqlFragment,
boolean useStatementSet,
Integer maxRowNum,
Integer checkpoint,
Integer parallelism,
Integer savePointStrategyValue,
String savePointPath,
Map<String, String> configJson,
GatewayConfig gatewayConfig) {
this.type = type;
this.useResult = useResult;
this.useChangeLog = useChangeLog;
this.useAutoCancel = useAutoCancel;
this.useSession = useSession;
this.session = session;
this.useRemote = useRemote;
this.jobName = jobName;
this.useSqlFragment = useSqlFragment;
this.useStatementSet = useStatementSet;
this.maxRowNum = maxRowNum;
this.checkpoint = checkpoint;
this.parallelism = parallelism;
this.savePointStrategy = SavePointStrategy.get(savePointStrategyValue);
this.savePointPath = savePointPath;
this.configJson = configJson;
this.gatewayConfig = gatewayConfig;
setAddress(address);
}
public JobConfig(
String type,
boolean useResult,
boolean useSession,
String session,
boolean useRemote,
Integer clusterId,
Integer maxRowNum) {
this.type = type;
this.useResult = useResult;
this.useSession = useSession;
this.session = session;
this.useRemote = useRemote;
this.clusterId = clusterId;
this.maxRowNum = maxRowNum;
}
public JobConfig(
String type,
Integer step,
boolean useResult,
boolean useSession,
boolean useRemote,
Integer clusterId,
Integer clusterConfigurationId,
Integer jarId,
Integer taskId,
String jobName,
boolean useSqlFragment,
boolean useStatementSet,
boolean useBatchModel,
Integer checkpoint,
Integer parallelism,
Integer savePointStrategyValue,
String savePointPath,
Map<String, String> configJson,
boolean isJarTask) {
this.type = type;
this.step = step;
this.useResult = useResult;
this.useSession = useSession;
this.useRemote = useRemote;
this.clusterId = clusterId;
this.clusterConfigurationId = clusterConfigurationId;
this.jarId = jarId;
this.taskId = taskId;
this.jobName = jobName;
this.useSqlFragment = useSqlFragment;
this.useStatementSet = useStatementSet;
this.useBatchModel = useBatchModel;
this.checkpoint = checkpoint;
this.parallelism = parallelism;
this.savePointStrategy = SavePointStrategy.get(savePointStrategyValue);
this.savePointPath = savePointPath;
this.configJson = configJson;
this.isJarTask = isJarTask;
}
public ExecutorConfig getExecutorSetting() { public ExecutorConfig getExecutorSetting() {
return ExecutorConfig.build( return ExecutorConfig.build(
address, address,
checkpoint, checkpoint,
parallelism, parallelism,
useSqlFragment, fragment,
useStatementSet, statementSet,
useBatchModel, batchModel,
savePointPath, savePointPath,
jobName, jobName,
configJson, configJson,
...@@ -402,14 +230,13 @@ public class JobConfig { ...@@ -402,14 +230,13 @@ public class JobConfig {
} }
public void buildGatewayConfig(FlinkClusterConfig config) { public void buildGatewayConfig(FlinkClusterConfig config) {
FlinkConfig flinkConfig = config.getFlinkConfig();
flinkConfig.getConfiguration().putAll(getConfigJson());
flinkConfig.getConfiguration().put(CoreOptions.DEFAULT_PARALLELISM.key(), String.valueOf(parallelism));
flinkConfig.setJobName(getJobName());
gatewayConfig = GatewayConfig.build(config); gatewayConfig = GatewayConfig.build(config);
gatewayConfig.setTaskId(getTaskId()); gatewayConfig.setTaskId(getTaskId());
gatewayConfig.getFlinkConfig().setJobName(getJobName());
gatewayConfig
.getFlinkConfig()
.getConfiguration()
.put(CoreOptions.DEFAULT_PARALLELISM.key(), String.valueOf(parallelism));
setUseRemote(false); // todo: remove
} }
public void addGatewayConfig(Map<String, Object> config) { public void addGatewayConfig(Map<String, Object> config) {
......
...@@ -176,7 +176,7 @@ public class JobManager { ...@@ -176,7 +176,7 @@ public class JobManager {
useGateway = GatewayType.isDeployCluster(config.getType()); useGateway = GatewayType.isDeployCluster(config.getType());
handler = JobHandler.build(); handler = JobHandler.build();
} }
useStatementSet = config.isUseStatementSet(); useStatementSet = config.isStatementSet();
useRestAPI = SystemConfiguration.getInstances().isUseRestAPI(); useRestAPI = SystemConfiguration.getInstances().isUseRestAPI();
sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator(); sqlSeparator = SystemConfiguration.getInstances().getSqlSeparator();
executorConfig = config.getExecutorSetting(); executorConfig = config.getExecutorSetting();
......
...@@ -21,12 +21,11 @@ package org.dinky.core; ...@@ -21,12 +21,11 @@ package org.dinky.core;
import org.dinky.data.result.ResultPool; import org.dinky.data.result.ResultPool;
import org.dinky.data.result.SelectResult; import org.dinky.data.result.SelectResult;
import org.dinky.gateway.enums.GatewayType;
import org.dinky.job.JobConfig; import org.dinky.job.JobConfig;
import org.dinky.job.JobManager; import org.dinky.job.JobManager;
import org.dinky.job.JobResult; import org.dinky.job.JobResult;
import java.util.HashMap;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -45,29 +44,20 @@ public class JobManagerTest { ...@@ -45,29 +44,20 @@ public class JobManagerTest {
@Ignore @Ignore
@Test @Test
public void cancelJobSelect() { public void cancelJobSelect() {
JobConfig config = JobConfig.builder()
JobConfig config = new JobConfig( .type(GatewayType.YARN_SESSION.getLongValue())
"session-yarn", .useResult(true)
true, .useChangeLog(true)
true, .useAutoCancel(true)
true, .session("s1")
true, .clusterId(2)
"s1", .jobName("Test")
2, .fragment(false)
null, .statementSet(false)
null, .batchModel(false)
null, .maxRowNum(100)
"测试", .parallelism(1)
false, .build();
false,
false,
100,
0,
1,
0,
null,
new HashMap<>(),
new HashMap<>());
if (config.isUseRemote()) { if (config.isUseRemote()) {
config.setAddress("192.168.123.157:8081"); 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));
}
}
...@@ -30,6 +30,7 @@ import java.util.List; ...@@ -30,6 +30,7 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrFormatter;
/** /**
* Process * Process
...@@ -163,6 +164,10 @@ public class ProcessEntity { ...@@ -163,6 +164,10 @@ public class ProcessEntity {
ConsolePool.write(message, userId); ConsolePool.write(message, userId);
} }
public void info(String strPattern, Object... argArray) {
info(StrFormatter.format(strPattern, argArray));
}
public void infoSuccess() { public void infoSuccess() {
if (isNullProcess()) { if (isNullProcess()) {
return; return;
...@@ -189,6 +194,10 @@ public class ProcessEntity { ...@@ -189,6 +194,10 @@ public class ProcessEntity {
ConsolePool.write(message, userId); ConsolePool.write(message, userId);
} }
public void error(String strPattern, Object... argArray) {
error(StrFormatter.format(strPattern, argArray));
}
public void nextStep() { public void nextStep() {
if (isNullProcess()) { if (isNullProcess()) {
return; return;
......
import React, {useState} from "react";
import {Button} from "antd";
import {ButtonProps} from "antd/es/button/button";
export const LoadingBtn: React.FC<ButtonProps> = (props) => {
const [loading, setLoading] = useState(false);
const handleClick = async (event: React.MouseEvent<HTMLElement, MouseEvent>) => {
if (props.onClick) {
setLoading(true)
await props.onClick(event)
setLoading(false)
}
}
return (
<Button
{...props}
loading={loading}
onClick={(event) =>handleClick(event)}
></Button>
);
};
...@@ -36,6 +36,8 @@ export default { ...@@ -36,6 +36,8 @@ export default {
'button.edit': 'Edit', 'button.edit': 'Edit',
'button.start': 'Start', 'button.start': 'Start',
'button.stop': 'Stop', 'button.stop': 'Stop',
'button.publish': 'Publish',
'button.offline': 'OffLine',
'button.assignUser': 'Assign Users', 'button.assignUser': 'Assign Users',
'button.assignRole': 'Assign Role', 'button.assignRole': 'Assign Role',
'button.changePassword': 'Change Password', 'button.changePassword': 'Change Password',
......
...@@ -309,7 +309,7 @@ export default { ...@@ -309,7 +309,7 @@ export default {
'pages.datastudio.editor.stop.job': 'Stop job', 'pages.datastudio.editor.stop.job': 'Stop job',
'pages.datastudio.editor.stop.jobConfirm': 'Are you sure to stop the job [{jobName}]? ', 'pages.datastudio.editor.stop.jobConfirm': 'Are you sure to stop the job [{jobName}]? ',
'pages.datastudio.editor.submitting': 'The new task [{jobName}] is executing', 'pages.datastudio.editor.submitting': 'The new task [{jobName}] is executing',
'pages.datastudio.to.jobDetail': 'Go to Job Detail', 'pages.datastudio.to.jobDetail': 'Operation Center',
'pages.datastudio.explain.validate': 'Validating...', 'pages.datastudio.explain.validate': 'Validating...',
'pages.datastudio.explain.validate.allright': 'All Right', 'pages.datastudio.explain.validate.allright': 'All Right',
'pages.datastudio.explain.validate.error': 'There are errors, a total of {errorCount}', 'pages.datastudio.explain.validate.error': 'There are errors, a total of {errorCount}',
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
export default { export default {
'button.check': '检查', 'button.check': '检查',
'button.graph': '图', 'button.graph': 'DAG',
'button.create': '新建', 'button.create': '新建',
'button.recovery': '恢复', 'button.recovery': '恢复',
'button.close': '关闭', 'button.close': '关闭',
...@@ -38,6 +38,8 @@ export default { ...@@ -38,6 +38,8 @@ export default {
'button.edit': '编辑', 'button.edit': '编辑',
'button.start': '启动', 'button.start': '启动',
'button.stop': '停止', 'button.stop': '停止',
'button.publish': '发布',
'button.offline': '下线',
'button.assignUser': '分配用户', 'button.assignUser': '分配用户',
'button.assignRole': '分配角色', 'button.assignRole': '分配角色',
'button.changePassword': '修改密码', 'button.changePassword': '修改密码',
......
...@@ -290,8 +290,8 @@ export default { ...@@ -290,8 +290,8 @@ export default {
* *
* */ * */
'pages.datastudio.editor.check': '检查当前的 FlinkSql', 'pages.datastudio.editor.check': '检查',
'pages.datastudio.editor.exec': '执行', 'pages.datastudio.editor.exec': '运行',
'pages.datastudio.editor.exec.error': '任务【{jobName}】执行失败', 'pages.datastudio.editor.exec.error': '任务【{jobName}】执行失败',
'pages.datastudio.editor.exec.success': '执行成功', 'pages.datastudio.editor.exec.success': '执行成功',
'pages.datastudio.editor.execute.warn': 'pages.datastudio.editor.execute.warn':
...@@ -302,7 +302,7 @@ export default { ...@@ -302,7 +302,7 @@ export default {
'pages.datastudio.editor.stop.job': '停止作业', 'pages.datastudio.editor.stop.job': '停止作业',
'pages.datastudio.editor.stop.jobConfirm': '确定停止作业【{jobName}】吗?', 'pages.datastudio.editor.stop.jobConfirm': '确定停止作业【{jobName}】吗?',
'pages.datastudio.editor.submitting': '新任务【{jobName}】正在执行', 'pages.datastudio.editor.submitting': '新任务【{jobName}】正在执行',
'pages.datastudio.to.jobDetail': '跳转到作业详情', 'pages.datastudio.to.jobDetail': '运维',
'pages.datastudio.explain.validate': '正在校验中...', 'pages.datastudio.explain.validate': '正在校验中...',
'pages.datastudio.explain.validate.allright': '全部正确', 'pages.datastudio.explain.validate.allright': '全部正确',
'pages.datastudio.explain.validate.error': '存在错误,共计{errorCount}个', 'pages.datastudio.explain.validate.error': '存在错误,共计{errorCount}个',
......
...@@ -67,7 +67,7 @@ const Explain: React.FC<ExplainProps> = (props: any) => { ...@@ -67,7 +67,7 @@ const Explain: React.FC<ExplainProps> = (props: any) => {
...current, ...current,
// useSession: useSession, // useSession: useSession,
// session: currentSession.session, // session: currentSession.session,
configJson: JSON.stringify(current?.config), configJson: current?.config,
taskId: current?.id taskId: current?.id
}; };
setResult(<Text>{l('pages.datastudio.explain.validate')}</Text>); setResult(<Text>{l('pages.datastudio.explain.validate')}</Text>);
......
...@@ -17,7 +17,8 @@ ...@@ -17,7 +17,8 @@
* *
*/ */
import { TabsPageType } from '@/pages/DataStudio/model'; import { TabsPageType, TaskDataType } from '@/pages/DataStudio/model';
import { JOB_LIFE_CYCLE, JOB_STATUS } from '@/pages/DevOps/constants';
import { HomeOutlined } from '@ant-design/icons'; import { HomeOutlined } from '@ant-design/icons';
/** /**
...@@ -35,6 +36,20 @@ export const buildBreadcrumbItems = (breadcrumb: string) => { ...@@ -35,6 +36,20 @@ export const buildBreadcrumbItems = (breadcrumb: string) => {
return items; return items;
}; };
export const projectCommonShow = (type?: TabsPageType, subType?: string, data?: any) => { export const projectCommonShow = (type?: TabsPageType) => {
return type === TabsPageType.project; return type === TabsPageType.project;
}; };
export const isOnline = (data: TaskDataType | undefined) => {
if (data) {
return JOB_LIFE_CYCLE.ONLINE == data.step;
}
return false;
};
export const isRunning = (data: TaskDataType | undefined) => {
if (data) {
return JOB_STATUS.RUNNING == data.status;
}
return false;
};
...@@ -16,48 +16,54 @@ ...@@ -16,48 +16,54 @@
* limitations under the License. * limitations under the License.
* *
*/ */
import { LoadingBtn } from '@/components/CallBackButton/LoadingBtn';
import { FlexCenterDiv } from '@/components/StyledComponents'; import { FlexCenterDiv } from '@/components/StyledComponents';
import { getCurrentData, getCurrentTab, mapDispatchToProps } from '@/pages/DataStudio/function'; import { getCurrentData, getCurrentTab, mapDispatchToProps } from '@/pages/DataStudio/function';
import Explain from '@/pages/DataStudio/HeaderContainer/Explain'; import Explain from '@/pages/DataStudio/HeaderContainer/Explain';
import FlinkGraph from '@/pages/DataStudio/HeaderContainer/FlinkGraph'; import FlinkGraph from '@/pages/DataStudio/HeaderContainer/FlinkGraph';
import { import {
buildBreadcrumbItems, buildBreadcrumbItems,
isOnline,
isRunning,
projectCommonShow projectCommonShow
} from '@/pages/DataStudio/HeaderContainer/function'; } from '@/pages/DataStudio/HeaderContainer/function';
import { import {
cancelTask,
executeSql, executeSql,
getJobPlan, getJobPlan,
isOnline, offLinelTask,
isSql, onLineTask
offLineTask
} from '@/pages/DataStudio/HeaderContainer/service'; } from '@/pages/DataStudio/HeaderContainer/service';
import { import {
DataStudioParams,
DataStudioTabsItemType, DataStudioTabsItemType,
MetadataTabsItemType,
StateType, StateType,
TabsPageType, TabsPageType,
TaskDataType, TaskDataType,
VIEW VIEW
} from '@/pages/DataStudio/model'; } from '@/pages/DataStudio/model';
import { JOB_LIFE_CYCLE, JOB_STATUS } from '@/pages/DevOps/constants';
import { ConfigStateType } from '@/pages/SettingCenter/GlobalSetting/model'; import { ConfigStateType } from '@/pages/SettingCenter/GlobalSetting/model';
import { SettingConfigKeyEnum } from '@/pages/SettingCenter/GlobalSetting/SettingOverView/constants'; import { SettingConfigKeyEnum } from '@/pages/SettingCenter/GlobalSetting/SettingOverView/constants';
import { handlePutDataJson } from '@/services/BusinessCrud'; import { handlePutDataJson } from '@/services/BusinessCrud';
import { BaseConfigProperties } from '@/types/SettingCenter/data'; import { BaseConfigProperties } from '@/types/SettingCenter/data';
import { l } from '@/utils/intl'; import { l } from '@/utils/intl';
import { connect, history } from '@@/exports'; import { connect } from '@@/exports';
import { import {
ApartmentOutlined,
CaretRightFilled,
EnvironmentOutlined, EnvironmentOutlined,
FlagTwoTone, FundOutlined,
MergeCellsOutlined,
MoreOutlined, MoreOutlined,
PauseCircleTwoTone, PauseOutlined, PlayCircleTwoTone,
PlayCircleTwoTone,
RotateRightOutlined, RotateRightOutlined,
SafetyCertificateTwoTone, SaveOutlined,
SaveTwoTone, ScheduleOutlined,
SendOutlined, SendOutlined
SmileOutlined
} from '@ant-design/icons'; } from '@ant-design/icons';
import { Breadcrumb, Button, Descriptions, message, Modal, notification, Space } from 'antd'; import { Breadcrumb, Descriptions, message, Modal, Space } from 'antd';
import { ButtonProps } from 'antd/es/button/button';
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
const headerStyle: React.CSSProperties = { const headerStyle: React.CSSProperties = {
...@@ -71,12 +77,13 @@ const headerStyle: React.CSSProperties = { ...@@ -71,12 +77,13 @@ const headerStyle: React.CSSProperties = {
}; };
type ButtonRoute = { type ButtonRoute = {
icon: React.ReactNode; icon?: React.ReactNode;
title: string; title?: string;
click: () => void; click?: () => void;
hotKey?: (e: KeyboardEvent) => boolean; hotKey?: (e: KeyboardEvent) => boolean;
hotKeyDesc?: string; hotKeyDesc?: string;
isShow?: (type?: TabsPageType, subType?: string, data?: any) => boolean; isShow: boolean;
props?: ButtonProps;
}; };
const HeaderContainer = (props: any) => { const HeaderContainer = (props: any) => {
...@@ -91,18 +98,26 @@ const HeaderContainer = (props: any) => { ...@@ -91,18 +98,26 @@ const HeaderContainer = (props: any) => {
} = props; } = props;
const [modal, contextHolder] = Modal.useModal(); const [modal, contextHolder] = Modal.useModal();
const [notificationApi, notificationContextHolder] = notification.useNotification();
const [messageApi, messageContextHolder] = message.useMessage(); const [messageApi, messageContextHolder] = message.useMessage();
const [enableDs, setEnableDs] = useState<boolean>(false); const [enableDs, setEnableDs] = useState<boolean>(false);
const [currentData, setCurrentData] = useState<TaskDataType | undefined>(undefined);
const [currentTab, setCurrentTab] = useState<
DataStudioTabsItemType | MetadataTabsItemType | undefined
>(undefined);
useEffect(() => { useEffect(() => {
queryDsConfig(SettingConfigKeyEnum.DOLPHIN_SCHEDULER.toLowerCase()); queryDsConfig(SettingConfigKeyEnum.DOLPHIN_SCHEDULER.toLowerCase());
}, []); }, []);
useEffect(() => {
setCurrentTab(getCurrentTab(panes, activeKey));
setCurrentData(getCurrentData(panes, activeKey));
}, [panes, activeKey]);
useEffect(() => { useEffect(() => {
// 检查是否开启 ds 配置 & 如果 // 检查是否开启 ds 配置 & 如果
if (!dsConfig) { if (!dsConfig) {
dsConfig.map((item: BaseConfigProperties) => { dsConfig.foreach((item: BaseConfigProperties) => {
if (item.key === 'dolphinscheduler.settings.enable') { if (item.key === 'dolphinscheduler.settings.enable') {
setEnableDs(item.value === 'true'); setEnableDs(item.value === 'true');
} }
...@@ -110,201 +125,171 @@ const HeaderContainer = (props: any) => { ...@@ -110,201 +125,171 @@ const HeaderContainer = (props: any) => {
} }
}, [dsConfig]); }, [dsConfig]);
const handleSave = async () => {
await handlePutDataJson('/api/task', currentData);
saveTabs({ ...props.tabs });
};
const handlerStop = () => { const handlerStop = () => {
const current = getCurrentData(panes, activeKey); if (!currentData) return;
if (!current) {
return;
}
modal.confirm({ modal.confirm({
title: l('pages.datastudio.editor.stop.job'), title: l('pages.datastudio.editor.stop.job'),
content: l('pages.datastudio.editor.stop.jobConfirm', '', { content: l('pages.datastudio.editor.stop.jobConfirm', '', {
jobName: current.name jobName: currentData.name
}), }),
okText: l('button.confirm'), okText: l('button.confirm'),
cancelText: l('button.cancel'), cancelText: l('button.cancel'),
onOk: async () => { onOk: async () => {
offLineTask(l('pages.datastudio.editor.stop.job'), current.id, 'canceljob').then( cancelTask(l('pages.datastudio.editor.stop.job'), currentData.id).then(() => {
(result) => { currentData.status = JOB_STATUS.CANCELED;
( saveTabs({ ...props.tabs });
getCurrentTab(panes, activeKey)?.params as DataStudioParams });
).taskData.jobInstanceId = 0;
saveTabs({ ...props.tabs });
}
);
} }
}); });
}; };
const handlerExec = () => {
const current = getCurrentData(panes, activeKey);
if (!current) {
return;
}
if (!isSql(current.dialect) && !isOnline(current.type)) { const handlerSubmit = async () => {
messageApi.warning(l('pages.datastudio.editor.execute.warn', '', { type: current.type })); if (!currentData) return;
return;
}
const param: TaskDataType = {
...current,
jobName: current.name,
taskId: current.id
};
const taskKey = Math.random() * 1000 + ''; const res = await executeSql(
l('pages.datastudio.editor.submitting', '', { jobName: currentData.name }),
currentData.id
);
if (!res) return;
notificationApi.success({ updateJobRunningMsg({
message: l('pages.datastudio.editor.submitting', '', { taskId: currentData.id,
jobName: param.name jobName: currentData.name,
}), jobState: res.datas.status,
description: param.statement.substring(0, 40) + '...', runningLog: res.msg
duration: null,
key: taskKey,
icon: <SmileOutlined style={{ color: '#108ee9' }} />
}); });
executeSql(l('pages.datastudio.editor.submitting', '', { jobName: param.name }), param).then( messageApi.success(l('pages.datastudio.editor.exec.success'));
(res) => { currentData.status = JOB_STATUS.RUNNING;
notificationApi.destroy(taskKey); saveTabs({ ...props.tabs });
if (!res) { };
return;
} const handleChangeJobLife = async () => {
updateJobRunningMsg({ if (!currentData) return;
taskId: current.id, if (isOnline(currentData)) {
jobName: current.name, await offLinelTask(currentData.id);
jobState: res.datas.status, currentData.step = JOB_LIFE_CYCLE.DEVELOP;
runningLog: res.msg } else {
}); await onLineTask(currentData.id);
if (res.datas.success) { currentData.step = JOB_LIFE_CYCLE.ONLINE;
messageApi.success(l('pages.datastudio.editor.exec.success')); }
(getCurrentTab(panes, activeKey)?.params as DataStudioParams).taskData.jobInstanceId = saveTabs({ ...props.tabs });
res.datas.jobInstanceId; };
saveTabs({ ...props.tabs });
} const showDagGraph = async () => {
} const result = await getJobPlan(l('pages.datastudio.editor.explan.tip'), currentData);
); if (result) {
modal.confirm({
title: l('pages.datastudio.editor.explan.tip'),
width: '100%',
icon: null,
content: <FlinkGraph data={result.datas} />,
cancelButtonProps: { style: { display: 'none' } }
});
}
};
const showExplain = async () => {
modal.confirm({
title: l('pages.datastudio.explain.validate.msg'),
width: '100%',
icon: null,
content: <Explain />,
cancelButtonProps: { style: { display: 'none' } }
});
}; };
const routes: ButtonRoute[] = [ const routes: ButtonRoute[] = [
// 保存按钮 icon // 保存按钮 icon
{ {
icon: <SaveTwoTone />,
title: l('button.save'),
click: () => {
const current = getCurrentData(panes, activeKey);
handlePutDataJson('/api/task', current).then(() => saveTabs({ ...props.tabs }));
},
hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's', hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's',
hotKeyDesc: 'Ctrl+S', hotKeyDesc: 'Ctrl+S',
isShow: projectCommonShow isShow: projectCommonShow(currentTab?.type),
icon: <SaveOutlined />,
title: l('button.save'),
click: () => handleSave(),
props: {
disabled: isOnline(currentData)
}
},
{
// 执行图按钮
icon: <ApartmentOutlined />,
title: l('button.graph'),
isShow: projectCommonShow(currentTab?.type),
click: async () => showDagGraph()
}, },
{ {
// 检查 sql按钮 // 检查 sql按钮
icon: <SafetyCertificateTwoTone />, icon: <ScheduleOutlined />,
title: l('pages.datastudio.editor.check'), title: l('pages.datastudio.editor.check'),
click: () => { click: () => showExplain(),
modal.confirm({ isShow: projectCommonShow(currentTab?.type)
title: l('pages.datastudio.explain.validate.msg'),
width: '100%',
icon: null,
content: <Explain />,
cancelButtonProps: { style: { display: 'none' } }
});
},
isShow: projectCommonShow
// hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's'
}, },
{ {
// 执行图按钮 // 推送海豚, 此处需要将系统设置中的 ds 的配置拿出来做判断 启用才展示
icon: <FlagTwoTone />, icon: <SendOutlined className={'blue-icon'} />,
title: l('button.graph'), title: l('button.push'),
click: () => { hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's',
const currentData = getCurrentData(panes, activeKey); isShow: enableDs
const res = getJobPlan(l('pages.datastudio.editor.explan.tip'), currentData); },
res.then((result) => { {
if (result) { // 发布按钮
modal.confirm({ icon: isOnline(currentData) ? <MergeCellsOutlined /> : <FundOutlined />,
title: l('pages.datastudio.editor.explan.tip'), title: isOnline(currentData) ? l('button.offline') : l('button.publish'),
width: '100%', isShow: currentTab?.type == TabsPageType.project,
icon: null, click: () => handleChangeJobLife()
content: <FlinkGraph data={result.datas} />, },
cancelButtonProps: { style: { display: 'none' } } {
}); // flink jobdetail跳转
} icon: <RotateRightOutlined />,
}); title: l('pages.datastudio.to.jobDetail'),
}, isShow:
// hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's' currentTab?.type == TabsPageType.project &&
isShow: projectCommonShow currentData?.jobInstanceId &&
currentTab.subType == 'flinksql',
props: {
href: `/#/devops/job-detail?id=${currentData?.jobInstanceId}`,
target: '_blank'
}
}, },
{ {
// 执行按钮 // 执行按钮
icon: <PlayCircleTwoTone />, icon: <CaretRightFilled/>,
title: l('pages.datastudio.editor.exec'), title: l('pages.datastudio.editor.exec'),
click: handlerExec, click: handlerSubmit,
hotKey: (e: KeyboardEvent) => e.shiftKey && e.key === 'F10', hotKey: (e: KeyboardEvent) => e.shiftKey && e.key === 'F10',
hotKeyDesc: 'Shift+F10', hotKeyDesc: 'Shift+F10',
isShow: (type?: TabsPageType, subType?: string, data?: any) => isShow: currentTab?.type == TabsPageType.project && !isRunning(currentData),
type === TabsPageType.project && !data?.jobInstanceId props: {
style: {background: "#52c41a"},
type: 'primary',
}
}, },
{ {
// 停止按钮 // 停止按钮
icon: <PauseCircleTwoTone />, icon: <PauseOutlined />,
title: l('pages.datastudio.editor.stop'), title: l('pages.datastudio.editor.stop'),
click: handlerStop, click: handlerStop,
isShow: (type?: TabsPageType, subType?: string, data?: any) => isShow: currentTab?.type == TabsPageType.project && isRunning(currentData),
type === TabsPageType.project && data?.jobInstanceId hotKey: (e: KeyboardEvent) => e.shiftKey && e.key === 'F10',
// hotKey: (e: KeyboardEvent) => e.shiftKey && e.key === 'F10', hotKeyDesc: 'Shift+F10',
// hotKeyDesc: "Shift+F10" props: {
}, type: 'primary',
{ danger: true
// flink jobdetail跳转 }
icon: <RotateRightOutlined />,
title: l('pages.datastudio.to.jobDetail'),
click: () => history.push(`/devops/job-detail?id=${getCurrentData(panes, activeKey)?.id}`),
isShow: (type?: TabsPageType, subType?: string, data?: any) =>
type === TabsPageType.project && data?.jobInstanceId && subType === 'flinksql'
},
// {
// // 异步提交按钮
// icon: <RocketTwoTone/>,
// title: l('button.async'),
// click: () => {
// console.log("ctrl+s")
// },
// // hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's'
// },
{
// 推送海豚, 此处需要将系统设置中的 ds 的配置拿出来做判断 启用才展示
icon: <SendOutlined className={'blue-icon'} />,
title: l('button.push'),
click: () => {},
hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's',
isShow: () => enableDs
}, },
// {
// // 发布按钮
// icon: <PauseCircleTwoTone/>,
// title: l('button.publish'),
// click: () => {
// console.log("ctrl+s")
// },
// // hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's'
// }, {
// // api 按钮
// icon: <ApiTwoTone/>,
// title: l('button.api'),
// click: () => {
// console.log("ctrl+s")
// },
// // hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's'
// },
{ {
//
icon: <MoreOutlined />, icon: <MoreOutlined />,
title: 'More', title: '',
click: () => {}, click: () => {},
isShow: () => true isShow: true
// hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's' // hotKey: (e: KeyboardEvent) => e.ctrlKey && e.key === 's'
} }
]; ];
...@@ -328,59 +313,44 @@ const HeaderContainer = (props: any) => { ...@@ -328,59 +313,44 @@ const HeaderContainer = (props: any) => {
</FlexCenterDiv> </FlexCenterDiv>
); );
}; };
const renderHotkey = () => {
document.onkeydown = (e) => { document.onkeydown = (e) => {
if (getCurrentTab(panes, activeKey)) { routes
routes .filter((r) => r.hotKey?.(e))
.filter((r) => r.hotKey?.(e)) .forEach((r) => {
.forEach((r) => { r.click?.();
r.click(); e.preventDefault();
e.preventDefault(); });
});
}
};
}; };
renderHotkey();
/** /**
* @description: 渲染右侧按钮 * @description: 渲染右侧按钮
*/ */
const renderRightButtons = () => { const renderRightButtons = () => {
return ( return (
<> <div style={{ padding: '4px' }}>
<Space size={'middle'} align={'center'} direction={'horizontal'} wrap> <Space size={'small'} align={'center'} direction={'horizontal'} wrap>
{routes {routes
.filter((x) => { .filter((x) => x.isShow)
if (x.isShow) {
const currentTab = getCurrentTab(panes, activeKey);
if (currentTab) {
return x.isShow(
currentTab?.type,
currentTab?.subType,
(currentTab as DataStudioTabsItemType)?.params.taskData
);
}
}
return false;
})
.map((route) => { .map((route) => {
const { icon, title, click, hotKeyDesc } = route;
return ( return (
<Button <LoadingBtn
key={title} key={route.title}
size={'small'} size={'small'}
type={'text'} type={'text'}
icon={icon} icon={route.icon}
title={title + (hotKeyDesc ? ' ' + hotKeyDesc : '')} onClick={route.click}
onClick={click} title={route.hotKeyDesc}
/> {...route.props}
>
{route.title}
</LoadingBtn>
); );
})} })}
</Space> </Space>
{contextHolder} {contextHolder}
{notificationContextHolder}
{messageContextHolder} {messageContextHolder}
</> </div>
); );
}; };
......
import { TaskDataType } from '@/pages/DataStudio/model';
import { postAll } from '@/services/api'; import { postAll } from '@/services/api';
import { handleGetOption, handleOption } from '@/services/BusinessCrud'; import { handleGetOption, handleOption } from '@/services/BusinessCrud';
import { DIALECT, RUN_MODE } from '@/services/constants'; import { DIALECT } from '@/services/constants';
export async function explainSql(params: any) { export async function explainSql(params: any) {
return postAll('/api/studio/explainSql', params); return postAll('/api/task/explainSql', params);
} }
export async function getJobPlan(title: string, params: any) { export async function getJobPlan(title: string, params: any) {
return handleOption('/api/studio/getJobPlan', title, params); return handleOption('/api/task/getJobPlan', title, params);
}
export async function executeSql(title: string, id: number) {
return handleGetOption('/api/task/submitTask', title, { id });
} }
export async function executeSql(title: string, params: TaskDataType) {
return handleOption('/api/studio/executeSql', title, params); export function cancelTask(title: string, id: number) {
return handleGetOption('api/task/cancel', title, { id });
}
export function onLineTask(id: number) {
return handleGetOption('api/task/onLineTask', '', { taskId: id });
} }
export function offLineTask(title: string, id: number, type: string) {
return handleGetOption('api/task/offLineTask', title, { id, type }); export function offLinelTask(id: number) {
return handleGetOption('api/task/offLineTask', '', { taskId: id });
} }
export const isSql = (dialect: string) => { export const isSql = (dialect: string) => {
...@@ -37,14 +47,3 @@ export const isSql = (dialect: string) => { ...@@ -37,14 +47,3 @@ export const isSql = (dialect: string) => {
return false; return false;
} }
}; };
export const isOnline = (type: string) => {
switch (type) {
case RUN_MODE.LOCAL:
case RUN_MODE.STANDALONE:
case RUN_MODE.YARN_SESSION:
case RUN_MODE.KUBERNETES_SESSION:
return true;
default:
return false;
}
};
...@@ -17,12 +17,8 @@ ...@@ -17,12 +17,8 @@
export enum JOB_LIFE_CYCLE { export enum JOB_LIFE_CYCLE {
UNKNOWN = 0, UNKNOWN = 0,
CREATE = 1, DEVELOP = 1,
DEVELOP = 2, ONLINE = 2
DEBUG = 3,
RELEASE = 4,
ONLINE = 5,
CANCEL = 6
} }
export enum JOB_STATUS { export enum JOB_STATUS {
......
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