ProcessInstanceService.java 30.2 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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.
 */
Q
qiaozhanwei 已提交
17

18
package org.apache.dolphinscheduler.api.service;
19 20 21 22 23 24 25 26

import static org.apache.dolphinscheduler.common.Constants.DATA_LIST;
import static org.apache.dolphinscheduler.common.Constants.DEPENDENT_SPLIT;
import static org.apache.dolphinscheduler.common.Constants.GLOBAL_PARAMS;
import static org.apache.dolphinscheduler.common.Constants.LOCAL_PARAMS;
import static org.apache.dolphinscheduler.common.Constants.PROCESS_INSTANCE_STATE;
import static org.apache.dolphinscheduler.common.Constants.TASK_LIST;

Q
qiaozhanwei 已提交
27 28 29 30 31
import org.apache.dolphinscheduler.api.dto.gantt.GanttDto;
import org.apache.dolphinscheduler.api.dto.gantt.Task;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.Result;
32
import org.apache.dolphinscheduler.common.Constants;
Q
qiaozhanwei 已提交
33 34 35 36 37 38 39
import org.apache.dolphinscheduler.common.enums.DependResult;
import org.apache.dolphinscheduler.common.enums.ExecutionStatus;
import org.apache.dolphinscheduler.common.enums.Flag;
import org.apache.dolphinscheduler.common.enums.TaskType;
import org.apache.dolphinscheduler.common.graph.DAG;
import org.apache.dolphinscheduler.common.model.TaskNode;
import org.apache.dolphinscheduler.common.model.TaskNodeRelation;
40
import org.apache.dolphinscheduler.common.process.ProcessDag;
Q
qiaozhanwei 已提交
41
import org.apache.dolphinscheduler.common.process.Property;
42 43 44 45 46
import org.apache.dolphinscheduler.common.utils.CollectionUtils;
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.common.utils.ParameterUtils;
import org.apache.dolphinscheduler.common.utils.StringUtils;
Q
qiaozhanwei 已提交
47
import org.apache.dolphinscheduler.common.utils.placeholder.BusinessTimeUtils;
48 49 50 51 52 53 54
import org.apache.dolphinscheduler.dao.entity.ProcessData;
import org.apache.dolphinscheduler.dao.entity.ProcessDefinition;
import org.apache.dolphinscheduler.dao.entity.ProcessInstance;
import org.apache.dolphinscheduler.dao.entity.Project;
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import org.apache.dolphinscheduler.dao.entity.Tenant;
import org.apache.dolphinscheduler.dao.entity.User;
S
simon 已提交
55 56 57 58
import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper;
import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper;
import org.apache.dolphinscheduler.dao.mapper.ProjectMapper;
import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper;
59
import org.apache.dolphinscheduler.dao.utils.DagHelper;
60
import org.apache.dolphinscheduler.service.process.ProcessService;
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

L
ligang 已提交
76 77 78 79
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
80
import org.springframework.transaction.annotation.Transactional;
L
ligang 已提交
81

82 83
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
L
ligang 已提交
84 85 86 87 88

/**
 * process instance service
 */
@Service
89
public class ProcessInstanceService extends BaseService {
L
ligang 已提交
90 91 92 93 94 95 96 97 98 99 100


    private static final Logger logger = LoggerFactory.getLogger(ProcessInstanceService.class);

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    ProjectService projectService;

    @Autowired
101
    ProcessService processService;
L
ligang 已提交
102 103 104 105 106 107 108 109 110 111

    @Autowired
    ProcessInstanceMapper processInstanceMapper;

    @Autowired
    ProcessDefinitionMapper processDefineMapper;

    @Autowired
    ProcessDefinitionService processDefinitionService;

112 113 114
    @Autowired
    ProcessDefinitionVersionService processDefinitionVersionService;

L
ligang 已提交
115 116 117 118 119 120 121 122 123
    @Autowired
    ExecutorService execService;

    @Autowired
    TaskInstanceMapper taskInstanceMapper;

