ProcessService.java 108.1 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.
 */
17

18
package org.apache.dolphinscheduler.service.process;
Q
qiaozhanwei 已提交
19

20
import static java.util.stream.Collectors.toSet;
21 22
import static org.apache.dolphinscheduler.common.Constants.CMDPARAM_COMPLEMENT_DATA_END_DATE;
import static org.apache.dolphinscheduler.common.Constants.CMDPARAM_COMPLEMENT_DATA_START_DATE;
K
Kirs 已提交
23
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_EMPTY_SUB_PROCESS;
24
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_FATHER_PARAMS;
K
Kirs 已提交
25 26
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_RECOVER_PROCESS_ID_STRING;
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_SUB_PROCESS;
27
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_SUB_PROCESS_DEFINE_CODE;
K
Kirs 已提交
28
import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_SUB_PROCESS_PARENT_INSTANCE_ID;
29
import static org.apache.dolphinscheduler.common.Constants.LOCAL_PARAMS;
30

Q
qiaozhanwei 已提交
31
import org.apache.dolphinscheduler.common.Constants;
32 33
import org.apache.dolphinscheduler.common.enums.AuthorizationType;
import org.apache.dolphinscheduler.common.enums.CommandType;
34
import org.apache.dolphinscheduler.common.enums.Direct;
35 36 37
import org.apache.dolphinscheduler.common.enums.ExecutionStatus;
import org.apache.dolphinscheduler.common.enums.FailureStrategy;
import org.apache.dolphinscheduler.common.enums.Flag;
38
import org.apache.dolphinscheduler.common.enums.ReleaseState;
39
import org.apache.dolphinscheduler.common.enums.TaskDependType;
40
import org.apache.dolphinscheduler.common.enums.TimeoutFlag;
41
import org.apache.dolphinscheduler.common.enums.WarningType;
42
import org.apache.dolphinscheduler.common.graph.DAG;
Q
qiaozhanwei 已提交
43 44
import org.apache.dolphinscheduler.common.model.DateInterval;
import org.apache.dolphinscheduler.common.model.TaskNode;
45 46
import org.apache.dolphinscheduler.common.model.TaskNodeRelation;
import org.apache.dolphinscheduler.common.process.ProcessDag;
Q
qiaozhanwei 已提交
47
import org.apache.dolphinscheduler.common.process.Property;
48 49
import org.apache.dolphinscheduler.common.process.ResourceInfo;
import org.apache.dolphinscheduler.common.task.AbstractParameters;
50
import org.apache.dolphinscheduler.common.task.TaskTimeoutParameter;
Q
qiaozhanwei 已提交
51
import org.apache.dolphinscheduler.common.task.subprocess.SubProcessParameters;
52 53
import org.apache.dolphinscheduler.common.utils.CodeGenerateUtils;
import org.apache.dolphinscheduler.common.utils.CodeGenerateUtils.CodeGenerateException;
54 55 56
import org.apache.dolphinscheduler.common.utils.DateUtils;
import org.apache.dolphinscheduler.common.utils.JSONUtils;
import org.apache.dolphinscheduler.common.utils.ParameterUtils;
57
import org.apache.dolphinscheduler.common.utils.TaskParametersUtils;
58
import org.apache.dolphinscheduler.dao.entity.Command;
59
import org.apache.dolphinscheduler.dao.entity.DagData;
60
import org.apache.dolphinscheduler.dao.entity.DataSource;
61
import org.apache.dolphinscheduler.dao.entity.Environment;
62 63
import org.apache.dolphinscheduler.dao.entity.ErrorCommand;
import org.apache.dolphinscheduler.dao.entity.ProcessDefinition;
64
import org.apache.dolphinscheduler.dao.entity.ProcessDefinitionLog;
65 66
import org.apache.dolphinscheduler.dao.entity.ProcessInstance;
import org.apache.dolphinscheduler.dao.entity.ProcessInstanceMap;
67 68
import org.apache.dolphinscheduler.dao.entity.ProcessTaskRelation;
import org.apache.dolphinscheduler.dao.entity.ProcessTaskRelationLog;
69
import org.apache.dolphinscheduler.dao.entity.Project;
K
Kirs 已提交
70
import org.apache.dolphinscheduler.dao.entity.ProjectUser;
71 72
import org.apache.dolphinscheduler.dao.entity.Resource;
import org.apache.dolphinscheduler.dao.entity.Schedule;
73 74
import org.apache.dolphinscheduler.dao.entity.TaskDefinition;
import org.apache.dolphinscheduler.dao.entity.TaskDefinitionLog;
75 76 77 78 79 80
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import org.apache.dolphinscheduler.dao.entity.Tenant;
import org.apache.dolphinscheduler.dao.entity.UdfFunc;
import org.apache.dolphinscheduler.dao.entity.User;
import org.apache.dolphinscheduler.dao.mapper.CommandMapper;
import org.apache.dolphinscheduler.dao.mapper.DataSourceMapper;
81
import org.apache.dolphinscheduler.dao.mapper.EnvironmentMapper;
82
import org.apache.dolphinscheduler.dao.mapper.ErrorCommandMapper;
83
import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionLogMapper;
84 85 86
import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper;
import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapMapper;
import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper;
87 88
import org.apache.dolphinscheduler.dao.mapper.ProcessTaskRelationLogMapper;
import org.apache.dolphinscheduler.dao.mapper.ProcessTaskRelationMapper;
89 90
import org.apache.dolphinscheduler.dao.mapper.ProjectMapper;
import org.apache.dolphinscheduler.dao.mapper.ResourceMapper;
91
import org.apache.dolphinscheduler.dao.mapper.ResourceUserMapper;
92
import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper;
93 94
import org.apache.dolphinscheduler.dao.mapper.TaskDefinitionLogMapper;
import org.apache.dolphinscheduler.dao.mapper.TaskDefinitionMapper;
95 96 97 98
import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper;
import org.apache.dolphinscheduler.dao.mapper.TenantMapper;
import org.apache.dolphinscheduler.dao.mapper.UdfFuncMapper;
import org.apache.dolphinscheduler.dao.mapper.UserMapper;
99
import org.apache.dolphinscheduler.dao.utils.DagHelper;
100 101
import org.apache.dolphinscheduler.remote.command.StateEventChangeCommand;
import org.apache.dolphinscheduler.remote.processor.StateEventCallbackService;
102
import org.apache.dolphinscheduler.remote.utils.Host;
103
import org.apache.dolphinscheduler.service.exceptions.ServiceException;
104
import org.apache.dolphinscheduler.service.log.LogClientService;
105
import org.apache.dolphinscheduler.service.quartz.cron.CronUtils;
106
import org.apache.dolphinscheduler.spi.enums.ResourceType;
107

K
kezhenxu94 已提交
108
import org.apache.commons.collections.CollectionUtils;
109 110
import org.apache.commons.lang.StringUtils;

111 112 113
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
114
import java.util.EnumMap;
115 116 117 118
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
119
import java.util.Map.Entry;
120 121 122 123
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

L
ligang 已提交
124 125 126 127 128
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
129

130
import com.facebook.presto.jdbc.internal.guava.collect.Lists;
131
import com.fasterxml.jackson.core.type.TypeReference;
132
import com.fasterxml.jackson.databind.node.ObjectNode;
L
ligang 已提交
133 134 135 136 137

/**
 * process relative dao that some mappers in this.
 */
@Component
138
public class ProcessService {
L
ligang 已提交
139 140 141

    private final Logger logger = LoggerFactory.getLogger(getClass());

142
    private final int[] stateArray = new int[]{ExecutionStatus.SUBMITTED_SUCCESS.ordinal(),
143 144 145 146
            ExecutionStatus.RUNNING_EXECUTION.ordinal(),
            ExecutionStatus.DELAY_EXECUTION.ordinal(),
            ExecutionStatus.READY_PAUSE.ordinal(),
            ExecutionStatus.READY_STOP.ordinal()};
L
ligang 已提交
147 148

    @Autowired
149
    private UserMapper userMapper;
L
ligang 已提交
150 151 152 153

    @Autowired
    private ProcessDefinitionMapper processDefineMapper;

154 155 156
    @Autowired
    private ProcessDefinitionLogMapper processDefineLogMapper;

L
ligang 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    @Autowired
    private ProcessInstanceMapper processInstanceMapper;

    @Autowired
    private DataSourceMapper dataSourceMapper;

    @Autowired
    private ProcessInstanceMapMapper processInstanceMapMapper;

    @Autowired
    private TaskInstanceMapper taskInstanceMapper;

    @Autowired
    private CommandMapper commandMapper;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private UdfFuncMapper udfFuncMapper;

    @Autowired
    private ResourceMapper resourceMapper;

181 182 183
    @Autowired
    private ResourceUserMapper resourceUserMapper;

B
baoliang 已提交
184 185 186
    @Autowired
    private ErrorCommandMapper errorCommandMapper;

187
    @Autowired
188
    private TenantMapper tenantMapper;
189

190
    @Autowired
191
    private ProjectMapper projectMapper;
192

193 194 195 196 197 198 199
    @Autowired
    private TaskDefinitionMapper taskDefinitionMapper;

    @Autowired
    private TaskDefinitionLogMapper taskDefinitionLogMapper;

    @Autowired
200 201 202 203
    private ProcessTaskRelationMapper processTaskRelationMapper;

    @Autowired
    private ProcessTaskRelationLogMapper processTaskRelationLogMapper;
204

205 206 207 208

    @Autowired
    StateEventCallbackService stateEventCallbackService;

209 210 211
    @Autowired
    private EnvironmentMapper environmentMapper;

212
    /**
213
     * handle Command (construct ProcessInstance from Command) , wrapped in transaction
214
     *
215 216 217
     * @param logger logger
     * @param host host
     * @param command found command
218
     * @return process instance
219
     */
220
    @Transactional
221 222
    public ProcessInstance handleCommand(Logger logger, String host, Command command, HashMap<String, ProcessDefinition> processDefinitionCacheMaps) {
        ProcessInstance processInstance = constructProcessInstance(command, host, processDefinitionCacheMaps);
223
        // cannot construct process instance, return null
224
        if (processInstance == null) {
Q
qiaozhanwei 已提交
225
            logger.error("scan command, command parameter is error: {}", command);
226
            moveToErrorCommand(command, "process instance is null");
L
ligang 已提交
227 228
            return null;
        }
229 230
        processInstance.setCommandType(command.getCommandType());
        processInstance.addHistoryCmd(command.getCommandType());
231 232 233
        //if the processDefination is serial
        ProcessDefinition processDefinition = this.findProcessDefinition(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion());
        if (processDefinition.getExecutionType().typeIsSerial()) {
234
            saveSerialProcess(processInstance, processDefinition);
235
            if (processInstance.getState() != ExecutionStatus.SUBMITTED_SUCCESS) {
236 237
                setSubProcessParam(processInstance);
                deleteCommandWithCheck(command.getId());
238 239 240 241 242
                return null;
            }
        } else {
            saveProcessInstance(processInstance);
        }
243 244
        setSubProcessParam(processInstance);
        deleteCommandWithCheck(command.getId());
245
        return processInstance;
B
baoliang 已提交
246 247
    }

248
    private void saveSerialProcess(ProcessInstance processInstance, ProcessDefinition processDefinition) {
249 250 251 252 253 254 255
        processInstance.setState(ExecutionStatus.SERIAL_WAIT);
        saveProcessInstance(processInstance);
        //serial wait
        //when we get the running instance(or waiting instance) only get the priority instance(by id)
        if (processDefinition.getExecutionType().typeIsSerialWait()) {
            while (true) {
                List<ProcessInstance> runningProcessInstances = this.processInstanceMapper.queryByProcessDefineCodeAndStatusAndNextId(processInstance.getProcessDefinitionCode(),
256
                        Constants.RUNNING_PROCESS_STATE, processInstance.getId());
257 258 259 260 261 262 263 264 265 266 267 268
                if (CollectionUtils.isEmpty(runningProcessInstances)) {
                    processInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS);
                    saveProcessInstance(processInstance);
                    return;
                }
                ProcessInstance runningProcess = runningProcessInstances.get(0);
                if (this.processInstanceMapper.updateNextProcessIdById(processInstance.getId(), runningProcess.getId())) {
                    return;
                }
            }
        } else if (processDefinition.getExecutionType().typeIsSerialDiscard()) {
            List<ProcessInstance> runningProcessInstances = this.processInstanceMapper.queryByProcessDefineCodeAndStatusAndNextId(processInstance.getProcessDefinitionCode(),
269
                    Constants.RUNNING_PROCESS_STATE, processInstance.getId());
270 271 272 273 274 275
            if (CollectionUtils.isEmpty(runningProcessInstances)) {
                processInstance.setState(ExecutionStatus.STOP);
                saveProcessInstance(processInstance);
            }
        } else if (processDefinition.getExecutionType().typeIsSerialPriority()) {
            List<ProcessInstance> runningProcessInstances = this.processInstanceMapper.queryByProcessDefineCodeAndStatusAndNextId(processInstance.getProcessDefinitionCode(),
276
                    Constants.RUNNING_PROCESS_STATE, processInstance.getId());
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
            if (CollectionUtils.isNotEmpty(runningProcessInstances)) {
                for (ProcessInstance info : runningProcessInstances) {
                    info.setCommandType(CommandType.STOP);
                    info.addHistoryCmd(CommandType.STOP);
                    info.setState(ExecutionStatus.READY_STOP);
                    int update = updateProcessInstance(info);
                    // determine whether the process is normal
                    if (update > 0) {
                        String host = info.getHost();
                        String address = host.split(":")[0];
                        int port = Integer.parseInt(host.split(":")[1]);
                        StateEventChangeCommand stateEventChangeCommand = new StateEventChangeCommand(
                                info.getId(), 0, info.getState(), info.getId(), 0
                        );
                        try {
                            stateEventCallbackService.sendResult(address, port, stateEventChangeCommand.convert2Command());
                        } catch (Exception e) {
                            logger.error("sendResultError");
                        }
                    }
                }
            }
        }
    }

302
    /**
303
     * save error command, and delete original command
304
     *
305 306 307
     * @param command command
     * @param message message
     */
308
    public void moveToErrorCommand(Command command, String message) {
B
baoliang 已提交
309 310
        ErrorCommand errorCommand = new ErrorCommand(command, message);
        this.errorCommandMapper.insert(errorCommand);
311
        this.commandMapper.deleteById(command.getId());
B
baoliang 已提交
312 313
    }

B
baoliang 已提交
314 315
    /**
     * set process waiting thread
316
     *
317
     * @param command command
318 319
     * @param processInstance processInstance
     * @return process instance
B
baoliang 已提交
320 321
     */
    private ProcessInstance setWaitingThreadProcess(Command command, ProcessInstance processInstance) {
322 323
        processInstance.setState(ExecutionStatus.WAITING_THREAD);
        if (command.getCommandType() != CommandType.RECOVER_WAITING_THREAD) {
B
baoliang 已提交
324 325 326 327 328 329 330 331
            processInstance.addHistoryCmd(command.getCommandType());
        }
        saveProcessInstance(processInstance);
        this.setSubProcessParam(processInstance);
        createRecoveryWaitingThreadCommand(command, processInstance);
        return null;
    }

