ProcessDao.java 60.2 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.escheduler.dao;

import cn.escheduler.common.Constants;
import cn.escheduler.common.enums.*;
import cn.escheduler.common.model.DateInterval;
import cn.escheduler.common.model.TaskNode;
import cn.escheduler.common.queue.ITaskQueue;
import cn.escheduler.common.queue.TaskQueueFactory;
import cn.escheduler.common.task.subprocess.SubProcessParameters;
import cn.escheduler.common.utils.DateUtils;
import cn.escheduler.common.utils.JSONUtils;
import cn.escheduler.common.utils.ParameterUtils;
import cn.escheduler.dao.mapper.*;
import cn.escheduler.dao.model.*;
import cn.escheduler.dao.utils.cron.CronUtils;
import com.alibaba.fastjson.JSONObject;
import com.cronutils.model.Cron;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
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;

import java.util.*;

import static cn.escheduler.common.Constants.*;
import static cn.escheduler.dao.datasource.ConnectionFactory.getMapper;

/**
 * process relative dao that some mappers in this.
 */
@Component
public class ProcessDao extends AbstractBaseDao {

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

    private final int[] stateArray = new int[]{ExecutionStatus.SUBMITTED_SUCCESS.ordinal(),
            ExecutionStatus.RUNNING_EXEUTION.ordinal(),
            ExecutionStatus.READY_PAUSE.ordinal(),
            ExecutionStatus.READY_STOP.ordinal()};

    @Autowired
62
    private UserMapper userMapper;
L
ligang 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

    @Autowired
    private ProcessDefinitionMapper processDefineMapper;

    @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;

B
baoliang 已提交
91 92 93
    @Autowired
    private WorkerGroupMapper workerGroupMapper;

B
baoliang 已提交
94 95 96
    @Autowired
    private ErrorCommandMapper errorCommandMapper;

L
ligang 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110
    /**
     * task queue impl
     */
    protected ITaskQueue taskQueue;

    public ProcessDao(){
        init();
    }

    /**
     * initialize
     */
    @Override
    protected void init() {
111
        userMapper=getMapper(UserMapper.class);
L
ligang 已提交
112 113 114 115 116 117 118 119 120
        processDefineMapper = getMapper(ProcessDefinitionMapper.class);
        processInstanceMapper = getMapper(ProcessInstanceMapper.class);
        dataSourceMapper = getMapper(DataSourceMapper.class);
        processInstanceMapMapper = getMapper(ProcessInstanceMapMapper.class);
        taskInstanceMapper = getMapper(TaskInstanceMapper.class);
        commandMapper = getMapper(CommandMapper.class);
        scheduleMapper = getMapper(ScheduleMapper.class);
        udfFuncMapper = getMapper(UdfFuncMapper.class);
        resourceMapper = getMapper(ResourceMapper.class);
B
baoliang 已提交
121
        workerGroupMapper = getMapper(WorkerGroupMapper.class);
L
ligang 已提交
122 123 124 125 126 127 128 129
        taskQueue = TaskQueueFactory.getTaskQueueInstance();
    }


    /**
     * find one command from command queue, construct process instance
     * @param logger
     * @param host
B
baoliang 已提交
130
     * @param validThreadNum
L
ligang 已提交
131 132 133
     * @return
     */
    @Transactional(value = "TransactionManager",rollbackFor = Exception.class)
B
baoliang 已提交
134
    public ProcessInstance scanCommand(Logger logger, String host, int validThreadNum){
L
ligang 已提交
135 136 137 138 139 140 141 142

        ProcessInstance processInstance = null;
        Command command = findOneCommand();
        if (command == null) {
            return null;
        }
        logger.info(String.format("find one command: id: %d, type: %s", command.getId(),command.getCommandType().toString()));

B
baoliang 已提交
143 144 145 146 147 148
        try{
            processInstance = constructProcessInstance(command, host);
            //cannot construct process instance, return null;
            if(processInstance == null){
                logger.error("scan command, command parameter is error: %s", command.toString());
                delCommandByid(command.getId());
B
baoliang 已提交
149
                saveErrorCommand(command, "process instance is null");
L
ligang 已提交
150
                return null;
B
baoliang 已提交
151 152 153
            }else if(!checkThreadNum(command, validThreadNum)){
                    logger.info("there is not enough thread for this command: {}",command.toString() );
                    return setWaitingThreadProcess(command, processInstance);
L
ligang 已提交
154
            }else{
B
baoliang 已提交
155 156 157 158 159 160
                    processInstance.setCommandType(command.getCommandType());
                    processInstance.addHistoryCmd(command.getCommandType());
                    saveProcessInstance(processInstance);
                    this.setSubProcessParam(processInstance);
                    delCommandByid(command.getId());
                    return processInstance;
L
ligang 已提交
161
            }
B
baoliang 已提交
162 163
        }catch (Exception e){
            logger.error("scan command error ", e);
B
baoliang 已提交
164
            saveErrorCommand(command, e.toString());
B
baoliang 已提交
165
            delCommandByid(command.getId());
L
ligang 已提交
166
        }
B
baoliang 已提交
167 168 169
        return null;
    }

B
baoliang 已提交
170 171 172 173 174 175
    private void saveErrorCommand(Command command, String message) {

        ErrorCommand errorCommand = new ErrorCommand(command, message);
        this.errorCommandMapper.insert(errorCommand);
    }

B
baoliang 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
    /**
     * set process waiting thread
     * @param command
     * @param processInstance
     * @return
     */
    private ProcessInstance setWaitingThreadProcess(Command command, ProcessInstance processInstance) {
        processInstance.setState(ExecutionStatus.WAITTING_THREAD);
        if(command.getCommandType() != CommandType.RECOVER_WAITTING_THREAD){
            processInstance.addHistoryCmd(command.getCommandType());
        }
        saveProcessInstance(processInstance);
        this.setSubProcessParam(processInstance);
        createRecoveryWaitingThreadCommand(command, processInstance);
        return null;
    }

    private boolean checkThreadNum(Command command, int validThreadNum) {
        int commandThreadCount = this.workProcessThreadNumCount(command.getProcessDefinitionId());
        return validThreadNum >= commandThreadCount;
L
ligang 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    }

    /**
     * insert one command
     */
    public int createCommand(Command command) {
        int result = 0;
        if (command != null){
            result = commandMapper.insert(command);
        }
        return result;
    }

    /**
     *
     * find one command from queue list
     * @return
     */
    public Command findOneCommand(){
        return commandMapper.queryOneCommand();
    }