    @Autowired
    LoggerService loggerService;

Q
qiaozhanwei 已提交
124

125 126 127
    @Autowired
    UsersService usersService;

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
    /**
     * return top n SUCCESS process instance order by running time which started between startTime and endTime
     */
    public Map<String, Object> queryTopNLongestRunningProcessInstance(User loginUser, String projectName, int size, String startTime, String endTime) {
        Map<String, Object> result = new HashMap<>();

        Project project = projectMapper.queryByName(projectName);
        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }

        if (0 > size) {
            putMsg(result, Status.NEGTIVE_SIZE_NUMBER_ERROR, size);
            return result;
        }
        if (Objects.isNull(startTime)) {
            putMsg(result, Status.DATA_IS_NULL, Constants.START_TIME);
            return result;
        }
        Date start = DateUtils.stringToDate(startTime);
        if (Objects.isNull(endTime)) {
            putMsg(result, Status.DATA_IS_NULL, Constants.END_TIME);
            return result;
        }
        Date end = DateUtils.stringToDate(endTime);
155
        if (start == null || end == null) {
156 157 158 159 160 161 162 163 164 165 166 167 168
            putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, "startDate,endDate");
            return result;
        }
        if (start.getTime() > end.getTime()) {
            putMsg(result, Status.START_TIME_BIGGER_THAN_END_TIME_ERROR, startTime, endTime);
            return result;
        }

        List<ProcessInstance> processInstances = processInstanceMapper.queryTopNProcessInstance(size, start, end, ExecutionStatus.SUCCESS);
        result.put(DATA_LIST, processInstances);
        putMsg(result, Status.SUCCESS);
        return result;
    }
169

L
ligang 已提交
170 171 172
    /**
     * query process instance by id
     *
B
bao liang 已提交
173 174 175 176
     * @param loginUser login user
     * @param projectName project name
     * @param processId process instance id
     * @return process instance detail
L
ligang 已提交
177 178
     */
    public Map<String, Object> queryProcessInstanceById(User loginUser, String projectName, Integer processId) {
_和's avatar
_和 已提交
179
        Map<String, Object> result = new HashMap<>();
L
ligang 已提交
180 181 182 183 184 185 186
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }
187
        ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
Q
test  
qiaozhanwei 已提交
188

189
        ProcessDefinition processDefinition = processService.findProcessDefineById(processInstance.getProcessDefinitionId());
leon-baoliang's avatar
leon-baoliang 已提交
190 191
        processInstance.setReceivers(processDefinition.getReceivers());
        processInstance.setReceiversCc(processDefinition.getReceiversCc());
192
        result.put(DATA_LIST, processInstance);
L
ligang 已提交
193 194 195 196 197 198 199 200
        putMsg(result, Status.SUCCESS);

        return result;
    }

    /**
     * paging query process instance list, filtering according to project, process definition, time range, keyword, process status
     *
B
bao liang 已提交
201 202 203 204 205 206 207 208 209 210 211
     * @param loginUser login user
     * @param projectName project name
     * @param pageNo page number
     * @param pageSize page size
     * @param processDefineId process definition id
     * @param searchVal search value
     * @param stateType state type
     * @param host host
     * @param startDate start time
     * @param endDate end time
     * @return process instance list
L
ligang 已提交
212 213 214
     */
    public Map<String, Object> queryProcessInstanceList(User loginUser, String projectName, Integer processDefineId,
                                                        String startDate, String endDate,
215
                                                        String searchVal, String executorName, ExecutionStatus stateType, String host,
L
ligang 已提交
216 217
                                                        Integer pageNo, Integer pageSize) {

_和's avatar
_和 已提交
218
        Map<String, Object> result = new HashMap<>();
L
ligang 已提交
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }

        int[] statusArray = null;
        // filter by state
        if (stateType != null) {
            statusArray = new int[]{stateType.ordinal()};
        }

        Date start = null;
        Date end = null;
        try {
            if (StringUtils.isNotEmpty(startDate)) {
                start = DateUtils.getScheduleDate(startDate);
            }
            if (StringUtils.isNotEmpty(endDate)) {
                end = DateUtils.getScheduleDate(endDate);
            }
        } catch (Exception e) {
            putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, "startDate,endDate");
            return result;
        }
246

247
        Page<ProcessInstance> page = new Page<>(pageNo, pageSize);