L
ligang 已提交
332 333
    /**
     * insert one command
334
     *
335 336
     * @param command command
     * @return create result
L
ligang 已提交
337 338 339
     */
    public int createCommand(Command command) {
        int result = 0;
340
        if (command != null) {
L
ligang 已提交
341 342 343 344 345
            result = commandMapper.insert(command);
        }
        return result;
    }

346 347 348 349
    /**
     * get command page
     */
    public List<Command> findCommandPage(int pageSize, int pageNumber) {
350
        return commandMapper.queryCommandPage(pageSize, pageNumber * pageSize);
351 352
    }

L
ligang 已提交
353 354
    /**
     * check the input command exists in queue list
355
     *
356 357
     * @param command command
     * @return create command result
L
ligang 已提交
358
     */
359 360
    public boolean verifyIsNeedCreateCommand(Command command) {
        boolean isNeedCreate = true;
361
        EnumMap<CommandType, Integer> cmdTypeMap = new EnumMap<>(CommandType.class);
362 363 364
        cmdTypeMap.put(CommandType.REPEAT_RUNNING, 1);
        cmdTypeMap.put(CommandType.RECOVER_SUSPENDED_PROCESS, 1);
        cmdTypeMap.put(CommandType.START_FAILURE_TASK_PROCESS, 1);
L
ligang 已提交
365 366
        CommandType commandType = command.getCommandType();

367
        if (cmdTypeMap.containsKey(commandType)) {
S
simon 已提交
368
            ObjectNode cmdParamObj = JSONUtils.parseObject(command.getCommandParam());
K
Kirs 已提交
369
            int processInstanceId = cmdParamObj.path(CMD_PARAM_RECOVER_PROCESS_ID_STRING).asInt();
L
ligang 已提交
370

371
            List<Command> commands = commandMapper.selectList(null);
Q
qiaozhanwei 已提交
372
            // for all commands
373 374
            for (Command tmpCommand : commands) {
                if (cmdTypeMap.containsKey(tmpCommand.getCommandType())) {
375
                    ObjectNode tempObj = JSONUtils.parseObject(tmpCommand.getCommandParam());
K
Kirs 已提交
376
                    if (tempObj != null && processInstanceId == tempObj.path(CMD_PARAM_RECOVER_PROCESS_ID_STRING).asInt()) {
L
ligang 已提交
377 378 379 380 381 382
                        isNeedCreate = false;
                        break;
                    }
                }
            }
        }
383
        return isNeedCreate;
L
ligang 已提交
384 385 386 387
    }

    /**
     * find process instance detail by id
388
     *
389 390
     * @param processId processId
     * @return process instance
L
ligang 已提交
391
     */
392
    public ProcessInstance findProcessInstanceDetailById(int processId) {
L
ligang 已提交
393 394 395
        return processInstanceMapper.queryDetailById(processId);
    }

_和's avatar
_和 已提交
396 397 398
    /**
     * get task node list by definitionId
     */
399 400
    public List<TaskDefinition> getTaskNodeListByDefinition(long defineCode) {
        ProcessDefinition processDefinition = processDefineMapper.queryByCode(defineCode);
_和's avatar
_和 已提交
401
        if (processDefinition == null) {
402
            logger.error("process define not exists");
403
            return new ArrayList<>();
_和's avatar
_和 已提交
404
        }
405 406 407 408
        List<ProcessTaskRelationLog> processTaskRelations = processTaskRelationLogMapper.queryByProcessCodeAndVersion(processDefinition.getCode(), processDefinition.getVersion());
        Set<TaskDefinition> taskDefinitionSet = new HashSet<>();
        for (ProcessTaskRelationLog processTaskRelation : processTaskRelations) {
            if (processTaskRelation.getPostTaskCode() > 0) {
409
                taskDefinitionSet.add(new TaskDefinition(processTaskRelation.getPostTaskCode(), processTaskRelation.getPostTaskVersion()));
410 411
            }
        }
412 413
        List<TaskDefinitionLog> taskDefinitionLogs = taskDefinitionLogMapper.queryByTaskDefinitions(taskDefinitionSet);
        return new ArrayList<>(taskDefinitionLogs);
_和's avatar
_和 已提交
414 415
    }

L
ligang 已提交
416 417
    /**
     * find process instance by id
418
     *
419 420
     * @param processId processId
     * @return process instance
L
ligang 已提交
421
     */
422
    public ProcessInstance findProcessInstanceById(int processId) {
B
bao liang 已提交
423
        return processInstanceMapper.selectById(processId);
L
ligang 已提交
424 425 426 427
    }

    /**
     * find process define by id.
428
     *
429 430
     * @param processDefinitionId processDefinitionId
     * @return process definition
L
ligang 已提交
431 432
     */
    public ProcessDefinition findProcessDefineById(int processDefinitionId) {
B
bao liang 已提交
433
        return processDefineMapper.selectById(processDefinitionId);
L
ligang 已提交
434 435
    }

436
    /**
437
     * find process define by code and version.
438 439 440 441 442 443
     *
     * @param processDefinitionCode processDefinitionCode
     * @return process definition
     */
    public ProcessDefinition findProcessDefinition(Long processDefinitionCode, int version) {
        ProcessDefinition processDefinition = processDefineMapper.queryByCode(processDefinitionCode);
444
        if (processDefinition == null || processDefinition.getVersion() != version) {
L
lenboo 已提交
445
            processDefinition = processDefineLogMapper.queryByDefinitionCodeAndVersion(processDefinitionCode, version);
446 447 448
            if (processDefinition != null) {
                processDefinition.setId(0);
            }
449 450 451 452
        }
        return processDefinition;
    }

453 454 455 456 457 458 459 460 461 462
    /**
     * find process define by code.
     *
     * @param processDefinitionCode processDefinitionCode
     * @return process definition
     */
    public ProcessDefinition findProcessDefinitionByCode(Long processDefinitionCode) {
        return processDefineMapper.queryByCode(processDefinitionCode);
    }

L
ligang 已提交
463 464
    /**
     * delete work process instance by id
465
     *
466 467
     * @param processInstanceId processInstanceId
     * @return delete process instance result
L
ligang 已提交
468
     */
469
    public int deleteWorkProcessInstanceById(int processInstanceId) {
B
bao liang 已提交
470
        return processInstanceMapper.deleteById(processInstanceId);
L
ligang 已提交
471 472 473 474
    }

    /**
     * delete all sub process by parent instance id
475
     *
476 477
     * @param processInstanceId processInstanceId
     * @return delete all sub process instance result
L
ligang 已提交
478
     */
479
    public int deleteAllSubWorkProcessByParentId(int processInstanceId) {
L
ligang 已提交
480

B
bao liang 已提交
481
        List<Integer> subProcessIdList = processInstanceMapMapper.querySubIdListByParentId(processInstanceId);
L
ligang 已提交
482

483
        for (Integer subId : subProcessIdList) {
L
ligang 已提交
484 485
            deleteAllSubWorkProcessByParentId(subId);
            deleteWorkProcessMapByParentId(subId);
486
            removeTaskLogFile(subId);
L
ligang 已提交
487 488 489 490 491
            deleteWorkProcessInstanceById(subId);
        }
        return 1;
    }

492 493
    /**
     * remove task log file
494
     *
495 496
     * @param processInstanceId processInstanceId
     */
497
    public void removeTaskLogFile(Integer processInstanceId) {
498 499 500 501 502
        List<TaskInstance> taskInstanceList = findValidTaskListByProcessId(processInstanceId);
        if (CollectionUtils.isEmpty(taskInstanceList)) {
            return;
        }
        try (LogClientService logClient = new LogClientService()) {
K
Kirs 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
            for (TaskInstance taskInstance : taskInstanceList) {
                String taskLogPath = taskInstance.getLogPath();
                if (StringUtils.isEmpty(taskInstance.getHost())) {
                    continue;
                }
                int port = Constants.RPC_PORT;
                String ip = "";
                try {
                    ip = Host.of(taskInstance.getHost()).getIp();
                } catch (Exception e) {
                    // compatible old version
                    ip = taskInstance.getHost();
                }
                // remove task log from loggerserver
                logClient.removeTaskLog(ip, port, taskLogPath);
518 519 520 521
            }
        }
    }

L
ligang 已提交
522 523
    /**
     * recursive query sub process definition id by parent id.
524
     *
525
     * @param parentCode parentCode
526
     * @param ids ids
L
ligang 已提交
527
     */
528 529
    public void recurseFindSubProcess(long parentCode, List<Long> ids) {
        List<TaskDefinition> taskNodeList = this.getTaskNodeListByDefinition(parentCode);
L
lenboo 已提交
530

531
        if (taskNodeList != null && !taskNodeList.isEmpty()) {
L
ligang 已提交
532

L
lenboo 已提交
533 534
            for (TaskDefinition taskNode : taskNodeList) {
                String parameter = taskNode.getTaskParams();
L
lenboo 已提交
535
                ObjectNode parameterJson = JSONUtils.parseObject(parameter);
536
                if (parameterJson.get(CMD_PARAM_SUB_PROCESS_DEFINE_CODE) != null) {
张世鸣 已提交
537
                    SubProcessParameters subProcessParam = JSONUtils.parseObject(parameter, SubProcessParameters.class);
538 539
                    ids.add(subProcessParam.getProcessDefinitionCode());
                    recurseFindSubProcess(subProcessParam.getProcessDefinitionCode(), ids);
L
ligang 已提交
540 541 542 543 544 545 546 547 548 549
                }
            }
        }
    }

    /**
     * create recovery waiting thread command when thread pool is not enough for the process instance.
     * sub work process instance need not to create recovery command.
     * create recovery waiting thread  command and delete origin command at the same time.
     * if the recovery command is exists, only update the field update_time
550
     *
551
     * @param originCommand originCommand
552
     * @param processInstance processInstance
L
ligang 已提交
553 554 555 556
     */
    public void createRecoveryWaitingThreadCommand(Command originCommand, ProcessInstance processInstance) {

        // sub process doesnot need to create wait command
557 558
        if (processInstance.getIsSubProcess() == Flag.YES) {
            if (originCommand != null) {
B
bao liang 已提交
559
                commandMapper.deleteById(originCommand.getId());
L
ligang 已提交
560 561 562 563
            }
            return;
        }
        Map<String, String> cmdParam = new HashMap<>();
K
Kirs 已提交
564
        cmdParam.put(Constants.CMD_PARAM_RECOVERY_WAITING_THREAD, String.valueOf(processInstance.getId()));
L
ligang 已提交
565
        // process instance quit by "waiting thread" state
566
        if (originCommand == null) {
L
ligang 已提交
567
            Command command = new Command(
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
                    CommandType.RECOVER_WAITING_THREAD,
                    processInstance.getTaskDependType(),
                    processInstance.getFailureStrategy(),
                    processInstance.getExecutorId(),
                    processInstance.getProcessDefinition().getCode(),
                    JSONUtils.toJsonString(cmdParam),
                    processInstance.getWarningType(),
                    processInstance.getWarningGroupId(),
                    processInstance.getScheduleTime(),
                    processInstance.getWorkerGroup(),
                    processInstance.getEnvironmentCode(),
                    processInstance.getProcessInstancePriority(),
                    processInstance.getDryRun(),
                    processInstance.getId(),
                    processInstance.getProcessDefinitionVersion()
L
ligang 已提交
583 584
            );
            saveCommand(command);
585
            return;
L
ligang 已提交
586 587 588
        }

        // update the command time if current command if recover from waiting
589
        if (originCommand.getCommandType() == CommandType.RECOVER_WAITING_THREAD) {
L
ligang 已提交
590 591
            originCommand.setUpdateTime(new Date());
            saveCommand(originCommand);
592
        } else {
L
ligang 已提交
593
            // delete old command and create new waiting thread command
B
bao liang 已提交
594
            commandMapper.deleteById(originCommand.getId());
L
ligang 已提交
595
            originCommand.setId(0);
596
            originCommand.setCommandType(CommandType.RECOVER_WAITING_THREAD);
L
ligang 已提交
597
            originCommand.setUpdateTime(new Date());
张世鸣 已提交
598
            originCommand.setCommandParam(JSONUtils.toJsonString(cmdParam));
L
ligang 已提交
599 600 601 602 603 604 605
            originCommand.setProcessInstancePriority(processInstance.getProcessInstancePriority());
            saveCommand(originCommand);
        }
    }

    /**
     * get schedule time from command
606
     *
607
     * @param command command
608 609
     * @param cmdParam cmdParam map
     * @return date
L
ligang 已提交
610
     */
611
    private Date getScheduleTime(Command command, Map<String, String> cmdParam) {
L
ligang 已提交
612
        Date scheduleTime = command.getScheduleTime();
613 614 615
        if (scheduleTime == null
                && cmdParam != null
                && cmdParam.containsKey(CMDPARAM_COMPLEMENT_DATA_START_DATE)) {
616 617 618 619 620 621

            Date start = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE));
            Date end = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_END_DATE));
            List<Schedule> schedules = queryReleaseSchedulerListByProcessDefinitionCode(command.getProcessDefinitionCode());
            List<Date> complementDateList = CronUtils.getSelfFireDateList(start, end, schedules);

622 623 624 625 626 627
            if (complementDateList.size() > 0) {
                scheduleTime = complementDateList.get(0);
            } else {
                logger.error("set scheduler time error: complement date list is empty, command: {}",
                        command.toString());
            }