    /**
     * check the input command exists in queue list
     * @param command
     * @return
     */
    public Boolean verifyIsNeedCreateCommand(Command command){
        Boolean isNeedCreate = true;
        Map<CommandType,Integer> cmdTypeMap = new HashMap<CommandType,Integer>();
        cmdTypeMap.put(CommandType.REPEAT_RUNNING,1);
        cmdTypeMap.put(CommandType.RECOVER_SUSPENDED_PROCESS,1);
        cmdTypeMap.put(CommandType.START_FAILURE_TASK_PROCESS,1);
        CommandType commandType = command.getCommandType();

        if(cmdTypeMap.containsKey(commandType)){
            JSONObject cmdParamObj = (JSONObject) JSONObject.parse(command.getCommandParam());
            JSONObject tempObj;
            int processInstanceId = cmdParamObj.getInteger(CMDPARAM_RECOVER_PROCESS_ID_STRING);

            List<Command> commands = commandMapper.queryAllCommand();
            //遍历所有命令
            for (Command tmpCommand:commands){
                if(cmdTypeMap.containsKey(tmpCommand.getCommandType())){
                    tempObj = (JSONObject) JSONObject.parse(tmpCommand.getCommandParam());
                    if(tempObj != null && processInstanceId == tempObj.getInteger(CMDPARAM_RECOVER_PROCESS_ID_STRING)){
                        isNeedCreate = false;
                        break;
                    }
                }
            }
        }
        return  isNeedCreate;
    }

    /**
     * find process instance detail by id
     * @param processId
     * @return
     */
    public ProcessInstance findProcessInstanceDetailById(int processId){
        return processInstanceMapper.queryDetailById(processId);
    }

    /**
     * find process instance by id
     * @param processId
     * @return
     */
    public ProcessInstance findProcessInstanceById(int processId){

        return processInstanceMapper.queryById(processId);
    }

    /**
     * find process instance by scheduler time.
     * @param defineId
     * @param scheduleTime
     * @return
     */
    public ProcessInstance findProcessInstanceByScheduleTime(int defineId, Date scheduleTime){

        return processInstanceMapper.queryByScheduleTime(defineId,
279
                DateUtils.dateToString(scheduleTime), 0, null, null);
L
ligang 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    }

    /**
     * find process define by id.
     * @param processDefinitionId
     * @return
     */
    public ProcessDefinition findProcessDefineById(int processDefinitionId) {
        return processDefineMapper.queryByDefineId(processDefinitionId);
    }

    /**
     * delete work process instance by id
     * @param processInstanceId
     * @return
     */
    public int deleteWorkProcessInstanceById(int processInstanceId){
        return processInstanceMapper.delete(processInstanceId);
    }

    /**
     *
     * delete all sub process by parent instance id
     * @return
     */
    public int deleteAllSubWorkProcessByParentId(int processInstanceId){

        List<Integer> subProcessIdList = processInstanceMapper.querySubIdListByParentId(processInstanceId);

        for(Integer subId : subProcessIdList ){
            deleteAllSubWorkProcessByParentId(subId);
            deleteWorkProcessMapByParentId(subId);
            deleteWorkProcessInstanceById(subId);
        }
        return 1;
    }

    /**
     * create process define
     * @param processDefinition
     * @return
     */
    public int createProcessDefine(ProcessDefinition processDefinition){
        int count = 0;
        if(processDefinition != null){
            count = this.processDefineMapper.insert(processDefinition);
        }
        return count;
    }


    /**
     * calculate sub process number in the process define.
     * @param processDefinitionId
     * @return
     */
    private Integer workProcessThreadNumCount(Integer processDefinitionId){
        List<String> ids = new ArrayList<>();
        recurseFindSubProcessId(processDefinitionId, ids);
        return ids.size()+1;
    }

    /**
     * recursive query sub process definition id by parent id.
     * @param parentId
     * @param ids
     */
    public void recurseFindSubProcessId(int parentId, List<String> ids){
        ProcessDefinition processDefinition = processDefineMapper.queryByDefineId(parentId);
        String processDefinitionJson = processDefinition.getProcessDefinitionJson();

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

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

        if (taskNodeList != null && taskNodeList.size() > 0){

            for (TaskNode taskNode : taskNodeList){
                String parameter = taskNode.getParams();
                if (parameter.contains(CMDPARAM_SUB_PROCESS_DEFINE_ID)){
                    SubProcessParameters subProcessParam = JSONObject.parseObject(parameter, SubProcessParameters.class);
                    ids.add(String.valueOf(subProcessParam.getProcessDefinitionId()));
                    recurseFindSubProcessId(subProcessParam.getProcessDefinitionId(),ids);
                }
            }
        }
    }

    /**
     * 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
     * @param originCommand
     * @param processInstance
     */
    public void createRecoveryWaitingThreadCommand(Command originCommand, ProcessInstance processInstance) {

        // sub process doesnot need to create wait command
        if(processInstance.getIsSubProcess() == Flag.YES){
            if(originCommand != null){
                commandMapper.delete(originCommand.getId());
            }
            return;
        }
        Map<String, String> cmdParam = new HashMap<>();
        cmdParam.put(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD, String.valueOf(processInstance.getId()));
        // process instance quit by "waiting thread" state
        if(originCommand == null){
            Command command = new Command(
                    CommandType.RECOVER_WAITTING_THREAD,
                    processInstance.getTaskDependType(),
                    processInstance.getFailureStrategy(),
                    processInstance.getExecutorId(),
                    processInstance.getProcessDefinitionId(),
                    JSONUtils.toJson(cmdParam),
                    processInstance.getWarningType(),
                    processInstance.getWarningGroupId(),
                    processInstance.getScheduleTime(),
                    processInstance.getProcessInstancePriority()
            );
            saveCommand(command);
            return ;
        }

        // update the command time if current command if recover from waiting
        if(originCommand.getCommandType() == CommandType.RECOVER_WAITTING_THREAD){
            originCommand.setUpdateTime(new Date());
            saveCommand(originCommand);
        }else{
            // delete old command and create new waiting thread command
            commandMapper.delete(originCommand.getId());
            originCommand.setId(0);
            originCommand.setCommandType(CommandType.RECOVER_WAITTING_THREAD);
            originCommand.setUpdateTime(new Date());
            originCommand.setCommandParam(JSONUtils.toJson(cmdParam));
            originCommand.setProcessInstancePriority(processInstance.getProcessInstancePriority());
            saveCommand(originCommand);
        }
    }