248 249
        PageInfo pageInfo = new PageInfo<ProcessInstance>(pageNo, pageSize);
        int executorId = usersService.getUserIdByName(executorName);
L
ligang 已提交
250

B
bao liang 已提交
251 252
        IPage<ProcessInstance> processInstanceList =
                processInstanceMapper.queryProcessInstanceListPaging(page,
253
                        project.getId(), processDefineId, searchVal, executorId, statusArray, host, start, end);
L
ligang 已提交
254

255
        List<ProcessInstance> processInstances = processInstanceList.getRecords();
256

257 258
        for (ProcessInstance processInstance : processInstances) {
            processInstance.setDuration(DateUtils.differSec(processInstance.getStartTime(), processInstance.getEndTime()));
259 260 261 262
            User executor = usersService.queryUser(processInstance.getExecutorId());
            if (null != executor) {
                processInstance.setExecutorName(executor.getUserName());
            }
263 264
        }

265
        pageInfo.setTotalCount((int) processInstanceList.getTotal());
266
        pageInfo.setLists(processInstances);
267
        result.put(DATA_LIST, pageInfo);
L
ligang 已提交
268 269 270 271 272 273 274
        putMsg(result, Status.SUCCESS);
        return result;
    }

    /**
     * query task list by process instance id
     *
B
bao liang 已提交
275 276 277 278 279
     * @param loginUser login user
     * @param projectName project name
     * @param processId process instance id
     * @return task list for the process instance
     * @throws IOException io exception
L
ligang 已提交
280 281 282 283 284 285 286 287 288 289
     */
    public Map<String, Object> queryTaskListByProcessId(User loginUser, String projectName, Integer processId) throws IOException {
        Map<String, Object> result = new HashMap<>();
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }
290 291
        ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
        List<TaskInstance> taskInstanceList = processService.findValidTaskListByProcessId(processId);
292
        addDependResultForTaskList(taskInstanceList);
L
ligang 已提交
293 294 295
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put(PROCESS_INSTANCE_STATE, processInstance.getState().toString());
        resultMap.put(TASK_LIST, taskInstanceList);
296
        result.put(DATA_LIST, resultMap);
L
ligang 已提交
297 298 299 300 301 302 303 304

        putMsg(result, Status.SUCCESS);
        return result;
    }

    /**
     * add dependent result for dependent task
     */
305
    private void addDependResultForTaskList(List<TaskInstance> taskInstanceList) throws IOException {
306 307
        for (TaskInstance taskInstance : taskInstanceList) {
            if (taskInstance.getTaskType().equalsIgnoreCase(TaskType.DEPENDENT.toString())) {
L
ligang 已提交
308 309
                Result logResult = loggerService.queryLog(
                        taskInstance.getId(), 0, 4098);
310
                if (logResult.getCode() == Status.SUCCESS.ordinal()) {
L
ligang 已提交
311 312
                    String log = (String) logResult.getData();
                    Map<String, DependResult> resultMap = parseLogForDependentResult(log);
张世鸣 已提交
313
                    taskInstance.setDependentResult(JSONUtils.toJsonString(resultMap));
L
ligang 已提交
314 315 316 317 318
                }
            }
        }
    }