L
ligang 已提交
628 629 630 631 632 633
        }
        return scheduleTime;
    }

    /**
     * generate a new work process instance from command.
634
     *
635
     * @param processDefinition processDefinition
636 637
     * @param command command
     * @param cmdParam cmdParam map
638
     * @return process instance
L
ligang 已提交
639 640 641
     */
    private ProcessInstance generateNewProcessInstance(ProcessDefinition processDefinition,
                                                       Command command,
642
                                                       Map<String, String> cmdParam) {
L
ligang 已提交
643
        ProcessInstance processInstance = new ProcessInstance(processDefinition);
644 645
        processInstance.setProcessDefinitionCode(processDefinition.getCode());
        processInstance.setProcessDefinitionVersion(processDefinition.getVersion());
_和's avatar
_和 已提交
646
        processInstance.setState(ExecutionStatus.RUNNING_EXECUTION);
L
ligang 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660
        processInstance.setRecovery(Flag.NO);
        processInstance.setStartTime(new Date());
        processInstance.setRunTimes(1);
        processInstance.setMaxTryTimes(0);
        processInstance.setCommandParam(command.getCommandParam());
        processInstance.setCommandType(command.getCommandType());
        processInstance.setIsSubProcess(Flag.NO);
        processInstance.setTaskDependType(command.getTaskDependType());
        processInstance.setFailureStrategy(command.getFailureStrategy());
        processInstance.setExecutorId(command.getExecutorId());
        WarningType warningType = command.getWarningType() == null ? WarningType.NONE : command.getWarningType();
        processInstance.setWarningType(warningType);
        Integer warningGroupId = command.getWarningGroupId() == null ? 0 : command.getWarningGroupId();
        processInstance.setWarningGroupId(warningGroupId);
661
        processInstance.setDryRun(command.getDryRun());
L
ligang 已提交
662

663 664
        if (command.getScheduleTime() != null) {
            processInstance.setScheduleTime(command.getScheduleTime());
L
ligang 已提交
665 666 667
        }
        processInstance.setCommandStartTime(command.getStartTime());
        processInstance.setLocations(processDefinition.getLocations());
K
Kirs 已提交
668

669
        // reset global params while there are start parameters
670
        setGlobalParamIfCommanded(processDefinition, cmdParam);
K
Kirs 已提交
671

L
ligang 已提交
672 673
        // curing global params
        processInstance.setGlobalParams(ParameterUtils.curingGlobalParams(
674 675 676 677
                processDefinition.getGlobalParamMap(),
                processDefinition.getGlobalParamList(),
                getCommandTypeIfComplement(processInstance, command),
                processInstance.getScheduleTime()));
L
ligang 已提交
678 679 680

        // set process instance priority
        processInstance.setProcessInstancePriority(command.getProcessInstancePriority());
L
lgcareer 已提交
681 682
        String workerGroup = StringUtils.isBlank(command.getWorkerGroup()) ? Constants.DEFAULT_WORKER_GROUP : command.getWorkerGroup();
        processInstance.setWorkerGroup(workerGroup);
683
        processInstance.setEnvironmentCode(Objects.isNull(command.getEnvironmentCode()) ? -1 : command.getEnvironmentCode());
B
baoliang 已提交
684
        processInstance.setTimeout(processDefinition.getTimeout());
685
        processInstance.setTenantId(processDefinition.getTenantId());
L
ligang 已提交
686 687 688
        return processInstance;
    }

689
    private void setGlobalParamIfCommanded(ProcessDefinition processDefinition, Map<String, String> cmdParam) {
K
Kirs 已提交
690
        // get start params from command param
691
        Map<String, String> startParamMap = new HashMap<>();
K
Kirs 已提交
692 693 694 695
        if (cmdParam != null && cmdParam.containsKey(Constants.CMD_PARAM_START_PARAMS)) {
            String startParamJson = cmdParam.get(Constants.CMD_PARAM_START_PARAMS);
            startParamMap = JSONUtils.toMap(startParamJson);
        }
696 697 698 699 700 701
        Map<String, String> fatherParamMap = new HashMap<>();
        if (cmdParam != null && cmdParam.containsKey(Constants.CMD_PARAM_FATHER_PARAMS)) {
            String fatherParamJson = cmdParam.get(Constants.CMD_PARAM_FATHER_PARAMS);
            fatherParamMap = JSONUtils.toMap(fatherParamJson);
        }
        startParamMap.putAll(fatherParamMap);
K
Kirs 已提交
702
        // set start param into global params
703
        if (startParamMap.size() > 0
704
                && processDefinition.getGlobalParamMap() != null) {
K
Kirs 已提交
705 706 707 708 709 710 711
            for (Map.Entry<String, String> param : processDefinition.getGlobalParamMap().entrySet()) {
                String val = startParamMap.get(param.getKey());
                if (val != null) {
                    param.setValue(val);
                }
            }
        }
L
ligang 已提交
712 713
    }

714 715 716 717 718
    /**
     * get process tenant
     * there is tenant id in definition, use the tenant of the definition.
     * if there is not tenant id in the definiton or the tenant not exist
     * use definition creator's tenant.
719
     *
720
     * @param tenantId tenantId
721
     * @param userId userId
722
     * @return tenant
723
     */
724
    public Tenant getTenantForProcess(int tenantId, int userId) {
725
        Tenant tenant = null;
726
        if (tenantId >= 0) {
727 728
            tenant = tenantMapper.queryById(tenantId);
        }
729

730
        if (userId == 0) {
731 732 733
            return null;
        }

734
        if (tenant == null) {
B
bao liang 已提交
735
            User user = userMapper.selectById(userId);
736
            tenant = tenantMapper.queryById(user.getTenantId());
737 738 739
        }
        return tenant;
    }
L
ligang 已提交
740

741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
    /**
     * get an environment
     * use the code of the environment to find a environment.
     *
     * @param environmentCode environmentCode
     * @return Environment
     */
    public Environment findEnvironmentByCode(Long environmentCode) {
        Environment environment = null;
        if (environmentCode >= 0) {
            environment = environmentMapper.queryByEnvironmentCode(environmentCode);
        }
        return environment;
    }

L
ligang 已提交
756 757
    /**
     * check command parameters is valid
758
     *
759
     * @param command command
760 761
     * @param cmdParam cmdParam map
     * @return whether command param is valid
L
ligang 已提交
762
     */
763 764 765
    private Boolean checkCmdParam(Command command, Map<String, String> cmdParam) {
        if (command.getTaskDependType() == TaskDependType.TASK_ONLY || command.getTaskDependType() == TaskDependType.TASK_PRE) {
            if (cmdParam == null
766 767
                    || !cmdParam.containsKey(Constants.CMD_PARAM_START_NODES)
                    || cmdParam.get(Constants.CMD_PARAM_START_NODES).isEmpty()) {
768
                logger.error("command node depend type is {}, but start nodes is null ", command.getTaskDependType());
L
ligang 已提交
769 770 771 772 773 774 775 776
                return false;
            }
        }
        return true;
    }

    /**
     * construct process instance according to one command.
777
     *
778 779
     * @param command command
     * @param host host
780
     * @return process instance
L
ligang 已提交
781
     */
782
    private ProcessInstance constructProcessInstance(Command command, String host, HashMap<String, ProcessDefinition> processDefinitionCacheMaps) {
783
        ProcessInstance processInstance;
784
        ProcessDefinition processDefinition;
L
ligang 已提交
785
        CommandType commandType = command.getCommandType();
786 787 788 789 790 791 792 793 794
        String key = String.format("%d-%d", command.getProcessDefinitionCode(), command.getProcessDefinitionVersion());
        if (processDefinitionCacheMaps.containsKey(key)) {
            processDefinition = processDefinitionCacheMaps.get(key);
        } else {
            processDefinition = this.findProcessDefinition(command.getProcessDefinitionCode(), command.getProcessDefinitionVersion());
            if (processDefinition != null) {
                processDefinitionCacheMaps.put(key, processDefinition);
            }
        }
795 796 797
        if (processDefinition == null) {
            logger.error("cannot find the work process define! define code : {}", command.getProcessDefinitionCode());
            return null;
L
ligang 已提交
798
        }
799 800 801 802 803 804 805 806 807 808
        Map<String, String> cmdParam = JSONUtils.toMap(command.getCommandParam());
        int processInstanceId = command.getProcessInstanceId();
        if (processInstanceId == 0) {
            processInstance = generateNewProcessInstance(processDefinition, command, cmdParam);
        } else {
            processInstance = this.findProcessInstanceDetailById(processInstanceId);
            if (processInstance == null) {
                return processInstance;
            }
        }
809
        if (cmdParam != null) {
810 811 812 813
            CommandType commandTypeIfComplement = getCommandTypeIfComplement(processInstance, command);
            // reset global params while repeat running is needed by cmdParam
            if (commandTypeIfComplement == CommandType.REPEAT_RUNNING) {
                setGlobalParamIfCommanded(processDefinition, cmdParam);
L
ligang 已提交
814
            }
815

816 817
            // Recalculate global parameters after rerun.
            processInstance.setGlobalParams(ParameterUtils.curingGlobalParams(
818 819 820 821
                    processDefinition.getGlobalParamMap(),
                    processDefinition.getGlobalParamList(),
                    commandTypeIfComplement,
                    processInstance.getScheduleTime()));
822 823 824 825 826 827 828 829
            processInstance.setProcessDefinition(processDefinition);
        }
        //reset command parameter
        if (processInstance.getCommandParam() != null) {
            Map<String, String> processCmdParam = JSONUtils.toMap(processInstance.getCommandParam());
            for (Map.Entry<String, String> entry : processCmdParam.entrySet()) {
                if (!cmdParam.containsKey(entry.getKey())) {
                    cmdParam.put(entry.getKey(), entry.getValue());
L
ligang 已提交
830 831
                }
            }
832 833
        }
        // reset command parameter if sub process
834
        if (cmdParam != null && cmdParam.containsKey(Constants.CMD_PARAM_SUB_PROCESS)) {
835
            processInstance.setCommandParam(command.getCommandParam());
L
ligang 已提交
836
        }
837
        if (Boolean.FALSE.equals(checkCmdParam(command, cmdParam))) {
L
ligang 已提交
838 839 840
            logger.error("command parameter check failed!");
            return null;
        }
841
        if (command.getScheduleTime() != null) {
L
ligang 已提交
842 843 844
            processInstance.setScheduleTime(command.getScheduleTime());
        }
        processInstance.setHost(host);
_和's avatar
_和 已提交
845
        ExecutionStatus runStatus = ExecutionStatus.RUNNING_EXECUTION;
L
ligang 已提交
846
        int runTime = processInstance.getRunTimes();
847
        switch (commandType) {
L
ligang 已提交
848 849 850 851 852
            case START_PROCESS:
                break;
            case START_FAILURE_TASK_PROCESS:
                // find failed tasks and init these tasks
                List<Integer> failedList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.FAILURE);
853
                List<Integer> toleranceList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.NEED_FAULT_TOLERANCE);
L
ligang 已提交
854
                List<Integer> killedList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.KILL);
K
Kirs 已提交
855
                cmdParam.remove(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING);
L
ligang 已提交
856 857

                failedList.addAll(killedList);
858
                failedList.addAll(toleranceList);
859
                for (Integer taskId : failedList) {
L
ligang 已提交
860 861
                    initTaskInstance(this.findTaskInstanceById(taskId));
                }
K
Kirs 已提交
862
                cmdParam.put(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING,
863
                        String.join(Constants.COMMA, convertIntListToString(failedList)));
张世鸣 已提交
864
                processInstance.setCommandParam(JSONUtils.toJsonString(cmdParam));
865
                processInstance.setRunTimes(runTime + 1);
L
ligang 已提交
866 867 868
                break;
            case START_CURRENT_TASK_PROCESS:
                break;
869
            case RECOVER_WAITING_THREAD:
L
ligang 已提交
870 871 872
                break;
            case RECOVER_SUSPENDED_PROCESS:
                // find pause tasks and init task's state
K
Kirs 已提交
873
                cmdParam.remove(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING);
L
ligang 已提交
874
                List<Integer> suspendedNodeList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.PAUSE);
leon-baoliang's avatar
leon-baoliang 已提交
875
                List<Integer> stopNodeList = findTaskIdByInstanceState(processInstance.getId(),
876
                        ExecutionStatus.KILL);
leon-baoliang's avatar
leon-baoliang 已提交
877
                suspendedNodeList.addAll(stopNodeList);
878
                for (Integer taskId : suspendedNodeList) {
Q
qiaozhanwei 已提交
879
                    // initialize the pause state
L
ligang 已提交
880 881
                    initTaskInstance(this.findTaskInstanceById(taskId));
                }
K
Kirs 已提交
882
                cmdParam.put(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING, String.join(",", convertIntListToString(suspendedNodeList)));
张世鸣 已提交
883
                processInstance.setCommandParam(JSONUtils.toJsonString(cmdParam));
884
                processInstance.setRunTimes(runTime + 1);
L
ligang 已提交
885 886 887 888
                break;
            case RECOVER_TOLERANCE_FAULT_PROCESS:
                // recover tolerance fault process
                processInstance.setRecovery(Flag.YES);
889
                runStatus = processInstance.getState();
L
ligang 已提交
890 891
                break;
            case COMPLEMENT_DATA:
892 893 894 895 896 897 898
                // delete all the valid tasks when complement data if id is not null
                if (processInstance.getId() != 0) {
                    List<TaskInstance> taskInstanceList = this.findValidTaskListByProcessId(processInstance.getId());
                    for (TaskInstance taskInstance : taskInstanceList) {
                        taskInstance.setFlag(Flag.NO);
                        this.updateTaskInstance(taskInstance);
                    }
L
ligang 已提交
899 900 901 902
                }
                break;
            case REPEAT_RUNNING:
                // delete the recover task names from command parameter
K
Kirs 已提交
903 904
                if (cmdParam.containsKey(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING)) {
                    cmdParam.remove(Constants.CMD_PARAM_RECOVERY_START_NODE_STRING);
张世鸣 已提交
905
                    processInstance.setCommandParam(JSONUtils.toJsonString(cmdParam));
L
ligang 已提交
906 907 908
                }
                // delete all the valid tasks when repeat running
                List<TaskInstance> validTaskList = findValidTaskListByProcessId(processInstance.getId());
909
                for (TaskInstance taskInstance : validTaskList) {
L
ligang 已提交
910 911 912 913
                    taskInstance.setFlag(Flag.NO);
                    updateTaskInstance(taskInstance);
                }
                processInstance.setStartTime(new Date());
914
                processInstance.setEndTime(null);
915
                processInstance.setRunTimes(runTime + 1);
L
ligang 已提交
916 917 918 919 920 921 922
                initComplementDataParam(processDefinition, processInstance, cmdParam);
                break;
            case SCHEDULER:
                break;
            default:
                break;
        }
923
        processInstance.setState(runStatus);
L
ligang 已提交
924 925 926
        return processInstance;
    }

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    /**
     * get process definition by command
     * If it is a fault-tolerant command, get the specified version of ProcessDefinition through ProcessInstance
     * Otherwise, get the latest version of ProcessDefinition
     *
     * @return ProcessDefinition
     */
    private ProcessDefinition getProcessDefinitionByCommand(long processDefinitionCode, Map<String, String> cmdParam) {
        if (cmdParam != null) {
            int processInstanceId = 0;
            if (cmdParam.containsKey(Constants.CMD_PARAM_RECOVER_PROCESS_ID_STRING)) {
                processInstanceId = Integer.parseInt(cmdParam.get(Constants.CMD_PARAM_RECOVER_PROCESS_ID_STRING));
            } else if (cmdParam.containsKey(Constants.CMD_PARAM_SUB_PROCESS)) {
                processInstanceId = Integer.parseInt(cmdParam.get(Constants.CMD_PARAM_SUB_PROCESS));
            } else if (cmdParam.containsKey(Constants.CMD_PARAM_RECOVERY_WAITING_THREAD)) {
                processInstanceId = Integer.parseInt(cmdParam.get(Constants.CMD_PARAM_RECOVERY_WAITING_THREAD));
            }

            if (processInstanceId != 0) {
                ProcessInstance processInstance = this.findProcessInstanceDetailById(processInstanceId);
                if (processInstance == null) {
                    return null;
                }

                return processDefineLogMapper.queryByDefinitionCodeAndVersion(
952
                        processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion());
953 954 955 956 957 958
            }
        }

        return processDefineMapper.queryByCode(processDefinitionCode);
    }

