Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature][Api] When use api to run a process we want get processInstanceId #13184

Merged
merged 34 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

package org.apache.dolphinscheduler.api.controller;

import static org.apache.dolphinscheduler.api.enums.Status.QUERY_PROCESS_INSTANCE_LIST_PAGING_ERROR;

import org.apache.dolphinscheduler.api.aspect.AccessLogAnnotation;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.exceptions.ApiException;
Expand Down Expand Up @@ -411,4 +413,20 @@ public Result batchDeleteProcessInstanceByIds(@RequestAttribute(value = Constant
}
return returnDataList(result);
}

@Operation(summary = "queryProcessInstanceListByTrigger", description = "QUERY_PROCESS_INSTANCE_BY_TRIGGER_NOTES")
@Parameters({
@Parameter(name = "projectCode", description = "PROJECT_CODE", required = true, schema = @Schema(implementation = Long.class)),
@Parameter(name = "triggerCode", description = "TRIGGER_CODE", required = true, schema = @Schema(implementation = Long.class))
})
@GetMapping("/trigger")
@ResponseStatus(HttpStatus.OK)
@ApiException(QUERY_PROCESS_INSTANCE_LIST_PAGING_ERROR)
@AccessLogAnnotation()
public Result queryProcessInstancesByTriggerCode(@RequestAttribute(value = Constants.SESSION_USER) User loginUser,
@PathVariable long projectCode,
@RequestParam(value = "triggerCode") Long triggerCode) {
Map<String, Object> result = processInstanceService.queryByTriggerCode(loginUser, projectCode, triggerCode);
return returnDataList(result);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,16 @@ List<ProcessInstance> queryByProcessDefineCodeAndStatus(Long processDefinitionCo
List<ProcessInstance> queryByProcessDefineCode(Long processDefinitionCode,
int size);

/**
* query process instance list bt trigger code
*
* @param loginUser
* @param projectCode
* @param triggerCode
* @return
*/
Map<String, Object> queryByTriggerCode(User loginUser, long projectCode, Long triggerCode);

void deleteProcessInstanceByWorkflowDefinitionCode(long workflowDefinitionCode);

void deleteProcessInstanceById(int workflowInstanceId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.apache.dolphinscheduler.api.service.ProjectService;
import org.apache.dolphinscheduler.api.service.WorkerGroupService;
import org.apache.dolphinscheduler.common.constants.Constants;
import org.apache.dolphinscheduler.common.enums.ApiTriggerType;
import org.apache.dolphinscheduler.common.enums.CommandType;
import org.apache.dolphinscheduler.common.enums.ComplementDependentMode;
import org.apache.dolphinscheduler.common.enums.CycleEnum;
Expand All @@ -52,6 +53,7 @@
import org.apache.dolphinscheduler.common.enums.WarningType;
import org.apache.dolphinscheduler.common.enums.WorkflowExecutionStatus;
import org.apache.dolphinscheduler.common.model.Server;
import org.apache.dolphinscheduler.common.utils.CodeGenerateUtils;
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.dao.entity.Command;
Expand Down Expand Up @@ -85,6 +87,7 @@
import org.apache.dolphinscheduler.service.cron.CronUtils;
import org.apache.dolphinscheduler.service.exceptions.CronParseException;
import org.apache.dolphinscheduler.service.process.ProcessService;
import org.apache.dolphinscheduler.service.process.TriggerRelationService;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
Expand All @@ -106,6 +109,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
Expand Down Expand Up @@ -164,6 +168,8 @@ public class ExecutorServiceImpl extends BaseServiceImpl implements ExecutorServ
@Autowired
private WorkerGroupService workerGroupService;

@Autowired
private TriggerRelationService triggerRelationService;
/**
* execute process instance
*
Expand All @@ -188,6 +194,7 @@ public class ExecutorServiceImpl extends BaseServiceImpl implements ExecutorServ
* @return execute process instance code
*/
@Override
@Transactional(rollbackFor = Exception.class)
public Map<String, Object> execProcessInstance(User loginUser, long projectCode, long processDefinitionCode,
String cronTime, CommandType commandType,
FailureStrategy failureStrategy, String startNodeList,
Expand Down Expand Up @@ -239,11 +246,15 @@ public Map<String, Object> execProcessInstance(User loginUser, long projectCode,
if (!checkMasterExists(result)) {
return result;
}

long triggerCode = CodeGenerateUtils.getInstance().genCode();

/**
* create command
*/
int create =
this.createCommand(commandType, processDefinition.getCode(), taskDependType, failureStrategy,
this.createCommand(triggerCode, commandType, processDefinition.getCode(), taskDependType,
failureStrategy,
startNodeList,
cronTime, warningType, loginUser.getId(), warningGroupId, runMode, processInstancePriority,
workerGroup,
Expand All @@ -255,6 +266,7 @@ public Map<String, Object> execProcessInstance(User loginUser, long projectCode,
processDefinitionMapper.updateById(processDefinition);
logger.info("Create command complete, processDefinitionCode:{}, commandCount:{}.",
processDefinition.getCode(), create);
result.put(Constants.DATA_LIST, triggerCode);
putMsg(result, Status.SUCCESS);
} else {
logger.error("Start process instance failed because create command error, processDefinitionCode:{}.",
Expand Down Expand Up @@ -878,7 +890,7 @@ public Map<String, Object> startCheckByProcessDefinedCode(long processDefinition
* @param environmentCode environmentCode
* @return command id
*/
private int createCommand(CommandType commandType, long processDefineCode, TaskDependType nodeDep,
private int createCommand(Long triggerCode, CommandType commandType, long processDefineCode, TaskDependType nodeDep,
FailureStrategy failureStrategy, String startNodeList, String schedule,
WarningType warningType, int executorId, Integer warningGroupId, RunMode runMode,
Priority processInstancePriority, String workerGroup, Long environmentCode,
Expand Down Expand Up @@ -940,7 +952,7 @@ private int createCommand(CommandType commandType, long processDefineCode, TaskD
try {
logger.info("Start to create {} command, processDefinitionCode:{}.",
command.getCommandType().getDescp(), processDefineCode);
return createComplementCommandList(schedule, runMode, command, expectedParallelismNumber,
return createComplementCommandList(triggerCode, schedule, runMode, command, expectedParallelismNumber,
complementDependentMode);
} catch (CronParseException cronParseException) {
// We catch the exception here just to make compiler happy, since we have already validated the schedule
Expand All @@ -949,8 +961,11 @@ private int createCommand(CommandType commandType, long processDefineCode, TaskD
}
} else {
command.setCommandParam(JSONUtils.toJsonString(cmdParam));
logger.info("Creating command, commandInfo:{}.", command);
return commandService.createCommand(command);
int count = commandService.createCommand(command);
if (count > 0) {
triggerRelationService.saveTriggerToDb(ApiTriggerType.COMMAND, triggerCode, command.getId());
}
return count;
}
}

Expand All @@ -962,7 +977,8 @@ private int createCommand(CommandType commandType, long processDefineCode, TaskD
* @param runMode
* @return
*/
protected int createComplementCommandList(String scheduleTimeParam, RunMode runMode, Command command,
protected int createComplementCommandList(Long triggerCode, String scheduleTimeParam, RunMode runMode,
Command command,
Integer expectedParallelismNumber,
ComplementDependentMode complementDependentMode) throws CronParseException {
int createCount = 0;
Expand Down Expand Up @@ -1027,6 +1043,9 @@ protected int createComplementCommandList(String scheduleTimeParam, RunMode runM
dependentProcessDefinitionCreateCount += createComplementDependentCommand(schedules, command);
}
}
if (createCount > 0) {
triggerRelationService.saveTriggerToDb(ApiTriggerType.COMMAND, triggerCode, command.getId());
}
break;
}
case RUN_MODE_PARALLEL: {
Expand Down Expand Up @@ -1075,6 +1094,8 @@ protected int createComplementCommandList(String scheduleTimeParam, RunMode runM
if (commandService.createCommand(command) > 0) {
logger.info("Create {} command complete, processDefinitionCode:{}",
command.getCommandType().getDescp(), command.getProcessDefinitionCode());
triggerRelationService.saveTriggerToDb(ApiTriggerType.COMMAND, triggerCode,
command.getId());
} else {
logger.error("Create {} command error, processDefinitionCode:{}",
command.getCommandType().getDescp(), command.getProcessDefinitionCode());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.dolphinscheduler.api.service.impl;

import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.WORKFLOW_INSTANCE;
import static org.apache.dolphinscheduler.api.enums.Status.PROCESS_INSTANCE_NOT_EXIST;
import static org.apache.dolphinscheduler.api.enums.Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR;
import static org.apache.dolphinscheduler.common.constants.Constants.DATA_LIST;
Expand Down Expand Up @@ -1021,6 +1022,32 @@ public List<ProcessInstance> queryByProcessDefineCode(Long processDefinitionCode
return processInstanceMapper.queryByProcessDefineCode(processDefinitionCode, size);
}

/**
* query process instance list bt trigger code
*
* @param loginUser
* @param projectCode
* @param triggerCode
* @return
*/
@Override
public Map<String, Object> queryByTriggerCode(User loginUser, long projectCode, Long triggerCode) {

Project project = projectMapper.queryByCode(projectCode);
// check user access for project
Map<String, Object> result =
projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE);
if (result.get(Constants.STATUS) != Status.SUCCESS || triggerCode == null) {
return result;
}

List<ProcessInstance> processInstances = processInstanceMapper.queryByTriggerCode(
triggerCode);
result.put(DATA_LIST, processInstances);
putMsg(result, Status.SUCCESS);
return result;
}

@Override
public void deleteProcessInstanceByWorkflowDefinitionCode(long workflowDefinitionCode) {
while (true) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,4 +248,24 @@ public void testBatchDeleteProcessInstanceByIds() throws Exception {
Assertions.assertNotNull(result);
Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());
}

@Test
public void queryProcessInstancesByTriggerCode() throws Exception {
Map<String, Object> mockResult = new HashMap<>();
mockResult.put(Constants.STATUS, Status.SUCCESS);

Mockito.when(processInstanceService
.queryByTriggerCode(Mockito.any(), Mockito.anyLong(), Mockito.anyLong()))
.thenReturn(mockResult);

MvcResult mvcResult = mockMvc.perform(get("/projects/1113/process-instances/trigger")
.header("sessionId", sessionId)
.param("triggerCode", "12051206"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class);
Assertions.assertNotNull(result);
Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
import org.apache.dolphinscheduler.dao.mapper.TaskGroupQueueMapper;
import org.apache.dolphinscheduler.service.command.CommandService;
import org.apache.dolphinscheduler.service.process.ProcessService;
import org.apache.dolphinscheduler.service.process.TriggerRelationService;

import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -143,6 +144,9 @@ public class ExecutorServiceTest {
@Mock
private ProcessInstanceMapper processInstanceMapper;

@Mock
private TriggerRelationService triggerRelationService;

private int processDefinitionId = 1;

private int processDefinitionVersion = 1;
Expand Down Expand Up @@ -231,6 +235,8 @@ public void init() {
Mockito.when(processService.findProcessDefinition(1L, 1)).thenReturn(this.processDefinition);
Mockito.when(taskGroupQueueMapper.selectById(1)).thenReturn(taskGroupQueue);
Mockito.when(processInstanceMapper.selectById(1)).thenReturn(processInstance);
Mockito.when(triggerRelationService.saveProcessInstanceTrigger(Mockito.any(), Mockito.any()))
.thenReturn(1);
Mockito.when(processService.findRelationByCode(processDefinitionCode, processDefinitionVersion))
.thenReturn(processTaskRelations);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,28 @@ public void testQueryProcessInstanceList() {

}

@Test
public void queryByTriggerCode() {
long projectCode = 666L;
User loginUser = getAdminUser();
Project project = getProject(projectCode);
Map<String, Object> result = new HashMap<>();
putMsg(result, Status.PROJECT_NOT_FOUND, projectCode);

// project auth fail
when(projectMapper.queryByCode(projectCode)).thenReturn(project);
when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result);
Map<String, Object> proejctAuthFailMap =
processInstanceService.queryByTriggerCode(loginUser, projectCode, 999L);
Assertions.assertEquals(Status.PROJECT_NOT_FOUND, proejctAuthFailMap.get(Constants.STATUS));
// project auth sucess
putMsg(result, Status.SUCCESS, projectCode);
when(processInstanceMapper.queryByTriggerCode(projectCode)).thenReturn(new ArrayList());
proejctAuthFailMap =
processInstanceService.queryByTriggerCode(loginUser, projectCode, 999L);
Assertions.assertEquals(Status.SUCCESS, proejctAuthFailMap.get(Constants.STATUS));
}

@Test
public void testQueryTopNLongestRunningProcessInstance() {
long projectCode = 1L;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* 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.apache.dolphinscheduler.common.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;

/**
* trigger support type
*/
public enum ApiTriggerType {

PROCESS(0, "process instance"),
TASK(1, "task node"),
COMMAND(2, "command");

ApiTriggerType(int code, String desc) {
this.code = code;
this.desc = desc;
}

@EnumValue
private final int code;
private final String desc;

public int getCode() {
return code;
}

public String getDesc() {
return desc;
}
}
Loading