319
    public Map<String, DependResult> parseLogForDependentResult(String log) throws IOException {
L
ligang 已提交
320
        Map<String, DependResult> resultMap = new HashMap<>();
321
        if (StringUtils.isEmpty(log)) {
L
ligang 已提交
322 323 324
            return resultMap;
        }

325
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(log.getBytes(
326
                StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
L
ligang 已提交
327 328
        String line;
        while ((line = br.readLine()) != null) {
329
            if (line.contains(DEPENDENT_SPLIT)) {
L
ligang 已提交
330
                String[] tmpStringArray = line.split(":\\|\\|");
331
                if (tmpStringArray.length != 2) {
L
ligang 已提交
332 333 334 335
                    continue;
                }
                String dependResultString = tmpStringArray[1];
                String[] dependStringArray = dependResultString.split(",");
336
                if (dependStringArray.length != 2) {
L
ligang 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349
                    continue;
                }
                String key = dependStringArray[0].trim();
                DependResult dependResult = DependResult.valueOf(dependStringArray[1].trim());
                resultMap.put(key, dependResult);
            }
        }
        return resultMap;
    }

    /**
     * query sub process instance detail info by task id
     *
B
bao liang 已提交
350 351 352 353
     * @param loginUser login user
     * @param projectName project name
     * @param taskId task id
     * @return sub process instance detail
L
ligang 已提交
354 355 356 357 358 359 360 361 362 363 364
     */
    public Map<String, Object> querySubProcessInstanceByTaskId(User loginUser, String projectName, Integer taskId) {
        Map<String, Object> result = new HashMap<>();
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }

365
        TaskInstance taskInstance = processService.findTaskInstanceById(taskId);
L
ligang 已提交
366 367 368 369 370 371 372 373 374
        if (taskInstance == null) {
            putMsg(result, Status.TASK_INSTANCE_NOT_EXISTS, taskId);
            return result;
        }
        if (!taskInstance.isSubProcess()) {
            putMsg(result, Status.TASK_INSTANCE_NOT_SUB_WORKFLOW_INSTANCE, taskInstance.getName());
            return result;
        }

375
        ProcessInstance subWorkflowInstance = processService.findSubProcessInstance(
L
ligang 已提交
376 377 378 379 380 381 382
                taskInstance.getProcessInstanceId(), taskInstance.getId());
        if (subWorkflowInstance == null) {
            putMsg(result, Status.SUB_PROCESS_INSTANCE_NOT_EXIST, taskId);
            return result;
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("subProcessInstanceId", subWorkflowInstance.getId());
383
        result.put(DATA_LIST, dataMap);
L
ligang 已提交
384 385 386 387 388 389 390
        putMsg(result, Status.SUCCESS);
        return result;
    }

    /**
     * update process instance
     *
B
bao liang 已提交
391 392 393 394 395 396 397 398 399 400 401
     * @param loginUser login user
     * @param projectName project name
     * @param processInstanceJson process instance json
     * @param processInstanceId process instance id
     * @param scheduleTime schedule time
     * @param syncDefine sync define
     * @param flag flag
     * @param locations locations
     * @param connects connects
     * @return update result code
     * @throws ParseException parse exception for json parse
L
ligang 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
     */
    public Map<String, Object> updateProcessInstance(User loginUser, String projectName, Integer processInstanceId,
                                                     String processInstanceJson, String scheduleTime, Boolean syncDefine,
                                                     Flag flag, String locations, String connects) throws ParseException {
        Map<String, Object> result = new HashMap<>();
        Project project = projectMapper.queryByName(projectName);

        //check project permission
        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }

        //check process instance exists
417
        ProcessInstance processInstance = processService.findProcessInstanceDetailById(processInstanceId);
L
ligang 已提交
418 419 420 421 422 423 424
        if (processInstance == null) {
            putMsg(result, Status.PROCESS_INSTANCE_NOT_EXIST, processInstanceId);
            return result;
        }

        //check process instance status
        if (!processInstance.getState().typeIsFinished()) {
B
baoliang 已提交
425 426
            putMsg(result, Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR,
                    processInstance.getName(), processInstance.getState().toString(), "update");
L
ligang 已提交
427 428 429 430 431 432 433 434
            return result;
        }
        Date schedule = null;
        if (scheduleTime != null) {
            schedule = DateUtils.getScheduleDate(scheduleTime);
        } else {
            schedule = processInstance.getScheduleTime();
        }
B
baoliang 已提交
435 436 437
        processInstance.setScheduleTime(schedule);
        processInstance.setLocations(locations);
        processInstance.setConnects(connects);
L
ligang 已提交
438 439
        String globalParams = null;
        String originDefParams = null;
B
baoliang 已提交
440
        int timeout = processInstance.getTimeout();
441
        ProcessDefinition processDefinition = processService.findProcessDefineById(processInstance.getProcessDefinitionId());
L
ligang 已提交
442 443 444 445 446 447 448 449
        if (StringUtils.isNotEmpty(processInstanceJson)) {
            ProcessData processData = JSONUtils.parseObject(processInstanceJson, ProcessData.class);
            //check workflow json is valid
            Map<String, Object> checkFlowJson = processDefinitionService.checkProcessNodeList(processData, processInstanceJson);
            if (checkFlowJson.get(Constants.STATUS) != Status.SUCCESS) {
                return result;
            }

张世鸣 已提交
450
            originDefParams = JSONUtils.toJsonString(processData.getGlobalParams());
L
ligang 已提交
451 452 453 454
            List<Property> globalParamList = processData.getGlobalParams();
            Map<String, String> globalParamMap = globalParamList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue));
            globalParams = ParameterUtils.curingGlobalParams(globalParamMap, globalParamList,
                    processInstance.getCmdTypeIfComplement(), schedule);
B
baoliang 已提交
455 456
            timeout = processData.getTimeout();
            processInstance.setTimeout(timeout);
457
            Tenant tenant = processService.getTenantForProcess(processData.getTenantId(),
458
                    processDefinition.getUserId());
459
            if (tenant != null) {
460 461
                processInstance.setTenantCode(tenant.getTenantCode());
            }
B
baoliang 已提交
462 463
            processInstance.setProcessInstanceJson(processInstanceJson);
            processInstance.setGlobalParams(globalParams);
L
ligang 已提交
464
        }