L
ligang 已提交
959 960
    /**
     * return complement data if the process start with complement data
961
     *
962
     * @param processInstance processInstance
963
     * @param command command
964
     * @return command type
L
ligang 已提交
965
     */
966 967
    private CommandType getCommandTypeIfComplement(ProcessInstance processInstance, Command command) {
        if (CommandType.COMPLEMENT_DATA == processInstance.getCmdTypeIfComplement()) {
L
ligang 已提交
968
            return CommandType.COMPLEMENT_DATA;
969
        } else {
L
ligang 已提交
970 971 972 973 974 975
            return command.getCommandType();
        }
    }

    /**
     * initialize complement data parameters
976
     *
977
     * @param processDefinition processDefinition
978 979
     * @param processInstance processInstance
     * @param cmdParam cmdParam
L
ligang 已提交
980
     */
981 982 983
    private void initComplementDataParam(ProcessDefinition processDefinition,
                                         ProcessInstance processInstance,
                                         Map<String, String> cmdParam) {
984
        if (!processInstance.isComplementData()) {
L
ligang 已提交
985 986 987
            return;
        }

988 989 990 991
        Date start = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE));
        Date end = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_END_DATE));
        List<Schedule> listSchedules = queryReleaseSchedulerListByProcessDefinitionCode(processInstance.getProcessDefinitionCode());
        List<Date> complementDate = CronUtils.getSelfFireDateList(start, end, listSchedules);
992 993 994 995

        if (complementDate.size() > 0
                && Flag.NO == processInstance.getIsSubProcess()) {
            processInstance.setScheduleTime(complementDate.get(0));
996
        }
L
ligang 已提交
997
        processInstance.setGlobalParams(ParameterUtils.curingGlobalParams(
998 999 1000
                processDefinition.getGlobalParamMap(),
                processDefinition.getGlobalParamList(),
                CommandType.COMPLEMENT_DATA, processInstance.getScheduleTime()));
1001 1002
    }

L
ligang 已提交
1003 1004 1005
    /**
     * set sub work process parameters.
     * handle sub work process instance, update relation table and command parameters
1006
     * set sub work process flag, extends parent work process command parameters
1007
     *
1008
     * @param subProcessInstance subProcessInstance
L
ligang 已提交
1009
     */
1010
    public void setSubProcessParam(ProcessInstance subProcessInstance) {
1011
        String cmdParam = subProcessInstance.getCommandParam();
1012
        if (StringUtils.isEmpty(cmdParam)) {
1013
            return;
L
ligang 已提交
1014 1015 1016
        }
        Map<String, String> paramMap = JSONUtils.toMap(cmdParam);
        // write sub process id into cmd param.
K
Kirs 已提交
1017
        if (paramMap.containsKey(CMD_PARAM_SUB_PROCESS)
1018
                && CMD_PARAM_EMPTY_SUB_PROCESS.equals(paramMap.get(CMD_PARAM_SUB_PROCESS))) {
K
Kirs 已提交
1019 1020
            paramMap.remove(CMD_PARAM_SUB_PROCESS);
            paramMap.put(CMD_PARAM_SUB_PROCESS, String.valueOf(subProcessInstance.getId()));
张世鸣 已提交
1021
            subProcessInstance.setCommandParam(JSONUtils.toJsonString(paramMap));
1022 1023
            subProcessInstance.setIsSubProcess(Flag.YES);
            this.saveProcessInstance(subProcessInstance);
L
ligang 已提交
1024 1025
        }
        // copy parent instance user def params to sub process..
K
Kirs 已提交
1026
        String parentInstanceId = paramMap.get(CMD_PARAM_SUB_PROCESS_PARENT_INSTANCE_ID);
1027
        if (StringUtils.isNotEmpty(parentInstanceId)) {
L
ligang 已提交
1028
            ProcessInstance parentInstance = findProcessInstanceDetailById(Integer.parseInt(parentInstanceId));
1029
            if (parentInstance != null) {
1030
                subProcessInstance.setGlobalParams(
1031
                        joinGlobalParams(parentInstance.getGlobalParams(), subProcessInstance.getGlobalParams()));
1032
                this.saveProcessInstance(subProcessInstance);
1033
            } else {
L
ligang 已提交
1034 1035 1036 1037
                logger.error("sub process command params error, cannot find parent instance: {} ", cmdParam);
            }
        }
        ProcessInstanceMap processInstanceMap = JSONUtils.parseObject(cmdParam, ProcessInstanceMap.class);
1038
        if (processInstanceMap == null || processInstanceMap.getParentProcessInstanceId() == 0) {
1039
            return;
L
ligang 已提交
1040 1041
        }
        // update sub process id to process map table
1042
        processInstanceMap.setProcessInstanceId(subProcessInstance.getId());
L
ligang 已提交
1043 1044

        this.updateWorkProcessInstanceMap(processInstanceMap);
1045 1046 1047 1048
    }

    /**
     * join parent global params into sub process.
1049
     * only the keys doesn't in sub process global would be joined.
1050
     *
1051
     * @param parentGlobalParams parentGlobalParams
1052
     * @param subGlobalParams subGlobalParams
1053
     * @return global params join
1054
     */
1055
    private String joinGlobalParams(String parentGlobalParams, String subGlobalParams) {
S
simon824 已提交
1056

B
add esc  
baoliang 已提交
1057 1058
        List<Property> parentPropertyList = JSONUtils.toList(parentGlobalParams, Property.class);
        List<Property> subPropertyList = JSONUtils.toList(subGlobalParams, Property.class);
S
simon824 已提交
1059

1060
        Map<String, String> subMap = subPropertyList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue));
1061

1062 1063
        for (Property parent : parentPropertyList) {
            if (!subMap.containsKey(parent.getProp())) {
B
add esc  
baoliang 已提交
1064
                subPropertyList.add(parent);
1065 1066
            }
        }
张世鸣 已提交
1067
        return JSONUtils.toJsonString(subPropertyList);
L
ligang 已提交
1068 1069 1070 1071
    }

    /**
     * initialize task instance
1072
     *
1073
     * @param taskInstance taskInstance
L
ligang 已提交
1074
     */
1075
    private void initTaskInstance(TaskInstance taskInstance) {
leon-baoliang's avatar
leon-baoliang 已提交
1076

1077
        if (!taskInstance.isSubProcess()
1078
                && (taskInstance.getState().typeIsCancel() || taskInstance.getState().typeIsFailure())) {
1079 1080 1081
            taskInstance.setFlag(Flag.NO);
            updateTaskInstance(taskInstance);
            return;
L
ligang 已提交
1082
        }
leon-baoliang's avatar
leon-baoliang 已提交
1083 1084
        taskInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS);
        updateTaskInstance(taskInstance);
L
ligang 已提交
1085 1086
    }

1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
    /**
     * retry submit task to db
     */
    public TaskInstance submitTask(TaskInstance taskInstance, int commitRetryTimes, int commitInterval) {

        int retryTimes = 1;
        boolean submitDB = false;
        TaskInstance task = null;
        while (retryTimes <= commitRetryTimes) {
            try {
                if (!submitDB) {
                    // submit task to db
                    task = submitTask(taskInstance);
                    if (task != null && task.getId() != 0) {
                        submitDB = true;
1102
                        break;
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
                    }
                }
                if (!submitDB) {
                    logger.error("task commit to db failed , taskId {} has already retry {} times, please check the database", taskInstance.getId(), retryTimes);
                }
                Thread.sleep(commitInterval);
            } catch (Exception e) {
                logger.error("task commit to mysql failed", e);
            }
            retryTimes += 1;
        }
        return task;
    }

L
ligang 已提交
1117
    /**
1118
     * submit task to db
1119
     * submit sub process to command
1120
     *
1121 1122
     * @param taskInstance taskInstance
     * @return task instance
L
ligang 已提交
1123
     */
K
Kirs 已提交
1124
    @Transactional(rollbackFor = Exception.class)
1125
    public TaskInstance submitTask(TaskInstance taskInstance) {
1126 1127
        ProcessInstance processInstance = this.findProcessInstanceDetailById(taskInstance.getProcessInstanceId());
        logger.info("start submit task : {}, instance id:{}, state: {}",
1128
                taskInstance.getName(), taskInstance.getProcessInstanceId(), processInstance.getState());
1129 1130
        //submit to db
        TaskInstance task = submitTaskInstanceToDB(taskInstance, processInstance);
1131
        if (task == null) {
1132
            logger.error("end submit task to db error, task name:{}, process id:{} state: {} ",
1133
                    taskInstance.getName(), taskInstance.getProcessInstance(), processInstance.getState());
1134 1135
            return task;
        }
1136
        if (!task.getState().typeIsFinished()) {
1137
            createSubWorkProcess(processInstance, task);
1138 1139
        }

1140 1141
        logger.info("end submit task to db successfully:{} {} state:{} complete, instance id:{} state: {}  ",
                taskInstance.getId(), taskInstance.getName(), task.getState(), processInstance.getId(), processInstance.getState());
L
ligang 已提交
1142 1143 1144 1145 1146
        return task;
    }

    /**
     * set work process instance map
1147 1148 1149
     * consider o
     * repeat running  does not generate new sub process instance
     * set map {parent instance id, task instance id, 0(child instance id)}
1150
     *
1151
     * @param parentInstance parentInstance
1152
     * @param parentTask parentTask
1153
     * @return process instance map
L
ligang 已提交
1154
     */
1155
    private ProcessInstanceMap setProcessInstanceMap(ProcessInstance parentInstance, TaskInstance parentTask) {
L
ligang 已提交
1156
        ProcessInstanceMap processMap = findWorkProcessMapByParent(parentInstance.getId(), parentTask.getId());
1157
        if (processMap != null) {
L
ligang 已提交
1158
            return processMap;
1159 1160
        }
        if (parentInstance.getCommandType() == CommandType.REPEAT_RUNNING) {
L
ligang 已提交
1161 1162
            // update current task id to map
            processMap = findPreviousTaskProcessMap(parentInstance, parentTask);
1163
            if (processMap != null) {
L
ligang 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
                processMap.setParentTaskInstanceId(parentTask.getId());
                updateWorkProcessInstanceMap(processMap);
                return processMap;
            }
        }
        // new task
        processMap = new ProcessInstanceMap();
        processMap.setParentProcessInstanceId(parentInstance.getId());
        processMap.setParentTaskInstanceId(parentTask.getId());
        createWorkProcessInstanceMap(processMap);
        return processMap;
    }

    /**
     * find previous task work process map.
1179
     *
1180
     * @param parentProcessInstance parentProcessInstance
1181
     * @param parentTask parentTask
1182
     * @return process instance map
L
ligang 已提交
1183 1184 1185 1186 1187 1188
     */
    private ProcessInstanceMap findPreviousTaskProcessMap(ProcessInstance parentProcessInstance,
                                                          TaskInstance parentTask) {

        Integer preTaskId = 0;
        List<TaskInstance> preTaskList = this.findPreviousTaskListByWorkProcessId(parentProcessInstance.getId());
1189 1190
        for (TaskInstance task : preTaskList) {
            if (task.getName().equals(parentTask.getName())) {
L
ligang 已提交
1191 1192
                preTaskId = task.getId();
                ProcessInstanceMap map = findWorkProcessMapByParent(parentProcessInstance.getId(), preTaskId);
1193
                if (map != null) {
L
ligang 已提交
1194 1195 1196 1197 1198
                    return map;
                }
            }
        }
        logger.info("sub process instance is not found,parent task:{},parent instance:{}",
1199
                parentTask.getId(), parentProcessInstance.getId());
L
ligang 已提交
1200 1201 1202 1203 1204
        return null;
    }

    /**
     * create sub work process command
1205
     *
1206
     * @param parentProcessInstance parentProcessInstance
1207
     * @param task task
L
ligang 已提交
1208
     */
1209 1210
    public void createSubWorkProcess(ProcessInstance parentProcessInstance, TaskInstance task) {
        if (!task.isSubProcess()) {
1211 1212
            return;
        }
1213 1214 1215 1216 1217
        //check create sub work flow firstly
        ProcessInstanceMap instanceMap = findWorkProcessMapByParent(parentProcessInstance.getId(), task.getId());
        if (null != instanceMap && CommandType.RECOVER_TOLERANCE_FAULT_PROCESS == parentProcessInstance.getCommandType()) {
            // recover failover tolerance would not create a new command when the sub command already have been created
            return;
L
ligang 已提交
1218
        }
1219 1220 1221 1222
        instanceMap = setProcessInstanceMap(parentProcessInstance, task);
        ProcessInstance childInstance = null;
        if (instanceMap.getProcessInstanceId() != 0) {
            childInstance = findProcessInstanceById(instanceMap.getProcessInstanceId());
L
ligang 已提交
1223
        }
1224
        Command subProcessCommand = createSubProcessCommand(parentProcessInstance, childInstance, instanceMap, task);
1225
        updateSubProcessDefinitionByParent(parentProcessInstance, subProcessCommand.getProcessDefinitionCode());
1226 1227 1228 1229 1230 1231 1232 1233
        initSubInstanceState(childInstance);
        createCommand(subProcessCommand);
        logger.info("sub process command created: {} ", subProcessCommand);
    }

    /**
     * complement data needs transform parent parameter to child.
     */
1234
    private String getSubWorkFlowParam(ProcessInstanceMap instanceMap, ProcessInstance parentProcessInstance, Map<String, String> fatherParams) {
L
ligang 已提交
1235
        // set sub work process command
张世鸣 已提交
1236
        String processMapStr = JSONUtils.toJsonString(instanceMap);
L
ligang 已提交
1237
        Map<String, String> cmdParam = JSONUtils.toMap(processMapStr);
1238
        if (parentProcessInstance.isComplementData()) {
L
ligang 已提交
1239
            Map<String, String> parentParam = JSONUtils.toMap(parentProcessInstance.getCommandParam());
1240 1241
            String endTime = parentParam.get(CMDPARAM_COMPLEMENT_DATA_END_DATE);
            String startTime = parentParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE);
L
ligang 已提交
1242 1243
            cmdParam.put(CMDPARAM_COMPLEMENT_DATA_END_DATE, endTime);
            cmdParam.put(CMDPARAM_COMPLEMENT_DATA_START_DATE, startTime);
张世鸣 已提交
1244
            processMapStr = JSONUtils.toJsonString(cmdParam);
L
ligang 已提交
1245
        }
1246 1247 1248 1249
        if (fatherParams.size() != 0) {
            cmdParam.put(CMD_PARAM_FATHER_PARAMS, JSONUtils.toJsonString(fatherParams));
            processMapStr = JSONUtils.toJsonString(cmdParam);
        }
1250 1251 1252
        return processMapStr;
    }