    /**
     * get schedule time from command
     * @param command
     * @param cmdParam
     * @return
     */
    private Date getScheduleTime(Command command, Map<String, String> cmdParam){
        Date scheduleTime = command.getScheduleTime();
        if(scheduleTime == null){
            if(cmdParam != null && cmdParam.containsKey(CMDPARAM_COMPLEMENT_DATA_START_DATE)){
                scheduleTime = DateUtils.stringToDate(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE));
            }
        }
        return scheduleTime;
    }

    /**
     * generate a new work process instance from command.
     * @param processDefinition
     * @param command
     * @param cmdParam
     * @return
     */
    private ProcessInstance generateNewProcessInstance(ProcessDefinition processDefinition,
                                                       Command command,
                                                       Map<String, String> cmdParam){
        ProcessInstance processInstance = new ProcessInstance(processDefinition);
        processInstance.setState(ExecutionStatus.RUNNING_EXEUTION);
        processInstance.setRecovery(Flag.NO);
        processInstance.setStartTime(new Date());
        processInstance.setRunTimes(1);
        processInstance.setMaxTryTimes(0);
        processInstance.setProcessDefinitionId(command.getProcessDefinitionId());
        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);

        // schedule time
        Date scheduleTime = getScheduleTime(command, cmdParam);
        if(scheduleTime != null){
            processInstance.setScheduleTime(scheduleTime);
        }
        processInstance.setCommandStartTime(command.getStartTime());
        processInstance.setLocations(processDefinition.getLocations());
        processInstance.setConnects(processDefinition.getConnects());
        // curing global params
        processInstance.setGlobalParams(ParameterUtils.curingGlobalParams(
                processDefinition.getGlobalParamMap(),
                processDefinition.getGlobalParamList(),
                getCommandTypeIfComplement(processInstance, command),
                processInstance.getScheduleTime()));

        //copy process define json to process instance
        processInstance.setProcessInstanceJson(processDefinition.getProcessDefinitionJson());
        // set process instance priority
        processInstance.setProcessInstancePriority(command.getProcessInstancePriority());
B
baoliang 已提交
484
        processInstance.setWorkerGroupId(command.getWorkerGroupId());
B
baoliang 已提交
485
        processInstance.setTimeout(processDefinition.getTimeout());
L
ligang 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
        return processInstance;
    }


    /**
     * check command parameters is valid
     * @param command
     * @param cmdParam
     * @return
     */
    private Boolean checkCmdParam(Command command, Map<String, String> cmdParam){
        if(command.getTaskDependType() == TaskDependType.TASK_ONLY || command.getTaskDependType()== TaskDependType.TASK_PRE){
            if(cmdParam == null
                    || !cmdParam.containsKey(Constants.CMDPARAM_START_NODE_NAMES)
                    || cmdParam.get(Constants.CMDPARAM_START_NODE_NAMES).isEmpty()){
                logger.error(String.format("command node depend type is %s, but start nodes is null ", command.getTaskDependType().toString()));
                return false;
            }
        }
        return true;
    }

    /**
     * construct process instance according to one command.
     * @param command
     * @param host
     * @return
     */
    private ProcessInstance constructProcessInstance(Command command, String host){

        ProcessInstance processInstance = null;
        CommandType commandType = command.getCommandType();
        Map<String, String> cmdParam = JSONUtils.toMap(command.getCommandParam());

        ProcessDefinition processDefinition = null;
        if(command.getProcessDefinitionId() != 0){
            processDefinition = processDefineMapper.queryByDefineId(command.getProcessDefinitionId());
            if(processDefinition == null){
                logger.error(String.format("cannot find the work process define! define id : %d", command.getProcessDefinitionId()));
                return null;
            }
        }

        if(cmdParam != null ){
            Integer processInstanceId = 0;
            // recover from failure or pause tasks
            if(cmdParam.containsKey(Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING)) {
                String processId = cmdParam.get(Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING);
                processInstanceId = Integer.parseInt(processId);
                if (processInstanceId == 0) {
                    logger.error("command parameter is error, [ ProcessInstanceId ] is 0");
                    return null;
                }
            }else if(cmdParam.containsKey(Constants.CMDPARAM_SUB_PROCESS)){
                // sub process map
                String pId = cmdParam.get(Constants.CMDPARAM_SUB_PROCESS);
                processInstanceId = Integer.parseInt(pId);
            }else if(cmdParam.containsKey(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD)){
                // waiting thread command
                String pId = cmdParam.get(Constants.CMDPARAM_RECOVERY_WAITTING_THREAD);
                processInstanceId = Integer.parseInt(pId);
            }
            if(processInstanceId ==0){
                processInstance = generateNewProcessInstance(processDefinition, command, cmdParam);
            }else{
                processInstance = this.findProcessInstanceDetailById(processInstanceId);
            }
            processDefinition = processDefineMapper.queryByDefineId(processInstance.getProcessDefinitionId());
            processInstance.setProcessDefinition(processDefinition);

            //reset command parameter
            if(processInstance.getCommandParam() != null){
                Map<String, String> processCmdParam = JSONUtils.toMap(processInstance.getCommandParam());
                for(String key : processCmdParam.keySet()){
                    if(!cmdParam.containsKey(key)){
                        cmdParam.put(key,processCmdParam.get(key));
                    }
                }
            }
            // reset command parameter if sub process
            if(cmdParam.containsKey(Constants.CMDPARAM_SUB_PROCESS)){
                processInstance.setCommandParam(command.getCommandParam());
            }
        }else{
            // generate one new process instance
            processInstance = generateNewProcessInstance(processDefinition, command, cmdParam);
        }
        if(!checkCmdParam(command, cmdParam)){
            logger.error("command parameter check failed!");
            return null;
        }

        if(command.getScheduleTime() != null){
            processInstance.setScheduleTime(command.getScheduleTime());
        }
        processInstance.setHost(host);
        int runTime = processInstance.getRunTimes();
        switch (commandType){
            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);
                List<Integer> killedList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.KILL);
                cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING);

                failedList.addAll(killedList);
                for(Integer taskId : failedList){
                    initTaskInstance(this.findTaskInstanceById(taskId));
                }
                cmdParam.put(Constants.CMDPARAM_RECOVERY_START_NODE_STRING,
                        String.join(Constants.COMMA, convertIntListToString(failedList)));
                processInstance.setCommandParam(JSONUtils.toJson(cmdParam));
                processInstance.setRunTimes(runTime +1 );
                break;
            case START_CURRENT_TASK_PROCESS:
                break;
            case RECOVER_WAITTING_THREAD:
                break;
            case RECOVER_SUSPENDED_PROCESS:
                // find pause tasks and init task's state
                cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING);
                List<Integer> suspendedNodeList = this.findTaskIdByInstanceState(processInstance.getId(), ExecutionStatus.PAUSE);
                for(Integer taskId : suspendedNodeList){
                    // 把暂停状态初始化
                    initTaskInstance(this.findTaskInstanceById(taskId));
                }
                cmdParam.put(Constants.CMDPARAM_RECOVERY_START_NODE_STRING, String.join(",", convertIntListToString(suspendedNodeList)));
                processInstance.setCommandParam(JSONUtils.toJson(cmdParam));
                processInstance.setRunTimes(runTime +1);
                break;
            case RECOVER_TOLERANCE_FAULT_PROCESS:
                // recover tolerance fault process
                processInstance.setRecovery(Flag.YES);
                break;
            case COMPLEMENT_DATA:
                // delete all the valid tasks when complement data
                List<TaskInstance> taskInstanceList = this.findValidTaskListByProcessId(processInstance.getId());
                for(TaskInstance taskInstance : taskInstanceList){
                    taskInstance.setFlag(Flag.NO);
                    this.updateTaskInstance(taskInstance);
                }
                break;
            case REPEAT_RUNNING:
                // delete the recover task names from command parameter
                if(cmdParam.containsKey(Constants.CMDPARAM_RECOVERY_START_NODE_STRING)){
                    cmdParam.remove(Constants.CMDPARAM_RECOVERY_START_NODE_STRING);
                    processInstance.setCommandParam(JSONUtils.toJson(cmdParam));
                }
                // delete all the valid tasks when repeat running
                List<TaskInstance> validTaskList = findValidTaskListByProcessId(processInstance.getId());
                for(TaskInstance taskInstance : validTaskList){
                    taskInstance.setFlag(Flag.NO);
                    updateTaskInstance(taskInstance);
                }
                processInstance.setStartTime(new Date());