465

466
        int update = processService.updateProcessInstance(processInstance);
L
ligang 已提交
467
        int updateDefine = 1;
468
        if (Boolean.TRUE.equals(syncDefine) && StringUtils.isNotEmpty(processInstanceJson)) {
L
ligang 已提交
469 470 471 472
            processDefinition.setProcessDefinitionJson(processInstanceJson);
            processDefinition.setGlobalParams(originDefParams);
            processDefinition.setLocations(locations);
            processDefinition.setConnects(connects);
B
baoliang 已提交
473
            processDefinition.setTimeout(timeout);
474 475 476 477 478
            processDefinition.setUpdateTime(new Date());

            // add process definition version
            long version = processDefinitionVersionService.addProcessDefinitionVersion(processDefinition);
            processDefinition.setVersion(version);
B
bao liang 已提交
479
            updateDefine = processDefineMapper.updateById(processDefinition);
L
ligang 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493
        }
        if (update > 0 && updateDefine > 0) {
            putMsg(result, Status.SUCCESS);
        } else {
            putMsg(result, Status.UPDATE_PROCESS_INSTANCE_ERROR);
        }

        return result;

    }

    /**
     * query parent process instance detail info by sub process instance id
     *
B
bao liang 已提交
494 495 496 497
     * @param loginUser login user
     * @param projectName project name
     * @param subId sub process id
     * @return parent instance detail
L
ligang 已提交
498 499 500 501 502 503 504 505 506 507 508
     */
    public Map<String, Object> queryParentInstanceBySubId(User loginUser, String projectName, Integer subId) {
        Map<String, Object> result = new HashMap<>();
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }

509
        ProcessInstance subInstance = processService.findProcessInstanceDetailById(subId);
L
ligang 已提交
510 511 512 513 514 515 516 517 518
        if (subInstance == null) {
            putMsg(result, Status.PROCESS_INSTANCE_NOT_EXIST, subId);
            return result;
        }
        if (subInstance.getIsSubProcess() == Flag.NO) {
            putMsg(result, Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE, subInstance.getName());
            return result;
        }

519
        ProcessInstance parentWorkflowInstance = processService.findParentProcessInstance(subId);
L
ligang 已提交
520 521 522 523 524 525
        if (parentWorkflowInstance == null) {
            putMsg(result, Status.SUB_PROCESS_INSTANCE_NOT_EXIST);
            return result;
        }
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("parentWorkflowInstance", parentWorkflowInstance.getId());
526
        result.put(DATA_LIST, dataMap);
L
ligang 已提交
527 528 529 530 531 532
        putMsg(result, Status.SUCCESS);
        return result;
    }

    /**
     * delete process instance by id, at the same time,delete task instance and their mapping relation data
533
     *
B
bao liang 已提交
534 535 536 537
     * @param loginUser login user
     * @param projectName project name
     * @param processInstanceId process instance id
     * @return delete result code
L
ligang 已提交
538
     */