1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
    public Map<String, String> getGlobalParamMap(String globalParams) {
        List<Property> propList;
        Map<String, String> globalParamMap = new HashMap<>();
        if (StringUtils.isNotEmpty(globalParams)) {
            propList = JSONUtils.toList(globalParams, Property.class);
            globalParamMap = propList.stream().collect(Collectors.toMap(Property::getProp, Property::getValue));
        }

        return globalParamMap;
    }

1264 1265 1266 1267 1268 1269 1270 1271
    /**
     * create sub work process command
     */
    public Command createSubProcessCommand(ProcessInstance parentProcessInstance,
                                           ProcessInstance childInstance,
                                           ProcessInstanceMap instanceMap,
                                           TaskInstance task) {
        CommandType commandType = getSubCommandType(parentProcessInstance, childInstance);
1272
        Map<String, String> subProcessParam = JSONUtils.toMap(task.getTaskParams());
1273 1274 1275 1276
        long childDefineCode = 0L;
        if (subProcessParam.containsKey(Constants.CMD_PARAM_SUB_PROCESS_DEFINE_CODE)) {
            childDefineCode = Long.parseLong(subProcessParam.get(Constants.CMD_PARAM_SUB_PROCESS_DEFINE_CODE));
        }
1277
        ProcessDefinition subProcessDefinition = processDefineMapper.queryByCode(childDefineCode);
1278

1279 1280 1281
        Object localParams = subProcessParam.get(Constants.LOCAL_PARAMS);
        List<Property> allParam = JSONUtils.toList(JSONUtils.toJsonString(localParams), Property.class);
        Map<String, String> globalMap = this.getGlobalParamMap(parentProcessInstance.getGlobalParams());
1282
        Map<String, String> fatherParams = new HashMap<>();
1283 1284 1285 1286 1287
        if (CollectionUtils.isNotEmpty(allParam)) {
            for (Property info : allParam) {
                fatherParams.put(info.getProp(), globalMap.get(info.getProp()));
            }
        }
1288
        String processParam = getSubWorkFlowParam(instanceMap, parentProcessInstance, fatherParams);
1289
        int subProcessInstanceId = childInstance == null ? 0 : childInstance.getId();
1290
        return new Command(
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
                commandType,
                TaskDependType.TASK_POST,
                parentProcessInstance.getFailureStrategy(),
                parentProcessInstance.getExecutorId(),
                subProcessDefinition.getCode(),
                processParam,
                parentProcessInstance.getWarningType(),
                parentProcessInstance.getWarningGroupId(),
                parentProcessInstance.getScheduleTime(),
                task.getWorkerGroup(),
                task.getEnvironmentCode(),
                parentProcessInstance.getProcessInstancePriority(),
                parentProcessInstance.getDryRun(),
                subProcessInstanceId,
                subProcessDefinition.getVersion()
1306 1307
        );
    }
1308

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
    /**
     * initialize sub work flow state
     * child instance state would be initialized when 'recovery from pause/stop/failure'
     */
    private void initSubInstanceState(ProcessInstance childInstance) {
        if (childInstance != null) {
            childInstance.setState(ExecutionStatus.RUNNING_EXECUTION);
            updateProcessInstance(childInstance);
        }
    }
1319

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    /**
     * get sub work flow command type
     * child instance exist: child command = fatherCommand
     * child instance not exists: child command = fatherCommand[0]
     */
    private CommandType getSubCommandType(ProcessInstance parentProcessInstance, ProcessInstance childInstance) {
        CommandType commandType = parentProcessInstance.getCommandType();
        if (childInstance == null) {
            String fatherHistoryCommand = parentProcessInstance.getHistoryCmd();
            commandType = CommandType.valueOf(fatherHistoryCommand.split(Constants.COMMA)[0]);
        }
        return commandType;
L
ligang 已提交
1332 1333
    }

1334
    /**
K
Kirs 已提交
1335
     * update sub process definition
1336
     *
1337
     * @param parentProcessInstance parentProcessInstance
1338
     * @param childDefinitionCode childDefinitionId
1339
     */
1340
    private void updateSubProcessDefinitionByParent(ProcessInstance parentProcessInstance, long childDefinitionCode) {
1341
        ProcessDefinition fatherDefinition = this.findProcessDefinition(parentProcessInstance.getProcessDefinitionCode(),
1342
                parentProcessInstance.getProcessDefinitionVersion());
1343
        ProcessDefinition childDefinition = this.findProcessDefinitionByCode(childDefinitionCode);
1344 1345
        if (childDefinition != null && fatherDefinition != null) {
            childDefinition.setWarningGroupId(fatherDefinition.getWarningGroupId());
B
bao liang 已提交
1346
            processDefineMapper.updateById(childDefinition);
1347 1348 1349
        }
    }

L
ligang 已提交
1350 1351
    /**
     * submit task to mysql
1352
     *
1353
     * @param taskInstance taskInstance
1354 1355
     * @param processInstance processInstance
     * @return task instance
L
ligang 已提交
1356
     */
1357
    public TaskInstance submitTaskInstanceToDB(TaskInstance taskInstance, ProcessInstance processInstance) {
L
ligang 已提交
1358 1359
        ExecutionStatus processInstanceState = processInstance.getState();

1360 1361 1362 1363 1364
        if (taskInstance.getState().typeIsFailure()) {
            if (taskInstance.isSubProcess()) {
                taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1);
            } else {
                if (processInstanceState != ExecutionStatus.READY_STOP
1365
                        && processInstanceState != ExecutionStatus.READY_PAUSE) {
L
ligang 已提交
1366 1367 1368 1369
                    // failure task set invalid
                    taskInstance.setFlag(Flag.NO);
                    updateTaskInstance(taskInstance);
                    // crate new task instance
1370 1371
                    if (taskInstance.getState() != ExecutionStatus.NEED_FAULT_TOLERANCE) {
                        taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1);
1372
                    }
1373
                    taskInstance.setSubmitTime(null);
1374 1375
                    taskInstance.setLogPath(null);
                    taskInstance.setExecutePath(null);
1376
                    taskInstance.setStartTime(null);
1377
                    taskInstance.setEndTime(null);
L
ligang 已提交
1378 1379 1380 1381 1382 1383
                    taskInstance.setFlag(Flag.YES);
                    taskInstance.setHost(null);
                    taskInstance.setId(0);
                }
            }
        }
1384
        taskInstance.setExecutorId(processInstance.getExecutorId());
L
ligang 已提交
1385 1386
        taskInstance.setProcessInstancePriority(processInstance.getProcessInstancePriority());
        taskInstance.setState(getSubmitTaskState(taskInstance, processInstanceState));
1387 1388 1389 1390 1391 1392
        if (taskInstance.getSubmitTime() == null) {
            taskInstance.setSubmitTime(new Date());
        }
        if (taskInstance.getFirstSubmitTime() == null) {
            taskInstance.setFirstSubmitTime(taskInstance.getSubmitTime());
        }
1393
        boolean saveResult = saveTaskInstance(taskInstance);
1394
        if (!saveResult) {
1395 1396
            return null;
        }
L
ligang 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        return taskInstance;
    }

    /**
     * get submit task instance state by the work process state
     * cannot modify the task state when running/kill/submit success, or this
     * task instance is already exists in task queue .
     * return pause if work process state is ready pause
     * return stop if work process state is ready stop
     * if all of above are not satisfied, return submit success
     *
1408
     * @param taskInstance taskInstance
1409 1410
     * @param processInstanceState processInstanceState
     * @return process instance state
L
ligang 已提交
1411
     */
1412
    public ExecutionStatus getSubmitTaskState(TaskInstance taskInstance, ExecutionStatus processInstanceState) {
L
ligang 已提交
1413
        ExecutionStatus state = taskInstance.getState();
1414 1415 1416
        // running, delayed or killed
        // the task already exists in task queue
        // return state
1417
        if (
1418 1419 1420
                state == ExecutionStatus.RUNNING_EXECUTION
                        || state == ExecutionStatus.DELAY_EXECUTION
                        || state == ExecutionStatus.KILL
1421
        ) {
L
ligang 已提交
1422 1423 1424 1425
            return state;
        }
        //return pasue /stop if process instance state is ready pause / stop
        // or return submit success
1426
        if (processInstanceState == ExecutionStatus.READY_PAUSE) {
L
ligang 已提交
1427
            state = ExecutionStatus.PAUSE;
1428
        } else if (processInstanceState == ExecutionStatus.READY_STOP
1429
                || !checkProcessStrategy(taskInstance)) {
L
ligang 已提交
1430
            state = ExecutionStatus.KILL;
1431
        } else {
L
ligang 已提交
1432 1433 1434 1435 1436
            state = ExecutionStatus.SUBMITTED_SUCCESS;
        }
        return state;
    }

1437
    /**
1438 1439
     * check process instance strategy
     *
1440 1441 1442
     * @param taskInstance taskInstance
     * @return check strategy result
     */
1443
    private boolean checkProcessStrategy(TaskInstance taskInstance) {
1444 1445
        ProcessInstance processInstance = this.findProcessInstanceById(taskInstance.getProcessInstanceId());
        FailureStrategy failureStrategy = processInstance.getFailureStrategy();
1446
        if (failureStrategy == FailureStrategy.CONTINUE) {
1447 1448 1449 1450
            return true;
        }
        List<TaskInstance> taskInstances = this.findValidTaskListByProcessId(taskInstance.getProcessInstanceId());

1451
        for (TaskInstance task : taskInstances) {
1452
            if (task.getState() == ExecutionStatus.FAILURE
1453
                    && task.getRetryTimes() >= task.getMaxRetryTimes()) {
1454 1455 1456 1457 1458 1459
                return false;
            }
        }
        return true;
    }

L
ligang 已提交
1460 1461
    /**
     * insert or update work process instance to data base
1462
     *
1463
     * @param processInstance processInstance
L
ligang 已提交
1464
     */
1465 1466
    public void saveProcessInstance(ProcessInstance processInstance) {
        if (processInstance == null) {
L
ligang 已提交
1467
            logger.error("save error, process instance is null!");
1468
            return;
L
ligang 已提交
1469
        }
1470
        if (processInstance.getId() != 0) {
1471
            processInstanceMapper.updateById(processInstance);
1472
        } else {
1473
            processInstanceMapper.insert(processInstance);
L
ligang 已提交
1474 1475 1476 1477 1478
        }
    }

    /**
     * insert or update command
1479
     *
1480 1481
     * @param command command
     * @return save command result
L
ligang 已提交
1482
     */
1483 1484
    public int saveCommand(Command command) {
        if (command.getId() != 0) {
B
bao liang 已提交
1485
            return commandMapper.updateById(command);
1486
        } else {
L
ligang 已提交
1487 1488 1489 1490 1491
            return commandMapper.insert(command);
        }
    }

    /**
1492 1493
     * insert or update task instance
     *
1494 1495
     * @param taskInstance taskInstance
     * @return save task instance result
L
ligang 已提交
1496
     */
1497 1498
    public boolean saveTaskInstance(TaskInstance taskInstance) {
        if (taskInstance.getId() != 0) {
L
ligang 已提交
1499
            return updateTaskInstance(taskInstance);
1500
        } else {
L
ligang 已提交
1501 1502 1503 1504 1505 1506
            return createTaskInstance(taskInstance);
        }
    }

    /**
     * insert task instance
1507
     *
1508 1509
     * @param taskInstance taskInstance
     * @return create task instance result
L
ligang 已提交
1510 1511 1512 1513 1514 1515 1516 1517
     */
    public boolean createTaskInstance(TaskInstance taskInstance) {
        int count = taskInstanceMapper.insert(taskInstance);
        return count > 0;
    }

    /**
     * update task instance
1518
     *
1519 1520
     * @param taskInstance taskInstance
     * @return update task instance result
L
ligang 已提交
1521
     */
1522
    public boolean updateTaskInstance(TaskInstance taskInstance) {
B
bao liang 已提交
1523
        int count = taskInstanceMapper.updateById(taskInstance);
L
ligang 已提交
1524 1525
        return count > 0;
    }
1526

1527 1528
    /**
     * find task instance by id
1529
     *
1530 1531 1532
     * @param taskId task id
     * @return task intance
     */
1533
    public TaskInstance findTaskInstanceById(Integer taskId) {
B
bao liang 已提交
1534
        return taskInstanceMapper.selectById(taskId);
L
ligang 已提交
1535 1536
    }

journey2018's avatar
journey2018 已提交
1537 1538
    /**
     * package task instance,associate processInstance and processDefine
1539
     *
1540 1541
     * @param taskInstId taskInstId
     * @return task instance
journey2018's avatar
journey2018 已提交
1542
     */
1543
    public TaskInstance getTaskInstanceDetailByTaskId(int taskInstId) {
journey2018's avatar
journey2018 已提交
1544 1545
        // get task instance
        TaskInstance taskInstance = findTaskInstanceById(taskInstId);
1546
        if (taskInstance == null) {
1547
            return null;
1548
        }
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
        setTaskInstanceDetail(taskInstance);
        return taskInstance;
    }

    /**
     * package task instance,associate processInstance and processDefine
     *
     * @param taskInstance taskInstance
     * @return task instance
     */
    public void setTaskInstanceDetail(TaskInstance taskInstance) {
journey2018's avatar
journey2018 已提交
1560 1561 1562
        // get process instance
        ProcessInstance processInstance = findProcessInstanceDetailById(taskInstance.getProcessInstanceId());
        // get process define
1563
        ProcessDefinition processDefine = findProcessDefinition(processInstance.getProcessDefinitionCode(),
1564
                processInstance.getProcessDefinitionVersion());
journey2018's avatar
journey2018 已提交
1565 1566
        taskInstance.setProcessInstance(processInstance);
        taskInstance.setProcessDefine(processDefine);
1567
        TaskDefinition taskDefinition = taskDefinitionLogMapper.queryByDefinitionCodeAndVersion(
1568 1569
                taskInstance.getTaskCode(),
                taskInstance.getTaskDefinitionVersion());
1570
        updateTaskDefinitionResources(taskDefinition);
1571
        taskInstance.setTaskDefine(taskDefinition);
journey2018's avatar
journey2018 已提交
1572 1573
    }