642
                processInstance.setEndTime(null);
L
ligang 已提交
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
                processInstance.setRunTimes(runTime +1);
                initComplementDataParam(processDefinition, processInstance, cmdParam);
                break;
            case SCHEDULER:
                break;
            default:
                break;
        }
        processInstance.setState(ExecutionStatus.RUNNING_EXEUTION);
        return processInstance;
    }

    /**
     * return complement data if the process start with complement data
     */
    private CommandType getCommandTypeIfComplement(ProcessInstance processInstance, Command command){
        if(CommandType.COMPLEMENT_DATA == processInstance.getCmdTypeIfComplement()){
            return CommandType.COMPLEMENT_DATA;
        }else{
            return command.getCommandType();
        }
    }

    /**
     * initialize complement data parameters
     * @param processDefinition
     * @param processInstance
     * @param cmdParam
     */
    private void initComplementDataParam(ProcessDefinition processDefinition, ProcessInstance processInstance, Map<String, String> cmdParam) {
        if(!processInstance.isComplementData()){
            return;
        }

        Date startComplementTime = DateUtils.parse(cmdParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE),
                YYYY_MM_DD_HH_MM_SS);
        processInstance.setScheduleTime(startComplementTime);
        processInstance.setGlobalParams(ParameterUtils.curingGlobalParams(
                processDefinition.getGlobalParamMap(),
                processDefinition.getGlobalParamList(),
                CommandType.COMPLEMENT_DATA, processInstance.getScheduleTime()));

    }

    /**
     * set sub work process parameters.
     * handle sub work process instance, update relation table and command parameters
     * set sub work process flag, extends parent work process command parameters.
     */
    public ProcessInstance setSubProcessParam(ProcessInstance processInstance){
        String cmdParam = processInstance.getCommandParam();
        if(StringUtils.isEmpty(cmdParam)){
            return processInstance;
        }
        Map<String, String> paramMap = JSONUtils.toMap(cmdParam);
        // write sub process id into cmd param.
        if(paramMap.containsKey(CMDPARAM_SUB_PROCESS)
                && CMDPARAM_EMPTY_SUB_PROCESS.equals(paramMap.get(CMDPARAM_SUB_PROCESS))){
            paramMap.remove(CMDPARAM_SUB_PROCESS);
            paramMap.put(CMDPARAM_SUB_PROCESS, String.valueOf(processInstance.getId()));
            processInstance.setCommandParam(JSONUtils.toJson(paramMap));
            processInstance.setIsSubProcess(Flag.YES);
B
baoliang 已提交
705
            this.saveProcessInstance(processInstance);
L
ligang 已提交
706 707 708 709 710 711 712
        }
        // copy parent instance user def params to sub process..
        String parentInstanceId = paramMap.get(CMDPARAM_SUB_PROCESS_PARENT_INSTANCE_ID);
        if(StringUtils.isNotEmpty(parentInstanceId)){
            ProcessInstance parentInstance = findProcessInstanceDetailById(Integer.parseInt(parentInstanceId));
            if(parentInstance != null){
                processInstance.setGlobalParams(parentInstance.getGlobalParams());
B
baoliang 已提交
713
                this.saveProcessInstance(processInstance);
L
ligang 已提交
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 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 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
            }else{
                logger.error("sub process command params error, cannot find parent instance: {} ", cmdParam);
            }
        }
        ProcessInstanceMap processInstanceMap = JSONUtils.parseObject(cmdParam, ProcessInstanceMap.class);
        if(processInstanceMap == null || processInstanceMap.getParentProcessInstanceId() == 0){
            return processInstance;
        }
        // update sub process id to process map table
        processInstanceMap.setProcessInstanceId(processInstance.getId());

        this.updateWorkProcessInstanceMap(processInstanceMap);
        return processInstance;
    }

    /**
     * initialize task instance
     * @param taskInstance
     */
    private void initTaskInstance(TaskInstance taskInstance){
        if(taskInstance.getState().typeIsFailure() && !taskInstance.isSubProcess()){
            taskInstance.setFlag(Flag.NO);
            updateTaskInstance(taskInstance);
        }else{
            taskInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS);
            updateTaskInstance(taskInstance);
        }
    }

    /**
     *  submit task to mysql and task queue
     *  submit sub process to command
     * @param taskInstance
     * @return
     */
    @Transactional(value = "TransactionManager",rollbackFor = Exception.class)
    public TaskInstance submitTask(TaskInstance taskInstance, ProcessInstance processInstance){
        logger.info("start submit task : {}, instance id:{}, state: {}, ",
                taskInstance.getName(), processInstance.getId(), processInstance.getState() );
        processInstance = this.findProcessInstanceDetailById(processInstance.getId());
        //submit to mysql
        TaskInstance task= submitTaskInstanceToMysql(taskInstance, processInstance);
        if(task.isSubProcess() && !task.getState().typeIsFinished()){
            ProcessInstanceMap processInstanceMap = setProcessInstanceMap(processInstance, task);

            TaskNode taskNode = JSONUtils.parseObject(task.getTaskJson(), TaskNode.class);
            Map<String, String> subProcessParam = JSONUtils.toMap(taskNode.getParams());
            Integer defineId = Integer.parseInt(subProcessParam.get(Constants.CMDPARAM_SUB_PROCESS_DEFINE_ID));
            createSubWorkProcessCommand(processInstance, processInstanceMap, defineId, task);
        }else if(!task.getState().typeIsFinished()){
            //submit to task queue
            task.setProcessInstancePriority(processInstance.getProcessInstancePriority());
            submitTaskToQueue(task);
        }
        logger.info("submit task :{} state:{} complete, instance id:{} state: {}  ",
                taskInstance.getName(), task.getState(), processInstance.getId(), processInstance.getState());
        return task;
    }

    /**
     * set work process instance map
     * @param parentInstance
     * @param parentTask
     * @return
     */
    private ProcessInstanceMap setProcessInstanceMap(ProcessInstance parentInstance, TaskInstance parentTask){
        ProcessInstanceMap processMap = findWorkProcessMapByParent(parentInstance.getId(), parentTask.getId());
        if(processMap != null){
            return processMap;
        }else if(parentInstance.getCommandType() == CommandType.REPEAT_RUNNING
                || parentInstance.isComplementData()){
            // update current task id to map
            // repeat running  does not generate new sub process instance
            processMap = findPreviousTaskProcessMap(parentInstance, parentTask);
            if(processMap!= null){
                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.
     * @param parentProcessInstance
     * @param parentTask
     * @return
     */
    private ProcessInstanceMap findPreviousTaskProcessMap(ProcessInstance parentProcessInstance,
                                                          TaskInstance parentTask) {

        Integer preTaskId = 0;
        List<TaskInstance> preTaskList = this.findPreviousTaskListByWorkProcessId(parentProcessInstance.getId());
        for(TaskInstance task : preTaskList){
            if(task.getName().equals(parentTask.getName())){
                preTaskId = task.getId();
                ProcessInstanceMap map = findWorkProcessMapByParent(parentProcessInstance.getId(), preTaskId);
                if(map!=null){
                    return map;
                }
            }
        }
        logger.info("sub process instance is not found,parent task:{},parent instance:{}",
                parentTask.getId(), parentProcessInstance.getId());
        return null;
    }

    /**
     * create sub work process command
     * @param parentProcessInstance
     * @param instanceMap
     * @param childDefineId
     * @param task
     */
    private void createSubWorkProcessCommand(ProcessInstance parentProcessInstance,
                                             ProcessInstanceMap instanceMap,
                                             Integer childDefineId, TaskInstance task){
        ProcessInstance childInstance = findSubProcessInstance(parentProcessInstance.getId(), task.getId());

        CommandType fatherType = parentProcessInstance.getCommandType();
        CommandType commandType = fatherType;
        if(childInstance == null || commandType == CommandType.REPEAT_RUNNING){
            String fatherHistoryCommand = parentProcessInstance.getHistoryCmd();
            // sub process must begin with schedule/complement data
            // if father begin with scheduler/complement data
            if(fatherHistoryCommand.startsWith(CommandType.SCHEDULER.toString()) ||
                    fatherHistoryCommand.startsWith(CommandType.COMPLEMENT_DATA.toString())){
                commandType = CommandType.valueOf(fatherHistoryCommand.split(Constants.COMMA)[0]);
            }
        }

        if(childInstance != null){
            childInstance.setState(ExecutionStatus.SUBMITTED_SUCCESS);
            updateProcessInstance(childInstance);
        }
        // set sub work process command
        String processMapStr = JSONUtils.toJson(instanceMap);
        Map<String, String> cmdParam = JSONUtils.toMap(processMapStr);

        if(commandType == CommandType.COMPLEMENT_DATA ||
                (childInstance != null && childInstance.isComplementData())){
            Map<String, String> parentParam = JSONUtils.toMap(parentProcessInstance.getCommandParam());
            String endTime =  parentParam.get(CMDPARAM_COMPLEMENT_DATA_END_DATE);
            String startTime =  parentParam.get(CMDPARAM_COMPLEMENT_DATA_START_DATE);
            cmdParam.put(CMDPARAM_COMPLEMENT_DATA_END_DATE, endTime);
            cmdParam.put(CMDPARAM_COMPLEMENT_DATA_START_DATE, startTime);
            processMapStr = JSONUtils.toJson(cmdParam);
        }
        Command command = new Command();
        command.setWarningType(parentProcessInstance.getWarningType());
        command.setWarningGroupId(parentProcessInstance.getWarningGroupId());
        command.setFailureStrategy(parentProcessInstance.getFailureStrategy());
        command.setProcessDefinitionId(childDefineId);
        command.setScheduleTime(parentProcessInstance.getScheduleTime());
        command.setExecutorId(parentProcessInstance.getExecutorId());
        command.setCommandParam(processMapStr);
        command.setCommandType(commandType);
        command.setProcessInstancePriority(parentProcessInstance.getProcessInstancePriority());
        createCommand(command);
        logger.info("sub process command created: {} ", command.toString());
    }

    /**
     * submit task to mysql
     * @param taskInstance
     * @return
     */
    public TaskInstance submitTaskInstanceToMysql(TaskInstance taskInstance, ProcessInstance processInstance){
        ExecutionStatus processInstanceState = processInstance.getState();

        if(taskInstance.getState().typeIsFailure()){
            if(taskInstance.isSubProcess()){
                taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1 );
            }else {

                if( processInstanceState != ExecutionStatus.READY_STOP
                        && processInstanceState != ExecutionStatus.READY_PAUSE){
                    // failure task set invalid
                    taskInstance.setFlag(Flag.NO);
                    updateTaskInstance(taskInstance);
                    // crate new task instance
                    taskInstance.setRetryTimes(taskInstance.getRetryTimes() + 1 );
                    taskInstance.setFlag(Flag.YES);
                    taskInstance.setHost(null);
                    taskInstance.setId(0);
                }
            }
        }
        taskInstance.setProcessInstancePriority(processInstance.getProcessInstancePriority());
        taskInstance.setState(getSubmitTaskState(taskInstance, processInstanceState));
        taskInstance.setSubmitTime(new Date());
        saveTaskInstance(taskInstance);
        return taskInstance;
    }

    /**
     *  submit task to queue
     * @param task
     */
    public Boolean submitTaskToQueue(TaskInstance task) {

        try{
            // task cannot submit when running
            if(task.getState() == ExecutionStatus.RUNNING_EXEUTION){
                logger.info(String.format("submit to task queue, but task [%s] state already be running. ", task.getName()));
                return true;
            }
            if(checkTaskExistsInTaskQueue(task)){
                logger.info(String.format("submit to task queue, but task [%s] already exists in the queue.", task.getName()));
                return true;
            }
            logger.info("task ready to queue: {}" , task);
            taskQueue.add(SCHEDULER_TASKS_QUEUE, taskZkInfo(task));
            logger.info(String.format("master insert into queue success, task : %s", task.getName()) );
            return true;
        }catch (Exception e){
            logger.error("submit task to queue Exception: ", e);
            logger.error("task queue error : %s", JSONUtils.toJson(task));
            return false;

        }
    }

    /**
     * ${processInstancePriority}_${processInstanceId}_${taskInstancePriority}_${taskId}
     *
     * The tasks with the highest priority are selected by comparing the priorities of the above four levels from high to low.
     *
     * 流程实例优先级_流程实例id_任务优先级_任务id       high <- low
     *
     * @param task
     * @return
     */
    private String taskZkInfo(TaskInstance task) {
        return String.valueOf(task.getProcessInstancePriority().ordinal()) + Constants.UNDERLINE + task.getProcessInstanceId() + Constants.UNDERLINE + task.getTaskInstancePriority().ordinal() + Constants.UNDERLINE + task.getId();
    }

    /**
     * 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
     *
     * @param taskInstance
     * @param processInstanceState
     * @return
     */
    public ExecutionStatus getSubmitTaskState(TaskInstance taskInstance, ExecutionStatus processInstanceState){
        ExecutionStatus state = taskInstance.getState();
        if(
                // running or killed
                // the task already exists in task queue
                // return state
                state == ExecutionStatus.RUNNING_EXEUTION
                        || state == ExecutionStatus.KILL
                        || checkTaskExistsInTaskQueue(taskInstance)
                ){
            return state;
        }
        //return pasue /stop if process instance state is ready pause / stop
        // or return submit success
        if( processInstanceState == ExecutionStatus.READY_PAUSE){
            state = ExecutionStatus.PAUSE;
        }else if(processInstanceState == ExecutionStatus.READY_STOP) {
            state = ExecutionStatus.KILL;
        }else{
            state = ExecutionStatus.SUBMITTED_SUCCESS;
        }
        return state;
    }

    /**
     * check the task instance existing in queue
     * @return
     */
    public boolean checkTaskExistsInTaskQueue(TaskInstance task){
        if(task.isSubProcess()){
            return false;
        }

        String taskZkInfo = taskZkInfo(task);

        return taskQueue.checkTaskExists(SCHEDULER_TASKS_QUEUE, taskZkInfo);
    }

    /**
     * create a new process instance
     * @param processInstance
     */
    public void createProcessInstance(ProcessInstance processInstance){

        if (processInstance != null){
            processInstanceMapper.insert(processInstance);
        }
    }

    /**
     * insert or update work process instance to data base
     * @param workProcessInstance
     */
    public void saveProcessInstance(ProcessInstance workProcessInstance){

        if (workProcessInstance == null){
            logger.error("save error, process instance is null!");
            return ;
        }
        //创建流程实例
        if(workProcessInstance.getId() != 0){
            processInstanceMapper.update(workProcessInstance);
        }else{
            createProcessInstance(workProcessInstance);
        }
    }

    /**
     * insert or update command
     * @param command
     * @return
     */
    public int saveCommand(Command command){
        if(command.getId() != 0){
            return commandMapper.update(command);
        }else{
            return commandMapper.insert(command);
        }
    }

    /**
     *  insert or update task instance
     * @param taskInstance
     * @return
     */
    public boolean saveTaskInstance(TaskInstance taskInstance){
        if(taskInstance.getId() != 0){
            return updateTaskInstance(taskInstance);
        }else{
            return createTaskInstance(taskInstance);
        }
    }

    /**
     * insert task instance
     * @param taskInstance
     * @return
     */
    public boolean createTaskInstance(TaskInstance taskInstance) {
        int count = taskInstanceMapper.insert(taskInstance);
        return count > 0;
    }

    /**
     * update task instance
     * @param taskInstance
     * @return
     */
    public boolean updateTaskInstance(TaskInstance taskInstance){
        int count = taskInstanceMapper.update(taskInstance);
        return count > 0;
    }
    /**
     * delete a command by id
     * @param id
     */
    public void delCommandByid(int id) {
        commandMapper.delete(id);
    }

    public TaskInstance findTaskInstanceById(Integer taskId){
        return taskInstanceMapper.queryById(taskId);
    }

    /**
     * get id list by task state
     * @param instanceId
     * @param state
     * @return
     */
    public List<Integer> findTaskIdByInstanceState(int instanceId, ExecutionStatus state){
        return taskInstanceMapper.queryTaskByProcessIdAndState(instanceId, state.ordinal());
    }

    /**
     *
     * find valid task list by process definition id
     * @param processInstanceId
     * @return
     */
    public List<TaskInstance> findValidTaskListByProcessId(Integer processInstanceId){
         return taskInstanceMapper.findValidTaskListByProcessId(processInstanceId, Flag.YES);
    }

    /**
     * find previous task list by work process id
     * @param workProcessInstanceId
     * @return
     */
    public List<TaskInstance> findPreviousTaskListByWorkProcessId(Integer workProcessInstanceId){
        return taskInstanceMapper.findValidTaskListByProcessId(workProcessInstanceId, Flag.NO);
    }

    /**
     * update work process instance map
     * @param processInstanceMap
     * @return
     */
    public int updateWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap){
        return processInstanceMapMapper.update(processInstanceMap);
    }


    /**
     * create work process instance map
     * @param processInstanceMap
     * @return
     */
    public int createWorkProcessInstanceMap(ProcessInstanceMap processInstanceMap){
        Integer count = 0;
        if(processInstanceMap !=null){
            return  processInstanceMapMapper.insert(processInstanceMap);
        }
        return count;
    }

    /**
     * find work process map by parent process id and parent task id.
     * @param parentWorkProcessId
     * @param parentTaskId
     * @return
     */
    public ProcessInstanceMap findWorkProcessMapByParent(Integer parentWorkProcessId, Integer parentTaskId){
        return processInstanceMapMapper.queryByParentId(parentWorkProcessId, parentTaskId);
    }

    /**
     * delete work process map by parent process id
     * @param parentWorkProcessId
     * @return
     */
    public int deleteWorkProcessMapByParentId(int parentWorkProcessId){
        return processInstanceMapMapper.deleteByParentProcessId(parentWorkProcessId);

    }

    public ProcessInstance findSubProcessInstance(Integer parentProcessId, Integer parentTaskId){
        ProcessInstance processInstance = null;
        ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryByParentId(parentProcessId, parentTaskId);
        if(processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0){
            return processInstance;
        }
        processInstance = findProcessInstanceById(processInstanceMap.getProcessInstanceId());
        return processInstance;
    }
    public ProcessInstance findParentProcessInstance(Integer subProcessId) {
        ProcessInstance processInstance = null;
        ProcessInstanceMap processInstanceMap = processInstanceMapMapper.queryBySubProcessId(subProcessId);
        if(processInstanceMap == null || processInstanceMap.getProcessInstanceId() == 0){
            return processInstance;
        }
        processInstance = findProcessInstanceById(processInstanceMap.getParentProcessInstanceId());
        return processInstance;
    }



    /**
     * change task state
     * @param state
     * @param startTime
     * @param host
     * @param executePath
     */
    public void changeTaskState(ExecutionStatus state, Date startTime, String host,
                                String executePath,
                                String logPath,
                                int taskInstId) {

        TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId);
        taskInstance.setState(state);
        taskInstance.setStartTime(startTime);
        taskInstance.setHost(host);
        taskInstance.setExecutePath(executePath);
        taskInstance.setLogPath(logPath);
        saveTaskInstance(taskInstance);
    }

    /**
     * update process instance
     * @param instance
     * @return
     */
    public int updateProcessInstance(ProcessInstance instance){
        return processInstanceMapper.update(instance);
    }

    /**
     * update the process instance
     * @param  processInstanceId
     * @param processJson
     * @param globalParams
     * @param scheduleTime
     * @param flag
     * @param locations
     * @param connects
     * @return
     */
    public int updateProcessInstance(Integer processInstanceId, String processJson,
                                     String globalParams, Date scheduleTime, Flag flag,
                                     String locations, String connects){
1230
        return processInstanceMapper.updateProcessInstance(processInstanceId, processJson,
L
ligang 已提交
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
                globalParams, scheduleTime, locations, connects, flag);
    }

    /**
     * change task state
     * @param state
     * @param endTime
     */
    public void changeTaskState(ExecutionStatus state,
                                Date endTime,
                                int taskInstId) {
        TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId);
        taskInstance.setState(state);
        taskInstance.setEndTime(endTime);
        saveTaskInstance(taskInstance);
    }

    /**
     * convert integer list to string list
     * @param intList
     * @return
     */
    public List<String> convertIntListToString(List<Integer> intList){
        if(intList == null){
            return new ArrayList<>();
        }
        List<String> result = new ArrayList<String>(intList.size());
        for(Integer intVar : intList){
            result.add(String.valueOf(intVar));
        }
        return result;
    }

    /**
     * set task
     * 根据任务实例id设置pid
     * @param taskInstId
     * @param pid
     */
    public void updatePidByTaskInstId(int taskInstId, int pid) {
        TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId);
        taskInstance.setPid(pid);
        taskInstance.setAppLink("");
        saveTaskInstance(taskInstance);
    }

    /**
     * update pid and app links field by task instance id
     * @param taskInstId
     * @param pid
     */
    public void updatePidByTaskInstId(int taskInstId, int pid,String appLinks) {

        TaskInstance taskInstance = taskInstanceMapper.queryById(taskInstId);
        taskInstance.setPid(pid);
        taskInstance.setAppLink(appLinks);
        saveTaskInstance(taskInstance);
    }

    /**
     * query  ProcessDefinition by name
     *
     * @see ProcessDefinition
     */
    public ProcessDefinition findProcessDefineByName(int projectId, String name) {
        ProcessDefinition projectFlow = processDefineMapper.queryByDefineName(projectId, name);
        return projectFlow;
    }

    /**
     * query Schedule <p>
     *
     * @see Schedule
     */
    public Schedule querySchedule(int id) {
        return scheduleMapper.queryById(id);
    }