539
    @Transactional(rollbackFor = RuntimeException.class)
Q
qiaozhanwei 已提交
540
    public Map<String, Object> deleteProcessInstanceById(User loginUser, String projectName, Integer processInstanceId) {
L
ligang 已提交
541

_和's avatar
_和 已提交
542
        Map<String, Object> result = new HashMap<>();
L
ligang 已提交
543 544 545 546 547 548 549
        Project project = projectMapper.queryByName(projectName);

        Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
        Status resultEnum = (Status) checkResult.get(Constants.STATUS);
        if (resultEnum != Status.SUCCESS) {
            return checkResult;
        }
550
        ProcessInstance processInstance = processService.findProcessInstanceDetailById(processInstanceId);
551
        if (null == processInstance) {
552
            putMsg(result, Status.PROCESS_INSTANCE_NOT_EXIST, processInstanceId);
L
ligang 已提交
553 554
            return result;
        }
L
ligang 已提交
555

556
        processService.removeTaskLogFile(processInstanceId);
557
        // delete database cascade
558
        int delete = processService.deleteWorkProcessInstanceById(processInstanceId);
559

560 561
        processService.deleteAllSubWorkProcessByParentId(processInstanceId);
        processService.deleteWorkProcessMapByParentId(processInstanceId);
562 563

        if (delete > 0) {
L
ligang 已提交
564 565 566 567
            putMsg(result, Status.SUCCESS);
        } else {
            putMsg(result, Status.DELETE_PROCESS_INSTANCE_BY_ID_ERROR);
        }
568

L
ligang 已提交
569 570 571 572 573 574
        return result;
    }

    /**
     * view process instance variables
     *
B
bao liang 已提交
575 576
     * @param processInstanceId process instance id
     * @return variables data
L
ligang 已提交
577
     */