1574 1575 1576 1577 1578 1579 1580 1581
    /**
     * Update {@link ResourceInfo} information in {@link TaskDefinition}
     *
     * @param taskDefinition the given {@link TaskDefinition}
     */
    private void updateTaskDefinitionResources(TaskDefinition taskDefinition) {
        Map<String, Object> taskParameters = JSONUtils.parseObject(
                taskDefinition.getTaskParams(),
1582 1583
                new TypeReference<Map<String, Object>>() {
                });
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
        if (taskParameters != null) {
            // if contains mainJar field, query resource from database
            // Flink, Spark, MR
            if (taskParameters.containsKey("mainJar")) {
                Object mainJarObj = taskParameters.get("mainJar");
                ResourceInfo mainJar = JSONUtils.parseObject(
                        JSONUtils.toJsonString(mainJarObj),
                        ResourceInfo.class);
                ResourceInfo resourceInfo = updateResourceInfo(mainJar);
                if (resourceInfo != null) {
                    taskParameters.put("mainJar", resourceInfo);
                }
            }
            // update resourceList information
            if (taskParameters.containsKey("resourceList")) {
                String resourceListStr = JSONUtils.toJsonString(taskParameters.get("resourceList"));
                List<ResourceInfo> resourceInfos = JSONUtils.toList(resourceListStr, ResourceInfo.class);
                List<ResourceInfo> updatedResourceInfos = resourceInfos
                        .stream()
                        .map(this::updateResourceInfo)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                taskParameters.put("resourceList", updatedResourceInfos);
            }
            // set task parameters
            taskDefinition.setTaskParams(JSONUtils.toJsonString(taskParameters));
        }
    }

    /**
     * update {@link ResourceInfo} by given original ResourceInfo
     *
     * @param res origin resource info
     * @return {@link ResourceInfo}
     */
    private ResourceInfo updateResourceInfo(ResourceInfo res) {
        ResourceInfo resourceInfo = null;
        // only if mainJar is not null and does not contains "resourceName" field
        if (res != null) {
            int resourceId = res.getId();
            if (resourceId <= 0) {
                logger.error("invalid resourceId, {}", resourceId);
                return null;
            }
            resourceInfo = new ResourceInfo();
            // get resource from database, only one resource should be returned
            Resource resource = getResourceById(resourceId);
            resourceInfo.setId(resourceId);
            resourceInfo.setRes(resource.getFileName());
            resourceInfo.setResourceName(resource.getFullName());
            if (logger.isInfoEnabled()) {
                logger.info("updated resource info {}",
                        JSONUtils.toJsonString(resourceInfo));
            }
        }
        return resourceInfo;
    }

L
ligang 已提交
1642 1643
    /**
     * get id list by task state
1644
     *
1645
     * @param instanceId instanceId
1646
     * @param state state
1647
     * @return task instance states
L
ligang 已提交
1648
     */
1649
    public List<Integer> findTaskIdByInstanceState(int instanceId, ExecutionStatus state) {
L
ligang 已提交
1650 1651 1652 1653 1654
        return taskInstanceMapper.queryTaskByProcessIdAndState(instanceId, state.ordinal());
    }

    /**
     * find valid task list by process definition id
1655
     *
1656 1657
     * @param processInstanceId processInstanceId
     * @return task instance list
L
ligang 已提交
1658
     */
1659 1660
    public List<TaskInstance> findValidTaskListByProcessId(Integer processInstanceId) {
        return taskInstanceMapper.findValidTaskListByProcessId(processInstanceId, Flag.YES);
L
ligang 已提交
1661 1662 1663 1664
    }

    /**
     * find previous task list by work process id
1665
     *
1666 1667
     * @param processInstanceId processInstanceId
     * @return task instance list
L
ligang 已提交
1668
     */
1669
    public List<TaskInstance> findPreviousTaskListByWorkProcessId(Integer processInstanceId) {
1670
        return taskInstanceMapper.findValidTaskListByProcessId(processInstanceId, Flag.NO);
L
ligang 已提交
1671 1672 1673 1674
    }

    /**
     * update work process instance map
1675
     *
1676 1677
     * @param processInstanceMap processInstanceMap
     * @return update process instance result
L
ligang 已提交
1678
     */
1679
    public int updateWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap) {
B
bao liang 已提交
1680
        return processInstanceMapMapper.updateById(processInstanceMap);
L
ligang 已提交
1681 1682 1683 1684
    }

    /**
     * create work process instance map
1685
     *
1686 1687
     * @param processInstanceMap processInstanceMap
     * @return create process instance result
L
ligang 已提交
1688
     */
1689
    public int createWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap) {
K
Kirs 已提交
1690
        int count = 0;
1691 1692
        if (processInstanceMap != null) {
            return processInstanceMapMapper.insert(processInstanceMap);
L
ligang 已提交
1693 1694 1695 1696 1697 1698
        }
        return count;
    }

    /**
     * find work process map by parent process id and parent task id.
1699
     *
1700
     * @param parentWorkProcessId parentWorkProcessId
1701
     * @param parentTaskId parentTaskId
1702
     * @return process instance map
L
ligang 已提交
1703
     */
1704
    public ProcessInstanceMap findWorkProcessMapByParent(Integer parentWorkProcessId, Integer parentTaskId) {
L
ligang 已提交
1705 1706 1707 1708 1709
        return processInstanceMapMapper.queryByParentId(parentWorkProcessId, parentTaskId);
    }

    /**
     * delete work process map by parent process id
1710
     *
1711 1712
     * @param parentWorkProcessId parentWorkProcessId
     * @return delete process map result
L
ligang 已提交
1713
     */
1714
    public int deleteWorkProcessMapByParentId(int parentWorkProcessId) {
L
ligang 已提交
1715 1716 1717 1718
        return processInstanceMapMapper.deleteByParentProcessId(parentWorkProcessId);

    }

1719 1720
    /**
     * find sub process instance
1721
     *
1722
     * @param parentProcessId parentProcessId
1723
     * @param parentTaskId parentTaskId
1724 1725
     * @return process instance
     */
1726
    public ProcessInstance findSubProcessInstance(Integer parentProcessId, Integer parentTaskId) {
L
ligang 已提交
1727 1728
        ProcessInstance processInstance = null;
        ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryByParentId(parentProcessId, parentTaskId);
1729
        if (processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0) {
L
ligang 已提交
1730 1731 1732 1733 1734
            return processInstance;
        }
        processInstance = findProcessInstanceById(processInstanceMap.getProcessInstanceId());
        return processInstance;
    }
1735 1736 1737

    /**
     * find parent process instance
1738
     *
1739 1740 1741
     * @param subProcessId subProcessId
     * @return process instance
     */
L
ligang 已提交
1742 1743 1744
    public ProcessInstance findParentProcessInstance(Integer subProcessId) {
        ProcessInstance processInstance = null;
        ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryBySubProcessId(subProcessId);
1745
        if (processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0) {
L
ligang 已提交
1746 1747 1748 1749 1750 1751 1752 1753
            return processInstance;
        }
        processInstance = findProcessInstanceById(processInstanceMap.getParentProcessInstanceId());
        return processInstance;
    }

    /**
     * change task state
1754
     *
1755 1756 1757
     * @param state state
     * @param startTime startTime
     * @param host host
1758
     * @param executePath executePath
1759 1760
     * @param logPath logPath
     * @param taskInstId taskInstId
L
ligang 已提交
1761
     */
K
Kirs 已提交
1762
    public void changeTaskState(TaskInstance taskInstance, ExecutionStatus state, Date startTime, String host,
L
ligang 已提交
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
                                String executePath,
                                String logPath,
                                int taskInstId) {
        taskInstance.setState(state);
        taskInstance.setStartTime(startTime);
        taskInstance.setHost(host);
        taskInstance.setExecutePath(executePath);
        taskInstance.setLogPath(logPath);
        saveTaskInstance(taskInstance);
    }

    /**
     * update process instance
1776
     *
1777 1778
     * @param processInstance processInstance
     * @return update process instance result
L
ligang 已提交
1779
     */
1780
    public int updateProcessInstance(ProcessInstance processInstance) {
1781
        return processInstanceMapper.updateById(processInstance);
L
ligang 已提交
1782 1783 1784 1785
    }

    /**
     * change task state
1786
     *
1787 1788
     * @param state state
     * @param endTime endTime
1789
     * @param taskInstId taskInstId
1790
     * @param varPool varPool
L
ligang 已提交
1791
     */
K
Kirs 已提交
1792
    public void changeTaskState(TaskInstance taskInstance, ExecutionStatus state,
L
ligang 已提交
1793
                                Date endTime,
Q
qiaozhanwei 已提交
1794 1795
                                int processId,
                                String appIds,
1796
                                int taskInstId,
1797
                                String varPool) {
Q
qiaozhanwei 已提交
1798 1799
        taskInstance.setPid(processId);
        taskInstance.setAppLink(appIds);
L
ligang 已提交
1800 1801
        taskInstance.setState(state);
        taskInstance.setEndTime(endTime);
1802
        taskInstance.setVarPool(varPool);
1803
        changeOutParam(taskInstance);
L
ligang 已提交
1804 1805 1806
        saveTaskInstance(taskInstance);
    }

1807 1808 1809 1810 1811
    /**
     * for show in page of taskInstance
     */
    public void changeOutParam(TaskInstance taskInstance) {
        if (StringUtils.isEmpty(taskInstance.getVarPool())) {
1812 1813
            return;
        }
1814 1815
        List<Property> properties = JSONUtils.toList(taskInstance.getVarPool(), Property.class);
        if (CollectionUtils.isEmpty(properties)) {
1816 1817 1818
            return;
        }
        //if the result more than one line,just get the first .
1819 1820
        Map<String, Object> taskParams = JSONUtils.parseObject(taskInstance.getTaskParams(), new TypeReference<Map<String, Object>>() {
        });
1821 1822 1823 1824 1825
        Object localParams = taskParams.get(LOCAL_PARAMS);
        if (localParams == null) {
            return;
        }
        List<Property> allParam = JSONUtils.toList(JSONUtils.toJsonString(localParams), Property.class);
1826 1827 1828 1829 1830 1831
        Map<String, String> outProperty = new HashMap<>();
        for (Property info : properties) {
            if (info.getDirect() == Direct.OUT) {
                outProperty.put(info.getProp(), info.getValue());
            }
        }
1832 1833 1834
        for (Property info : allParam) {
            if (info.getDirect() == Direct.OUT) {
                String paramName = info.getProp();
1835
                info.setValue(outProperty.get(paramName));
1836 1837 1838
            }
        }
        taskParams.put(LOCAL_PARAMS, allParam);
1839
        taskInstance.setTaskParams(JSONUtils.toJsonString(taskParams));
1840 1841
    }

L
ligang 已提交
1842 1843
    /**
     * convert integer list to string list
1844
     *
1845 1846
     * @param intList intList
     * @return string list
L
ligang 已提交
1847
     */
1848 1849
    public List<String> convertIntListToString(List<Integer> intList) {
        if (intList == null) {
L
ligang 已提交
1850 1851
            return new ArrayList<>();
        }
1852
        List<String> result = new ArrayList<>(intList.size());
1853
        for (Integer intVar : intList) {
L
ligang 已提交
1854 1855 1856 1857 1858 1859
            result.add(String.valueOf(intVar));
        }
        return result;
    }

    /**
1860
     * query schedule by id
1861
     *
1862 1863
     * @param id id
     * @return schedule
L
ligang 已提交
1864 1865
     */
    public Schedule querySchedule(int id) {
B
bao liang 已提交
1866
        return scheduleMapper.selectById(id);
L
ligang 已提交
1867 1868
    }

1869
    /**
1870
     * query Schedule by processDefinitionCode
1871
     *
1872
     * @param processDefinitionCode processDefinitionCode
1873 1874
     * @see Schedule
     */
1875 1876
    public List<Schedule> queryReleaseSchedulerListByProcessDefinitionCode(long processDefinitionCode) {
        return scheduleMapper.queryReleaseSchedulerListByProcessDefinitionCode(processDefinitionCode);
1877 1878
    }

L
ligang 已提交
1879
    /**
1880
     * query need failover process instance
1881
     *
1882 1883
     * @param host host
     * @return process instance list
L
ligang 已提交
1884
     */
1885
    public List<ProcessInstance> queryNeedFailoverProcessInstances(String host) {
B
bao liang 已提交
1886
        return processInstanceMapper.queryByHostAndStatus(host, stateArray);
1887 1888
    }

L
ligang 已提交
1889 1890
    /**
     * process need failover process instance
1891
     *
1892
     * @param processInstance processInstance
L
ligang 已提交
1893
     */
1894
    @Transactional(rollbackFor = RuntimeException.class)
1895
    public void processNeedFailoverProcessInstances(ProcessInstance processInstance) {
L
ligang 已提交
1896
        //1 update processInstance host is null
1897
        processInstance.setHost(Constants.NULL);
B
bao liang 已提交
1898
        processInstanceMapper.updateById(processInstance);
L
ligang 已提交
1899

1900 1901
        ProcessDefinition processDefinition = findProcessDefinition(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion());

L
ligang 已提交
1902 1903
        //2 insert into recover command
        Command cmd = new Command();
1904
        cmd.setProcessDefinitionCode(processDefinition.getCode());
1905 1906
        cmd.setProcessDefinitionVersion(processDefinition.getVersion());
        cmd.setProcessInstanceId(processInstance.getId());
K
Kirs 已提交
1907
        cmd.setCommandParam(String.format("{\"%s\":%d}", Constants.CMD_PARAM_RECOVER_PROCESS_ID_STRING, processInstance.getId()));
L
ligang 已提交
1908 1909 1910 1911 1912 1913 1914
        cmd.setExecutorId(processInstance.getExecutorId());
        cmd.setCommandType(CommandType.RECOVER_TOLERANCE_FAULT_PROCESS);
        createCommand(cmd);
    }

    /**
     * query all need failover task instances by host
1915
     *
1916 1917
     * @param host host
     * @return task instance list
L
ligang 已提交
1918
     */
1919
    public List<TaskInstance> queryNeedFailoverTaskInstances(String host) {
B
bao liang 已提交
1920
        return taskInstanceMapper.queryByHostAndStatus(host,
1921
                stateArray);
L
ligang 已提交
1922 1923 1924 1925
    }

    /**
     * find data source by id
1926
     *
1927 1928
     * @param id id
     * @return datasource
L
ligang 已提交
1929
     */
1930
    public DataSource findDataSourceById(int id) {
B
bao liang 已提交
1931
        return dataSourceMapper.selectById(id);
L
ligang 已提交
1932 1933 1934 1935
    }

    /**
     * update process instance state by id
1936
     *
1937
     * @param processInstanceId processInstanceId
1938
     * @param executionStatus executionStatus
1939
     * @return update process result
L
ligang 已提交
1940 1941
     */
    public int updateProcessInstanceState(Integer processInstanceId, ExecutionStatus executionStatus) {
B
bao liang 已提交
1942 1943 1944
        ProcessInstance instance = processInstanceMapper.selectById(processInstanceId);
        instance.setState(executionStatus);
        return processInstanceMapper.updateById(instance);
L
ligang 已提交
1945 1946 1947 1948
    }

    /**
     * find process instance by the task id
1949
     *
1950 1951
     * @param taskId taskId
     * @return process instance
L
ligang 已提交
1952
     */
1953
    public ProcessInstance findProcessInstanceByTaskId(int taskId) {
B
bao liang 已提交
1954
        TaskInstance taskInstance = taskInstanceMapper.selectById(taskId);
1955
        if (taskInstance != null) {
B
bao liang 已提交
1956 1957 1958
            return processInstanceMapper.selectById(taskInstance.getProcessInstanceId());
        }
        return null;
L
ligang 已提交
1959 1960 1961 1962
    }

    /**
     * find udf function list by id list string
1963
     *
1964 1965
     * @param ids ids
     * @return udf function list
L
ligang 已提交
1966
     */