B
baoliang 已提交
1309
    public List<ProcessInstance> queryNeedFailoverProcessInstances(String host){
L
ligang 已提交
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        return processInstanceMapper.queryByHostAndStatus(host, stateArray);
    }


    /**
     * update host null
     * @param host
     * @return
     */
    public int updateNeddFailoverProcessInstances(String host){
        return processInstanceMapper.setFailoverByHostAndStateArray(host, stateArray);
    }

    /**
     * process need failover process instance
     * @param processInstance
     */
    @Transactional(value = "TransactionManager",rollbackFor = Exception.class)
    public void processNeedFailoverProcessInstances(ProcessInstance processInstance){


        //1 update processInstance host is null
        processInstance.setHost("null");
        processInstanceMapper.update(processInstance);

        //2 insert into recover command
        Command cmd = new Command();
        cmd.setProcessDefinitionId(processInstance.getProcessDefinitionId());
        cmd.setCommandParam(String.format("{\"%s\":%d}", Constants.CMDPARAM_RECOVER_PROCESS_ID_STRING, processInstance.getId()));
        cmd.setExecutorId(processInstance.getExecutorId());
        cmd.setCommandType(CommandType.RECOVER_TOLERANCE_FAULT_PROCESS);
        createCommand(cmd);

    }

    /**
     * query all need failover task instances by host
     * @param host
     * @return
     */
    public List<TaskInstance> queryNeedFailoverTaskInstances(String host){
        return taskInstanceMapper.queryByHostAndStatus(host,stateArray);
    }

    /**
     * update host null
     * @param host
     * @return
     */
    public int updateNeedFailoverTaskInstances(String host){
        return taskInstanceMapper.setFailoverByHostAndStateArray(host, stateArray);
    }

    /**
     * find data source by id
     * @param id
     * @return
     */
    public DataSource findDataSourceById(int id){
        return dataSourceMapper.queryById(id);
    }


    /**
     * update process instance state by id
     * @param processInstanceId
     * @param executionStatus
     * @return
     */
    public int updateProcessInstanceState(Integer processInstanceId, ExecutionStatus executionStatus) {
        return processInstanceMapper.updateState(processInstanceId, executionStatus);

    }

    /**
     * find process instance by the task id
     * @param taskId
     * @return
     */
    public ProcessInstance findProcessInstanceByTaskId(int taskId){
        return processInstanceMapper.queryByTaskId(taskId);
    }

    /**
     * find udf function list by id list string
     * @param ids
     * @return
     */
    public List<UdfFunc> queryUdfFunListByids(String ids){
        return udfFuncMapper.queryUdfByIdStr(ids);
    }

    /**
     * find tenant code by resource name
     * @param resName
     * @return
     */
    public String queryTenantCodeByResName(String resName){
        return resourceMapper.queryTenantCodeByResourceName(resName);
    }

    /**
     * find schedule list by process define id.
     * @param ids
     * @return
     */
    public List<Schedule> selectAllByProcessDefineId(int[] ids){
        return scheduleMapper.selectAllByProcessDefineArray(ids);
    }

    /**
     * get dependency cycle by work process define id and scheduler fire time
     *
     * @param masterId
     * @param processDefinitionId
     * @param scheduledFireTime 任务调度预计触发的时间
     * @return
     * @throws Exception
     */
    public CycleDependency getCycleDependency(int masterId, int processDefinitionId, Date scheduledFireTime) throws Exception {
        List<CycleDependency> list = getCycleDependencies(masterId,new int[]{processDefinitionId},scheduledFireTime);
        return list.size()>0 ? list.get(0) : null;

    }

    /**
     *
     * get dependency cycle list by work process define id list and scheduler fire time
     * @param masterId
     * @param ids
     * @param scheduledFireTime 任务调度预计触发的时间
     * @return
     * @throws Exception
     */
    public List<CycleDependency> getCycleDependencies(int masterId,int[] ids,Date scheduledFireTime) throws Exception {
        List<CycleDependency> cycleDependencyList =  new ArrayList<CycleDependency>();
        if(ArrayUtils.isEmpty(ids)){
            logger.warn("ids[] is empty!is invalid!");
            return cycleDependencyList;
        }
        if(scheduledFireTime == null){
            logger.warn("scheduledFireTime is null!is invalid!");
            return cycleDependencyList;
        }


        String strCrontab = "";
        CronExpression depCronExpression;
        Cron depCron;
        List<Date> list;
        List<Schedule> schedules = this.selectAllByProcessDefineId(ids);
        // 遍历所有的调度信息
        for(Schedule depSchedule:schedules){
            strCrontab = depSchedule.getCrontab();
            depCronExpression = CronUtils.parse2CronExpression(strCrontab);
            depCron = CronUtils.parse2Cron(strCrontab);
            CycleEnum cycleEnum = CronUtils.getMiniCycle(depCron);
            if(cycleEnum == null){
                logger.error("{} is not valid",strCrontab);
                continue;
            }
            Calendar calendar = Calendar.getInstance();
            switch (cycleEnum){
                /*case MINUTE:
                    calendar.add(Calendar.MINUTE,-61);*/
                case HOUR:
                    calendar.add(Calendar.HOUR,-25);
                    break;
                case DAY:
                    calendar.add(Calendar.DATE,-32);
                    break;
                case WEEK:
                    calendar.add(Calendar.DATE,-32);
                    break;
                case MONTH:
                    calendar.add(Calendar.MONTH,-13);
                    break;
                default:
                    logger.warn("Dependent process definition's  cycleEnum is {},not support!!", cycleEnum.name());
                    continue;
            }
            Date start = calendar.getTime();

            if(depSchedule.getProcessDefinitionId() == masterId){
                list = CronUtils.getSelfFireDateList(start, scheduledFireTime, depCronExpression);
            }else {
                list = CronUtils.getFireDateList(start, scheduledFireTime, depCronExpression);
            }
            if(list.size()>=1){
                start = list.get(list.size()-1);
                CycleDependency dependency = new CycleDependency(depSchedule.getProcessDefinitionId(),start, CronUtils.getExpirationTime(start, cycleEnum), cycleEnum);
                cycleDependencyList.add(dependency);
            }

        }
        return cycleDependencyList;
    }

    /**
     * find process instance by time interval
     * @param defineId
     * @param startTime
     * @param endTime
     * @return
     */
    public ProcessInstance findProcessInstanceByTimeInterval(int defineId, Date startTime, Date endTime, int excludeId) {

        return processInstanceMapper.queryByScheduleTime(defineId, null, excludeId,
                DateUtils.dateToString(startTime), DateUtils.dateToString(endTime));
    }

    public void selfFaultTolerant(int state){
        List<ProcessInstance> processInstanceList = processInstanceMapper.listByStatus(new int[]{state});
        for (ProcessInstance processInstance:processInstanceList){
            selfFaultTolerant(processInstance);
        }

    }