578
    public Map<String, Object> viewVariables(Integer processInstanceId) {
_和's avatar
_和 已提交
579
        Map<String, Object> result = new HashMap<>();
L
ligang 已提交
580 581 582

        ProcessInstance processInstance = processInstanceMapper.queryDetailById(processInstanceId);

D
dailidong 已提交
583 584 585 586
        if (processInstance == null) {
            throw new RuntimeException("workflow instance is null");
        }

L
ligang 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600
        Map<String, String> timeParams = BusinessTimeUtils
                .getBusinessTime(processInstance.getCmdTypeIfComplement(),
                        processInstance.getScheduleTime());

        String workflowInstanceJson = processInstance.getProcessInstanceJson();

        ProcessData workflowData = JSONUtils.parseObject(workflowInstanceJson, ProcessData.class);

        String userDefinedParams = processInstance.getGlobalParams();

        // global params
        List<Property> globalParams = new ArrayList<>();

        if (userDefinedParams != null && userDefinedParams.length() > 0) {
601
            globalParams = JSONUtils.toList(userDefinedParams, Property.class);
L
ligang 已提交
602 603 604 605 606
        }

        List<TaskNode> taskNodeList = workflowData.getTasks();

        // global param string
张世鸣 已提交
607
        String globalParamStr = JSONUtils.toJsonString(globalParams);
L
ligang 已提交
608
        globalParamStr = ParameterUtils.convertParameterPlaceholders(globalParamStr, timeParams);
S
simon824 已提交
609
        globalParams = JSONUtils.toList(globalParamStr, Property.class);
L
ligang 已提交
610 611 612 613 614
        for (Property property : globalParams) {
            timeParams.put(property.getProp(), property.getValue());
        }

        // local params
615
        Map<String, Map<String, Object>> localUserDefParams = new HashMap<>();
L
ligang 已提交
616 617 618 619 620 621
        for (TaskNode taskNode : taskNodeList) {
            String parameter = taskNode.getParams();
            Map<String, String> map = JSONUtils.toMap(parameter);
            String localParams = map.get(LOCAL_PARAMS);
            if (localParams != null && !localParams.isEmpty()) {
                localParams = ParameterUtils.convertParameterPlaceholders(localParams, timeParams);
S
simon824 已提交
622
                List<Property> localParamsList = JSONUtils.toList(localParams, Property.class);
S
simon824 已提交
623

624 625 626
                Map<String, Object> localParamsMap = new HashMap<>();
                localParamsMap.put("taskType", taskNode.getType());
                localParamsMap.put("localParamsList", localParamsList);
627
                if (CollectionUtils.isNotEmpty(localParamsList)) {
Q
qiaozhanwei 已提交
628
                    localUserDefParams.put(taskNode.getName(), localParamsMap);
L
ligang 已提交
629 630 631 632 633 634 635 636 637 638
                }
            }

        }

        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put(GLOBAL_PARAMS, globalParams);
        resultMap.put(LOCAL_PARAMS, localUserDefParams);

639
        result.put(DATA_LIST, resultMap);
L
ligang 已提交
640 641 642 643 644 645 646
        putMsg(result, Status.SUCCESS);
        return result;
    }

    /**
     * encapsulation gantt structure
     *
B
bao liang 已提交
647 648 649
     * @param processInstanceId process instance id
     * @return gantt tree data
     * @throws Exception exception when json parse
L
ligang 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
     */
    public Map<String, Object> viewGantt(Integer processInstanceId) throws Exception {
        Map<String, Object> result = new HashMap<>();

        ProcessInstance processInstance = processInstanceMapper.queryDetailById(processInstanceId);

        if (processInstance == null) {
            throw new RuntimeException("workflow instance is null");
        }

        GanttDto ganttDto = new GanttDto();

        DAG<String, TaskNode, TaskNodeRelation> dag = processInstance2DAG(processInstance);
        //topological sort
        List<String> nodeList = dag.topologicalSort();

        ganttDto.setTaskNames(nodeList);

        List<Task> taskList = new ArrayList<>();
        for (String node : nodeList) {
            TaskInstance taskInstance = taskInstanceMapper.queryByInstanceIdAndName(processInstanceId, node);
            if (taskInstance == null) {
                continue;
            }
            Date startTime = taskInstance.getStartTime() == null ? new Date() : taskInstance.getStartTime();
            Date endTime = taskInstance.getEndTime() == null ? new Date() : taskInstance.getEndTime();
            Task task = new Task();
            task.setTaskName(taskInstance.getName());
            task.getStartDate().add(startTime.getTime());
            task.getEndDate().add(endTime.getTime());
            task.setIsoStart(startTime);
            task.setIsoEnd(endTime);
            task.setStatus(taskInstance.getState().toString());
            task.setExecutionDate(taskInstance.getStartTime());
            task.setDuration(DateUtils.format2Readable(endTime.getTime() - startTime.getTime()));
            taskList.add(task);
        }
        ganttDto.setTasks(taskList);

689
        result.put(DATA_LIST, ganttDto);
L
ligang 已提交
690 691 692 693
        putMsg(result, Status.SUCCESS);
        return result;
    }

694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    /**
     * process instance to DAG
     *
     * @param processInstance input process instance
     * @return process instance dag.
     */
    private static DAG<String, TaskNode, TaskNodeRelation> processInstance2DAG(ProcessInstance processInstance) {

        String processDefinitionJson = processInstance.getProcessInstanceJson();

        ProcessData processData = JSONUtils.parseObject(processDefinitionJson, ProcessData.class);

        List<TaskNode> taskNodeList = processData.getTasks();

        ProcessDag processDag = DagHelper.getProcessDag(taskNodeList);

        return DagHelper.buildDagGraph(processDag);
    }

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    /**
     * query process instance by processDefinitionId and stateArray
     * @param processDefinitionId processDefinitionId
     * @param states states array
     * @return process instance list
     */
    public List<ProcessInstance> queryByProcessDefineIdAndStatus(int processDefinitionId, int[] states) {
        return processInstanceMapper.queryByProcessDefineIdAndStatus(processDefinitionId, states);
    }

    /**
     * query process instance by processDefinitionId
     * @param processDefinitionId processDefinitionId
     * @param size size
     * @return process instance list
     */
    public List<ProcessInstance> queryByProcessDefineId(int processDefinitionId,int size) {
        return processInstanceMapper.queryByProcessDefineId(processDefinitionId, size);
    }

L
ligang 已提交
733
}