K
Kirs 已提交
1967
    public List<UdfFunc> queryUdfFunListByIds(int[] ids) {
B
bao liang 已提交
1968
        return udfFuncMapper.queryUdfByIdStr(ids, null);
L
ligang 已提交
1969 1970 1971 1972
    }

    /**
     * find tenant code by resource name
1973
     *
1974
     * @param resName resource name
1975
     * @param resourceType resource type
1976
     * @return tenant code
L
ligang 已提交
1977
     */
1978
    public String queryTenantCodeByResName(String resName, ResourceType resourceType) {
K
Kirs 已提交
1979 1980
        // in order to query tenant code successful although the version is older
        String fullName = resName.startsWith("/") ? resName : String.format("/%s", resName);
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995

        List<Resource> resourceList = resourceMapper.queryResource(fullName, resourceType.ordinal());
        if (CollectionUtils.isEmpty(resourceList)) {
            return StringUtils.EMPTY;
        }
        int userId = resourceList.get(0).getUserId();
        User user = userMapper.selectById(userId);
        if (Objects.isNull(user)) {
            return StringUtils.EMPTY;
        }
        Tenant tenant = tenantMapper.selectById(user.getTenantId());
        if (Objects.isNull(tenant)) {
            return StringUtils.EMPTY;
        }
        return tenant.getTenantCode();
L
ligang 已提交
1996 1997 1998
    }

    /**
1999
     * find schedule list by process define codes.
2000
     *
2001
     * @param codes codes
2002
     * @return schedule list
L
ligang 已提交
2003
     */
2004 2005
    public List<Schedule> selectAllByProcessDefineCode(long[] codes) {
        return scheduleMapper.selectAllByProcessDefineArray(codes);
L
ligang 已提交
2006 2007 2008 2009
    }

    /**
     * find last scheduler process instance in the date interval
2010
     *
2011
     * @param definitionCode definitionCode
2012 2013
     * @param dateInterval dateInterval
     * @return process instance
L
ligang 已提交
2014
     */
2015 2016
    public ProcessInstance findLastSchedulerProcessInterval(Long definitionCode, DateInterval dateInterval) {
        return processInstanceMapper.queryLastSchedulerProcess(definitionCode,
2017 2018
                dateInterval.getStartTime(),
                dateInterval.getEndTime());
L
ligang 已提交
2019 2020
    }

2021 2022
    /**
     * find last manual process instance interval
2023
     *
2024
     * @param definitionCode process definition code
2025 2026 2027
     * @param dateInterval dateInterval
     * @return process instance
     */
2028 2029
    public ProcessInstance findLastManualProcessInterval(Long definitionCode, DateInterval dateInterval) {
        return processInstanceMapper.queryLastManualProcess(definitionCode,
2030 2031
                dateInterval.getStartTime(),
                dateInterval.getEndTime());
L
ligang 已提交
2032 2033
    }

2034 2035
    /**
     * find last running process instance
2036
     *
2037
     * @param definitionCode process definition code
2038 2039
     * @param startTime start time
     * @param endTime end time
2040 2041
     * @return process instance
     */
2042 2043
    public ProcessInstance findLastRunningProcess(Long definitionCode, Date startTime, Date endTime) {
        return processInstanceMapper.queryLastRunningProcess(definitionCode,
2044 2045 2046
                startTime,
                endTime,
                stateArray);
L
ligang 已提交
2047
    }
2048 2049

    /**
2050
     * query user queue by process instance id
2051
     *
2052 2053
     * @param processInstanceId processInstanceId
     * @return queue
2054
     */
2055
    public String queryUserQueueByProcessInstanceId(int processInstanceId) {
B
bao liang 已提交
2056 2057 2058

        String queue = "";
        ProcessInstance processInstance = processInstanceMapper.selectById(processInstanceId);
2059
        if (processInstance == null) {
B
bao liang 已提交
2060 2061 2062
            return queue;
        }
        User executor = userMapper.selectById(processInstance.getExecutorId());
2063
        if (executor != null) {
B
bao liang 已提交
2064 2065 2066
            queue = executor.getQueue();
        }
        return queue;
2067 2068
    }

K
Kirs 已提交
2069 2070
    /**
     * query project name and user name by processInstanceId.
2071
     *
K
Kirs 已提交
2072 2073 2074 2075 2076 2077 2078
     * @param processInstanceId processInstanceId
     * @return projectName and userName
     */
    public ProjectUser queryProjectWithUserByProcessInstanceId(int processInstanceId) {
        return projectMapper.queryProjectWithUserByProcessInstanceId(processInstanceId);
    }

2079
    /**
L
lgcareer 已提交
2080
     * get task worker group
2081
     *
2082 2083
     * @param taskInstance taskInstance
     * @return workerGroupId
2084
     */
L
lgcareer 已提交
2085 2086
    public String getTaskWorkerGroup(TaskInstance taskInstance) {
        String workerGroup = taskInstance.getWorkerGroup();
K
Kirs 已提交
2087

2088
        if (StringUtils.isNotBlank(workerGroup)) {
L
lgcareer 已提交
2089
            return workerGroup;
2090 2091
        }
        int processInstanceId = taskInstance.getProcessInstanceId();
2092
        ProcessInstance processInstance = findProcessInstanceById(processInstanceId);
2093

2094
        if (processInstance != null) {
L
lgcareer 已提交
2095
            return processInstance.getWorkerGroup();
2096
        }
L
lgcareer 已提交
2097 2098
        logger.info("task : {} will use default worker group", taskInstance.getId());
        return Constants.DEFAULT_WORKER_GROUP;
2099 2100
    }

2101
    /**
2102
     * get have perm project list
2103
     *
2104 2105
     * @param userId userId
     * @return project list
2106
     */
2107
    public List<Project> getProjectListHavePerm(int userId) {
2108 2109
        List<Project> createProjects = projectMapper.queryProjectCreatedByUser(userId);
        List<Project> authedProjects = projectMapper.queryAuthedProjectListByUserId(userId);
2110

2111
        if (createProjects == null) {
B
bao liang 已提交
2112 2113
            createProjects = new ArrayList<>();
        }
2114

2115
        if (authedProjects != null) {
B
bao liang 已提交
2116
            createProjects.addAll(authedProjects);
2117
        }
2118
        return createProjects;
B
bao liang 已提交
2119
    }
2120

2121 2122
    /**
     * list unauthorized udf function
2123
     *
2124
     * @param userId user id
2125
     * @param needChecks data source id array
2126 2127
     * @return unauthorized udf function list
     */
2128
    public <T> List<T> listUnauthorized(int userId, T[] needChecks, AuthorizationType authorizationType) {
2129
        List<T> resultList = new ArrayList<>();
2130

2131
        if (Objects.nonNull(needChecks) && needChecks.length > 0) {
2132
            Set<T> originResSet = new HashSet<>(Arrays.asList(needChecks));
2133

2134
            switch (authorizationType) {
2135
                case RESOURCE_FILE_ID:
2136
                case UDF_FILE:
2137 2138 2139
                    List<Resource> ownUdfResources = resourceMapper.listAuthorizedResourceById(userId, needChecks);
                    addAuthorizedResources(ownUdfResources, userId);
                    Set<Integer> authorizedResourceFiles = ownUdfResources.stream().map(Resource::getId).collect(toSet());
2140 2141 2142
                    originResSet.removeAll(authorizedResourceFiles);
                    break;
                case RESOURCE_FILE_NAME:
2143 2144 2145
                    List<Resource> ownResources = resourceMapper.listAuthorizedResource(userId, needChecks);
                    addAuthorizedResources(ownResources, userId);
                    Set<String> authorizedResources = ownResources.stream().map(Resource::getFullName).collect(toSet());
2146 2147 2148
                    originResSet.removeAll(authorizedResources);
                    break;
                case DATASOURCE:
2149
                    Set<Integer> authorizedDatasources = dataSourceMapper.listAuthorizedDataSource(userId, needChecks).stream().map(DataSource::getId).collect(toSet());
2150 2151 2152
                    originResSet.removeAll(authorizedDatasources);
                    break;
                case UDF:
2153
                    Set<Integer> authorizedUdfs = udfFuncMapper.listAuthorizedUdfFunc(userId, needChecks).stream().map(UdfFunc::getId).collect(toSet());
2154 2155
                    originResSet.removeAll(authorizedUdfs);
                    break;
2156 2157
                default:
                    break;
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
            }

            resultList.addAll(originResSet);
        }

        return resultList;
    }

    /**
     * get user by user id
2168
     *
2169 2170 2171
     * @param userId user id
     * @return User
     */
2172
    public User getUserById(int userId) {
2173
        return userMapper.selectById(userId);
2174 2175
    }

2176
    /**
2177
     * get resource by resource id
2178
     *
2179
     * @param resourceId resource id
2180 2181
     * @return Resource
     */
2182 2183
    public Resource getResourceById(int resourceId) {
        return resourceMapper.selectById(resourceId);
2184 2185
    }

2186 2187
    /**
     * list resources by ids
2188
     *
2189 2190 2191
     * @param resIds resIds
     * @return resource list
     */
2192
    public List<Resource> listResourceByIds(Integer[] resIds) {
2193 2194 2195
        return resourceMapper.listResourceByIds(resIds);
    }

2196 2197 2198
    /**
     * format task app id in task instance
     */
2199
    public String formatTaskAppId(TaskInstance taskInstance) {
2200 2201 2202 2203 2204 2205
        ProcessInstance processInstance = findProcessInstanceById(taskInstance.getProcessInstanceId());
        if (processInstance == null) {
            return "";
        }
        ProcessDefinition definition = findProcessDefinition(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion());
        if (definition == null) {
2206 2207
            return "";
        }
2208
        return String.format("%s_%s_%s", definition.getId(), processInstance.getId(), taskInstance.getId());
2209
    }
2210

2211 2212 2213
    /**
     * switch process definition version to process definition log version
     */
2214
    public int switchVersion(ProcessDefinition processDefinition, ProcessDefinitionLog processDefinitionLog) {
2215
        if (null == processDefinition || null == processDefinitionLog) {
2216
            return Constants.DEFINITION_FAILURE;
2217
        }
2218
        processDefinitionLog.setId(processDefinition.getId());
2219
        processDefinitionLog.setReleaseState(ReleaseState.OFFLINE);
2220
        processDefinitionLog.setFlag(Flag.YES);
2221

2222 2223
        int result = processDefineMapper.updateById(processDefinitionLog);
        if (result > 0) {
2224
            result = switchProcessTaskRelationVersion(processDefinitionLog);
2225 2226 2227
            if (result <= 0) {
                return Constants.DEFINITION_FAILURE;
            }
2228 2229 2230 2231
        }
        return result;
    }

2232
    public int switchProcessTaskRelationVersion(ProcessDefinition processDefinition) {
2233 2234 2235 2236 2237
        List<ProcessTaskRelation> processTaskRelationList = processTaskRelationMapper.queryByProcessCode(processDefinition.getProjectCode(), processDefinition.getCode());
        if (!processTaskRelationList.isEmpty()) {
            processTaskRelationMapper.deleteByCode(processDefinition.getProjectCode(), processDefinition.getCode());
        }
        List<ProcessTaskRelationLog> processTaskRelationLogList = processTaskRelationLogMapper.queryByProcessCodeAndVersion(processDefinition.getCode(), processDefinition.getVersion());
2238
        return processTaskRelationMapper.batchInsert(processTaskRelationLogList);
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
    }

    /**
     * get resource ids
     *
     * @param taskDefinition taskDefinition
     * @return resource ids
     */
    public String getResourceIds(TaskDefinition taskDefinition) {
        Set<Integer> resourceIds = null;
2249
        AbstractParameters params = TaskParametersUtils.getParameters(taskDefinition.getTaskType(), taskDefinition.getTaskParams());
2250 2251
        if (params != null && CollectionUtils.isNotEmpty(params.getResourceFilesList())) {
            resourceIds = params.getResourceFilesList().
2252 2253 2254 2255
                    stream()
                    .filter(t -> t.getId() != 0)
                    .map(ResourceInfo::getId)
                    .collect(Collectors.toSet());
2256 2257 2258 2259 2260 2261 2262
        }
        if (CollectionUtils.isEmpty(resourceIds)) {
            return StringUtils.EMPTY;
        }
        return StringUtils.join(resourceIds, ",");
    }

2263
    public int saveTaskDefine(User operator, long projectCode, List<TaskDefinitionLog> taskDefinitionLogs) {
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
        Date now = new Date();
        List<TaskDefinitionLog> newTaskDefinitionLogs = new ArrayList<>();
        List<TaskDefinitionLog> updateTaskDefinitionLogs = new ArrayList<>();
        for (TaskDefinitionLog taskDefinitionLog : taskDefinitionLogs) {
            taskDefinitionLog.setProjectCode(projectCode);
            taskDefinitionLog.setUpdateTime(now);
            taskDefinitionLog.setOperateTime(now);
            taskDefinitionLog.setOperator(operator.getId());
            taskDefinitionLog.setResourceIds(getResourceIds(taskDefinitionLog));
            if (taskDefinitionLog.getCode() > 0 && taskDefinitionLog.getVersion() > 0) {
                TaskDefinitionLog definitionCodeAndVersion = taskDefinitionLogMapper
2275
                        .queryByDefinitionCodeAndVersion(taskDefinitionLog.getCode(), taskDefinitionLog.getVersion());
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
                if (definitionCodeAndVersion != null) {
                    if (!taskDefinitionLog.equals(definitionCodeAndVersion)) {
                        taskDefinitionLog.setUserId(definitionCodeAndVersion.getUserId());
                        Integer version = taskDefinitionLogMapper.queryMaxVersionForDefinition(taskDefinitionLog.getCode());
                        taskDefinitionLog.setVersion(version + 1);
                        taskDefinitionLog.setCreateTime(definitionCodeAndVersion.getCreateTime());
                        updateTaskDefinitionLogs.add(taskDefinitionLog);
                    }
                    continue;
                }
            }
            taskDefinitionLog.setUserId(operator.getId());
            taskDefinitionLog.setVersion(Constants.VERSION_FIRST);
            taskDefinitionLog.setCreateTime(now);
            if (taskDefinitionLog.getCode() == 0) {
                try {
2292 2293
                    taskDefinitionLog.setCode(CodeGenerateUtils.getInstance().genCode());
                } catch (CodeGenerateException e) {
2294
                    logger.error("Task code get error, ", e);
2295
                    return Constants.DEFINITION_FAILURE;
2296 2297 2298 2299
                }
            }
            newTaskDefinitionLogs.add(taskDefinitionLog);
        }
2300 2301
        int insertResult = 0;
        int updateResult = 0;
2302 2303 2304 2305 2306
        for (TaskDefinitionLog taskDefinitionToUpdate : updateTaskDefinitionLogs) {
            TaskDefinition task = taskDefinitionMapper.queryByCode(taskDefinitionToUpdate.getCode());
            if (task == null) {
                newTaskDefinitionLogs.add(taskDefinitionToUpdate);
            } else {
2307
                insertResult += taskDefinitionLogMapper.insert(taskDefinitionToUpdate);
2308
                taskDefinitionToUpdate.setId(task.getId());
2309
                updateResult += taskDefinitionMapper.updateById(taskDefinitionToUpdate);
2310 2311 2312
            }
        }
        if (!newTaskDefinitionLogs.isEmpty()) {
2313 2314
            updateResult += taskDefinitionMapper.batchInsert(newTaskDefinitionLogs);
            insertResult += taskDefinitionLogMapper.batchInsert(newTaskDefinitionLogs);
2315
        }
2316
        return (insertResult & updateResult) > 0 ? 1 : Constants.EXIT_CODE_SUCCESS;
2317 2318
    }