1529 1530 1531 1532 1533 1534 1535 1536
    public void selfFaultTolerant(int ... states){
        List<ProcessInstance> processInstanceList = processInstanceMapper.listByStatus(states);
        for (ProcessInstance processInstance:processInstanceList){
            selfFaultTolerant(processInstance);
        }

    }

L
ligang 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
    @Transactional(value = "TransactionManager",rollbackFor = Exception.class)
    public void selfFaultTolerant(ProcessInstance processInstance){

        processInstance.setState(ExecutionStatus.FAILURE);
        processInstanceMapper.update(processInstance);
        // insert to command

        Command command = new Command();
        command.setCommandType(CommandType.START_FAILURE_TASK_PROCESS);
        command.setProcessDefinitionId(processInstance.getProcessDefinitionId());
        command.setCommandParam(String.format("{\"%s\":%d}",
                CMDPARAM_RECOVER_PROCESS_ID_STRING, processInstance.getId()));


        command.setExecutorId(processInstance.getExecutorId());
        command.setProcessInstancePriority(processInstance.getProcessInstancePriority());

        createCommand(command);

    }

    /**
     * find last scheduler process instance in the date interval
     * @param definitionId
     * @param dateInterval
     * @return
     */
    public ProcessInstance findLastSchedulerProcessInterval(int definitionId, DateInterval dateInterval) {
        return processInstanceMapper.queryLastSchedulerProcess(definitionId,
                DateUtils.dateToString(dateInterval.getStartTime()),
                DateUtils.dateToString(dateInterval.getEndTime()));
    }

    public ProcessInstance findLastManualProcessInterval(int definitionId, DateInterval dateInterval) {
        return processInstanceMapper.queryLastManualProcess(definitionId,
                DateUtils.dateToString(dateInterval.getStartTime()),
                DateUtils.dateToString(dateInterval.getEndTime()));
    }

    public ProcessInstance findLastRunningProcess(int definitionId, DateInterval dateInterval) {
        return processInstanceMapper.queryLastRunningProcess(definitionId,
                DateUtils.dateToString(dateInterval.getStartTime()),
                DateUtils.dateToString(dateInterval.getEndTime()),
                stateArray);
    }
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

    /**
     *  query user queue by process instance id
     * @param processInstanceId
     * @return
     */
    public String queryQueueByProcessInstanceId(int processInstanceId){
        return userMapper.queryQueueByProcessInstanceId(processInstanceId);
    }

B
baoliang 已提交
1592 1593 1594 1595 1596 1597 1598 1599 1600
    /**
     * query worker group by id
     * @param workerGroupId
     * @return
     */
    public WorkerGroup queryWorkerGroupById(int workerGroupId){
        return workerGroupMapper.queryById(workerGroupId);
    }

1601 1602


L
ligang 已提交
1603
}