2319
    /**
2320
     * save processDefinition (including create or update processDefinition)
2321
     */
2322 2323 2324
    public int saveProcessDefine(User operator, ProcessDefinition processDefinition, Boolean isFromProcessDefine) {
        ProcessDefinitionLog processDefinitionLog = new ProcessDefinitionLog(processDefinition);
        Integer version = processDefineLogMapper.queryMaxVersionForDefinition(processDefinition.getCode());
2325
        int insertVersion = version == null || version == 0 ? Constants.VERSION_FIRST : version + 1;
2326 2327 2328
        processDefinitionLog.setVersion(insertVersion);
        processDefinitionLog.setReleaseState(isFromProcessDefine ? ReleaseState.OFFLINE : ReleaseState.ONLINE);
        processDefinitionLog.setOperator(operator.getId());
2329
        processDefinitionLog.setOperateTime(processDefinition.getUpdateTime());
2330 2331
        int insertLog = processDefineLogMapper.insert(processDefinitionLog);
        int result;
2332
        if (0 == processDefinition.getId()) {
2333 2334
            result = processDefineMapper.insert(processDefinitionLog);
        } else {
2335
            processDefinitionLog.setId(processDefinition.getId());
2336 2337 2338 2339 2340 2341 2342 2343 2344
            result = processDefineMapper.updateById(processDefinitionLog);
        }
        return (insertLog & result) > 0 ? insertVersion : 0;
    }

    /**
     * save task relations
     */
    public int saveTaskRelation(User operator, long projectCode, long processDefinitionCode, int processDefinitionVersion,
2345 2346 2347 2348
                                List<ProcessTaskRelationLog> taskRelationList, List<TaskDefinitionLog> taskDefinitionLogs) {
        Map<Long, TaskDefinitionLog> taskDefinitionLogMap = null;
        if (CollectionUtils.isNotEmpty(taskDefinitionLogs)) {
            taskDefinitionLogMap = taskDefinitionLogs.stream()
2349
                    .collect(Collectors.toMap(TaskDefinition::getCode, taskDefinitionLog -> taskDefinitionLog));
2350
        }
2351
        Date now = new Date();
2352
        for (ProcessTaskRelationLog processTaskRelationLog : taskRelationList) {
2353 2354 2355
            processTaskRelationLog.setProjectCode(projectCode);
            processTaskRelationLog.setProcessDefinitionCode(processDefinitionCode);
            processTaskRelationLog.setProcessDefinitionVersion(processDefinitionVersion);
2356 2357 2358 2359 2360 2361 2362
            if (taskDefinitionLogMap != null) {
                TaskDefinitionLog taskDefinitionLog = taskDefinitionLogMap.get(processTaskRelationLog.getPreTaskCode());
                if (taskDefinitionLog != null) {
                    processTaskRelationLog.setPreTaskVersion(taskDefinitionLog.getVersion());
                }
                processTaskRelationLog.setPostTaskVersion(taskDefinitionLogMap.get(processTaskRelationLog.getPostTaskCode()).getVersion());
            }
2363 2364 2365 2366
            processTaskRelationLog.setCreateTime(now);
            processTaskRelationLog.setUpdateTime(now);
            processTaskRelationLog.setOperator(operator.getId());
            processTaskRelationLog.setOperateTime(now);
2367
        }
2368 2369 2370 2371
        List<ProcessTaskRelation> processTaskRelationList = processTaskRelationMapper.queryByProcessCode(projectCode, processDefinitionCode);
        if (!processTaskRelationList.isEmpty()) {
            Set<Integer> processTaskRelationSet = processTaskRelationList.stream().map(ProcessTaskRelation::hashCode).collect(toSet());
            Set<Integer> taskRelationSet = taskRelationList.stream().map(ProcessTaskRelationLog::hashCode).collect(toSet());
K
kezhenxu94 已提交
2372 2373
            boolean result = CollectionUtils.isEqualCollection(processTaskRelationSet, taskRelationSet);
            if (result) {
2374 2375 2376 2377
                return Constants.EXIT_CODE_SUCCESS;
            }
            processTaskRelationMapper.deleteByCode(projectCode, processDefinitionCode);
        }
2378 2379
        int result = processTaskRelationMapper.batchInsert(taskRelationList);
        int resultLog = processTaskRelationLogMapper.batchInsert(taskRelationList);
2380
        return (result & resultLog) > 0 ? Constants.EXIT_CODE_SUCCESS : Constants.EXIT_CODE_FAILURE;
2381 2382
    }

2383
    public boolean isTaskOnline(long taskCode) {
2384 2385 2386
        List<ProcessTaskRelation> processTaskRelationList = processTaskRelationMapper.queryByTaskCode(taskCode);
        if (!processTaskRelationList.isEmpty()) {
            Set<Long> processDefinitionCodes = processTaskRelationList
2387 2388 2389
                    .stream()
                    .map(ProcessTaskRelation::getProcessDefinitionCode)
                    .collect(Collectors.toSet());
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
            List<ProcessDefinition> processDefinitionList = processDefineMapper.queryByCodes(processDefinitionCodes);
            // check process definition is already online
            for (ProcessDefinition processDefinition : processDefinitionList) {
                if (processDefinition.getReleaseState() == ReleaseState.ONLINE) {
                    return true;
                }
            }
        }
        return false;
    }
2400 2401 2402 2403 2404 2405 2406 2407

    /**
     * Generate the DAG Graph based on the process definition id
     *
     * @param processDefinition process definition
     * @return dag graph
     */
    public DAG<String, TaskNode, TaskNodeRelation> genDagGraph(ProcessDefinition processDefinition) {
2408
        List<ProcessTaskRelation> processTaskRelations = processTaskRelationMapper.queryByProcessCode(processDefinition.getProjectCode(), processDefinition.getCode());
2409
        List<TaskNode> taskNodeList = transformTask(processTaskRelations, Lists.newArrayList());
2410
        ProcessDag processDag = DagHelper.getProcessDag(taskNodeList, new ArrayList<>(processTaskRelations));
2411 2412 2413
        // Generate concrete Dag to be executed
        return DagHelper.buildDagGraph(processDag);
    }
2414

2415 2416 2417 2418
    /**
     * generate DagData
     */
    public DagData genDagData(ProcessDefinition processDefinition) {
2419 2420 2421
        List<ProcessTaskRelation> processTaskRelations = processTaskRelationMapper.queryByProcessCode(processDefinition.getProjectCode(), processDefinition.getCode());
        List<TaskDefinitionLog> taskDefinitionLogList = genTaskDefineList(processTaskRelations);
        List<TaskDefinition> taskDefinitions = taskDefinitionLogList.stream()
2422 2423
                .map(taskDefinitionLog -> JSONUtils.parseObject(JSONUtils.toJsonString(taskDefinitionLog), TaskDefinition.class))
                .collect(Collectors.toList());
2424
        return new DagData(processDefinition, processTaskRelations, taskDefinitions);
2425 2426
    }

2427
    public List<TaskDefinitionLog> genTaskDefineList(List<ProcessTaskRelation> processTaskRelations) {
2428
        Set<TaskDefinition> taskDefinitionSet = new HashSet<>();
2429
        for (ProcessTaskRelation processTaskRelation : processTaskRelations) {
2430 2431 2432 2433 2434 2435 2436
            if (processTaskRelation.getPreTaskCode() > 0) {
                taskDefinitionSet.add(new TaskDefinition(processTaskRelation.getPreTaskCode(), processTaskRelation.getPreTaskVersion()));
            }
            if (processTaskRelation.getPostTaskCode() > 0) {
                taskDefinitionSet.add(new TaskDefinition(processTaskRelation.getPostTaskCode(), processTaskRelation.getPostTaskVersion()));
            }
        }
2437
        return taskDefinitionLogMapper.queryByTaskDefinitions(taskDefinitionSet);
2438 2439
    }

2440
    /**
2441
     * find task definition by code and version
2442 2443 2444 2445 2446
     */
    public TaskDefinition findTaskDefinition(long taskCode, int taskDefinitionVersion) {
        return taskDefinitionLogMapper.queryByDefinitionCodeAndVersion(taskCode, taskDefinitionVersion);
    }

2447 2448 2449 2450 2451 2452 2453
    /**
     * find process task relation list by projectCode and processDefinitionCode
     */
    public List<ProcessTaskRelation> findRelationByCode(long projectCode, long processDefinitionCode) {
        return processTaskRelationMapper.queryByProcessCode(projectCode, processDefinitionCode);
    }

2454 2455
    /**
     * add authorized resources
2456
     *
2457
     * @param ownResources own resources
2458
     * @param userId userId
2459 2460 2461 2462 2463 2464
     */
    private void addAuthorizedResources(List<Resource> ownResources, int userId) {
        List<Integer> relationResourceIds = resourceUserMapper.queryResourcesIdListByUserIdAndPerm(userId, 7);
        List<Resource> relationResources = CollectionUtils.isNotEmpty(relationResourceIds) ? resourceMapper.queryResourceListById(relationResourceIds) : new ArrayList<>();
        ownResources.addAll(relationResources);
    }
2465 2466 2467 2468

    /**
     * Use temporarily before refactoring taskNode
     */
2469
    public List<TaskNode> transformTask(List<ProcessTaskRelation> taskRelationList, List<TaskDefinitionLog> taskDefinitionLogs) {
2470
        Map<Long, List<Long>> taskCodeMap = new HashMap<>();
2471
        for (ProcessTaskRelation processTaskRelation : taskRelationList) {
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
            taskCodeMap.compute(processTaskRelation.getPostTaskCode(), (k, v) -> {
                if (v == null) {
                    v = new ArrayList<>();
                }
                if (processTaskRelation.getPreTaskCode() != 0L) {
                    v.add(processTaskRelation.getPreTaskCode());
                }
                return v;
            });
        }
2482 2483 2484
        if (CollectionUtils.isEmpty(taskDefinitionLogs)) {
            taskDefinitionLogs = genTaskDefineList(taskRelationList);
        }
2485
        Map<Long, TaskDefinitionLog> taskDefinitionLogMap = taskDefinitionLogs.stream()
2486
                .collect(Collectors.toMap(TaskDefinitionLog::getCode, taskDefinitionLog -> taskDefinitionLog));
2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500
        List<TaskNode> taskNodeList = new ArrayList<>();
        for (Entry<Long, List<Long>> code : taskCodeMap.entrySet()) {
            TaskDefinitionLog taskDefinitionLog = taskDefinitionLogMap.get(code.getKey());
            if (taskDefinitionLog != null) {
                TaskNode taskNode = new TaskNode();
                taskNode.setCode(taskDefinitionLog.getCode());
                taskNode.setVersion(taskDefinitionLog.getVersion());
                taskNode.setName(taskDefinitionLog.getName());
                taskNode.setDesc(taskDefinitionLog.getDescription());
                taskNode.setType(taskDefinitionLog.getTaskType().toUpperCase());
                taskNode.setRunFlag(taskDefinitionLog.getFlag() == Flag.YES ? Constants.FLOWNODE_RUN_FLAG_NORMAL : Constants.FLOWNODE_RUN_FLAG_FORBIDDEN);
                taskNode.setMaxRetryTimes(taskDefinitionLog.getFailRetryTimes());
                taskNode.setRetryInterval(taskDefinitionLog.getFailRetryInterval());
                Map<String, Object> taskParamsMap = taskNode.taskParamsToJsonObj(taskDefinitionLog.getTaskParams());
2501
                taskNode.setConditionResult(JSONUtils.toJsonString(taskParamsMap.get(Constants.CONDITION_RESULT)));
2502
                taskNode.setSwitchResult(JSONUtils.toJsonString(taskParamsMap.get(Constants.SWITCH_RESULT)));
2503
                taskNode.setDependence(JSONUtils.toJsonString(taskParamsMap.get(Constants.DEPENDENCE)));
2504 2505 2506 2507 2508
                taskParamsMap.remove(Constants.CONDITION_RESULT);
                taskParamsMap.remove(Constants.DEPENDENCE);
                taskNode.setParams(JSONUtils.toJsonString(taskParamsMap));
                taskNode.setTaskInstancePriority(taskDefinitionLog.getTaskPriority());
                taskNode.setWorkerGroup(taskDefinitionLog.getWorkerGroup());
2509
                taskNode.setEnvironmentCode(taskDefinitionLog.getEnvironmentCode());
2510
                taskNode.setTimeout(JSONUtils.toJsonString(new TaskTimeoutParameter(taskDefinitionLog.getTimeoutFlag() == TimeoutFlag.OPEN,
2511 2512
                        taskDefinitionLog.getTimeoutNotifyStrategy(),
                        taskDefinitionLog.getTimeout())));
2513
                taskNode.setDelayTime(taskDefinitionLog.getDelayTime());
2514
                taskNode.setPreTasks(JSONUtils.toJsonString(code.getValue().stream().map(taskDefinitionLogMap::get).map(TaskDefinition::getCode).collect(Collectors.toList())));
2515 2516 2517 2518 2519
                taskNodeList.add(taskNode);
            }
        }
        return taskNodeList;
    }
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535

    public Map<ProcessInstance, TaskInstance> notifyProcessList(int processId, int taskId) {
        HashMap<ProcessInstance, TaskInstance> processTaskMap = new HashMap<>();
        //find sub tasks
        ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryBySubProcessId(processId);
        if (processInstanceMap == null) {
            return processTaskMap;
        }
        ProcessInstance fatherProcess = this.findProcessInstanceById(processInstanceMap.getParentProcessInstanceId());
        TaskInstance fatherTask = this.findTaskInstanceById(processInstanceMap.getParentTaskInstanceId());

        if (fatherProcess != null) {
            processTaskMap.put(fatherProcess, fatherTask);
        }
        return processTaskMap;
    }
2536 2537

    public ProcessInstance loadNextProcess4Serial(long code, int state) {
2538 2539 2540 2541 2542 2543 2544 2545
        return this.processInstanceMapper.loadNextProcess4Serial(code, state);
    }

    private void deleteCommandWithCheck(int commandId) {
        int delete = this.commandMapper.deleteById(commandId);
        if (delete != 1) {
            throw new ServiceException("delete command fail, id:" + commandId);
        }
2546
    }
L
ligang 已提交
2547
}