Determines the new flow status based on the current flow status and new job status
@param jobExecutionStatus job status
@param currentFlowExecutionStatus current flow status
@return updated flow status
332206
static ExecutionStatus updatedFlowExecutionStatus(ExecutionStatus jobExecutionStatus,
      ExecutionStatus currentFlowExecutionStatus) {

    // if any job failed or flow has failed then return failed status
    if (currentFlowExecutionStatus == ExecutionStatus.FAILED ||
        jobExecutionStatus == ExecutionStatus.FAILED) {
      return ExecutionStatus.FAILED;
    }

    // if any job is cancelled or flow has failed then return failed status
    if (currentFlowExecutionStatus == ExecutionStatus.CANCELLED ||
        jobExecutionStatus == ExecutionStatus.CANCELLED) {
      return ExecutionStatus.CANCELLED;
    }

    if (currentFlowExecutionStatus == ExecutionStatus.RUNNING ||
        jobExecutionStatus == ExecutionStatus.RUNNING ||
        jobExecutionStatus == ExecutionStatus.ORCHESTRATED ||
        jobExecutionStatus == ExecutionStatus.COMPILED) {
      return ExecutionStatus.RUNNING;
    }

    return currentFlowExecutionStatus;
  }
1001949
private void createDoLogoutActionState(final Flow flow) {
        val actionState = createActionState(flow, CasWebflowConstants.STATE_ID_DO_LOGOUT, createEvaluateAction("logoutAction"));
        createTransitionForState(actionState, CasWebflowConstants.TRANSITION_ID_FINISH, CasWebflowConstants.STATE_ID_FINISH_LOGOUT);
        createTransitionForState(actionState, "front", CasWebflowConstants.STATE_ID_FRONT_LOGOUT);
    }
1089430
public void setExecutionInfos(java.util.Collection<WorkflowExecutionInfo> executionInfos) {
        if (executionInfos == null) {
            this.executionInfos = null;
            return;
        }

        this.executionInfos = new java.util.ArrayList<WorkflowExecutionInfo>(executionInfos);
    }
985725
@Override
    public List<StepExecution> getStepExecutionsTopLevelFromJobExecutionId(final long jobExecutionId) throws NoSuchJobExecutionException {
        final EntityManager em = getPsu().createEntityManager();
        try {
            List<StepExecution> exec = new TranRequest<List<StepExecution>>(em) {
                @Override
                public List<StepExecution> call() throws Exception {
                    TypedQuery<StepExecution> query = em.createNamedQuery(TopLevelStepExecutionEntity.GET_TOP_LEVEL_STEP_EXECUTIONS_BY_JOB_EXEC_SORT_BY_START_TIME_ASC,
                                                                          StepExecution.class);
                    query.setParameter("jobExecId", jobExecutionId);
                    List<StepExecution> result = query.getResultList();
                    if (result == null) {
                        result = new ArrayList<StepExecution>();
                    }
                    // If empty, try to get job execution to generate NoSuchJobExecutionException if unknown id
                    if (result.isEmpty()) {
                        getJobExecution(jobExecutionId);
                    }
                    return result;
                }
            }.runInNewOrExistingGlobalTran();
            return exec;
        } finally {
            em.close();
        }
    }
940970
protected StatusDetail toStatusDetail(final List<JobInfo> jobInfos,
                                          final JobDefinition jobDefinition) {
        final Status status;
        final String message;
        final JobInfo currentJob = jobInfos.get(0);
        final JobInfo lastJob = (!currentJob.getStopped().isPresent() && currentJob.getStatus() == JobStatus.OK && jobInfos.size() > 1) ? jobInfos.get(1) : jobInfos.get(0);
        final JobMeta jobMeta = getJobMeta(jobDefinition.jobType());
        long numFailedJobs = getNumFailedJobs(jobInfos);
        if (!jobMeta.isDisabled()) {
            switch (lastJob.getStatus()) {
                case OK:
                case SKIPPED:
                    if (jobTooOld(lastJob, jobDefinition)) {
                        status = WARNING;
                        message = jobAgeMessage(jobDefinition);
                    } else if (numFailedJobs > maxFailedJobs) {
                        status = WARNING;
                        message = format(TOO_MANY_JOBS_FAILED_MESSAGE, numFailedJobs, jobInfos.size());
                    } else {
                        status = OK;
                        message = SUCCESS_MESSAGE;
                    }
                    break;
                case ERROR:
                    if (numFailedJobs > maxFailedJobs) {
                        status = ERROR;
                    } else {
                        status = WARNING;
                    }
                    if (numberOfJobs == 1 && maxFailedJobs <= 1) {
                        message = ERROR_MESSAGE;
                    } else {
                        message = format(TOO_MANY_JOBS_FAILED_MESSAGE, numFailedJobs, jobInfos.size());
                    }
                    break;

                case DEAD:
                default:
                    status = WARNING;
                    message = DEAD_MESSAGE;
            }
        } else {
            status = OK;
            message = format(JOB_DEACTIVATED_MESSAGE, jobMeta.getDisabledComment());
        }
        return StatusDetail.statusDetail(
                jobDefinition.jobName(),
                status,
                message,
                asList(
                        link(REL_JOB, String.format("%s/jobs/%s", managementContextPath, lastJob.getJobId()), "Details")
                ),
                runningDetailsFor(lastJob)
        );
    }
436460
@Override
	public JobExecutionResult execute(String jobName) throws Exception {
		if (executor == null) {
			startNewSession();
		}

		Plan p = createProgramPlan(jobName);

		// Session management is disabled, revert this commit to enable
		//p.setJobId(jobID);
		//p.setSessionTimeout(sessionTimeout);

		JobExecutionResult result = executor.executePlan(p);

		this.lastJobExecutionResult = result;
		return result;
	}
476386
public ExecutionStatus doExecutionLoop() {

		final String methodName = "doExecutionLoop";
		
		try {
			currentExecutionElement = modelNavigator.getFirstExecutionElement(jobExecution.getRestartOn());
		} catch (IllegalTransitionException e) {
			String errorMsg = "Could not transition to first execution element within job.";
			logger.warning(errorMsg);
			throw new IllegalArgumentException(errorMsg, e);
		}

		logger.fine("First execution element = " + currentExecutionElement.getId());

		while (true) {

			if (jobContext.getBatchStatus().equals(BatchStatus.STOPPING)) {
				logger.fine(methodName + " Exiting execution loop as job is now in stopping state.");
				return new ExecutionStatus(ExtendedBatchStatus.JOB_OPERATOR_STOPPING);
			}
			
			IExecutionElementController currentElementController = getNextElementController();
			currentStoppableElementController = currentElementController;
			
			ExecutionStatus status = currentElementController.execute();

			// Nothing special for decision or step except to get exit status.  For flow and split we want to bubble up though.
			if ((currentExecutionElement instanceof Split) || (currentExecutionElement instanceof Flow)) {
				// Exit status and restartOn should both be in the job context.
				if (!status.getExtendedBatchStatus().equals(ExtendedBatchStatus.NORMAL_COMPLETION)) {
					logger.fine("Breaking out of loop with return status = " + status.getExtendedBatchStatus().name());
					return status;
				}
			} 

			// Seems like this should only happen if an Error is thrown at the step level, since normally a step-level
			// exception is caught and the fact that it was thrown capture in the ExecutionStatus
			if (jobContext.getBatchStatus().equals(BatchStatus.FAILED)) {
				String errorMsg = "Sub-execution returned its own BatchStatus of FAILED.  Deal with this by throwing exception to the next layer.";
				logger.warning(errorMsg);
				throw new BatchContainerRuntimeException(errorMsg);
			}

			// set the execution element controller to null so we don't try to call stop on it after the element has finished executing
			currentStoppableElementController = null;
			
			logger.fine("Done executing element=" + currentExecutionElement.getId() + ", exitStatus=" + status.getExitStatus());

			if (jobContext.getBatchStatus().equals(BatchStatus.STOPPING)) {
				logger.fine(methodName + " Exiting as job has been stopped");
				return new ExecutionStatus(ExtendedBatchStatus.JOB_OPERATOR_STOPPING);
			}

			Transition nextTransition = null;
			try {
				nextTransition = modelNavigator.getNextTransition(currentExecutionElement, status);
			} catch (IllegalTransitionException e) {
				String errorMsg = "Problem transitioning to next execution element.";
				logger.warning(errorMsg);
				throw new BatchContainerRuntimeException(errorMsg, e);
			} 

			//
			// We will find ourselves in one of four states now.  
			// 
			// 1. Finished transitioning after a normal execution, but nothing to do 'next'.
			// 2. We just executed a step which through an exception, but didn't match a transition element.
			// 3. We are going to 'next' to another execution element (and jump back to the top of this '
			//    'while'-loop.
			// 4. We matched a terminating transition element (<end>, <stop> or <fail).
			//
			
			// 1.
			if (nextTransition.isFinishedTransitioning()) {
				logger.fine(methodName + "No next execution element, and no transition element found either.  Looks like we're done and ready for COMPLETED state.");
				this.stepExecIds =  currentElementController.getLastRunStepExecutions();
				// Consider just passing the last 'status' back, but let's unwrap the exit status and pass a new NORMAL_COMPLETION
				// status back instead.
				return new ExecutionStatus(ExtendedBatchStatus.NORMAL_COMPLETION, status.getExitStatus());
			// 2.
			} else if (nextTransition.noTransitionElementMatchedAfterException()) {
				return new ExecutionStatus(ExtendedBatchStatus.EXCEPTION_THROWN, status.getExitStatus());
			// 3.
			} else if (nextTransition.getNextExecutionElement() != null) {
				// hold on to the previous execution element for the decider
				// we need it because we need to inject the context of the
				// previous execution element into the decider
				previousExecutionElement = currentExecutionElement;
				previousElementController = currentElementController;
				currentExecutionElement = nextTransition.getNextExecutionElement();
			// 4.
			} else if (nextTransition.getTransitionElement() != null) {
				ExecutionStatus terminatingStatus = handleTerminatingTransitionElement(nextTransition.getTransitionElement());
				logger.finer(methodName + " , Breaking out of execution loop after processing terminating transition element.");
				return terminatingStatus;
			} else {
				throw new IllegalStateException("Not sure how we'd end up in this state...aborting rather than looping.");
			}
		}
	}
815166
public static FlowElement getFlowElement(DelegateExecution execution) {
        BpmnModel bpmnModel = getBpmnModel(execution);
        FlowElement flowElement = bpmnModel.getFlowElement(execution.getCurrentActivityId());
        if (flowElement == null) {
            throw new ActivitiException("Could not find a FlowElement for activityId " + execution.getCurrentActivityId());
        }
        return flowElement;
    }
1033952
func (s *WorkflowExecutionInfo) SetExecutionStatus(v string) *WorkflowExecutionInfo {
	s.ExecutionStatus = &v
	return s
}
1350563
public static long getOrCreateFlowExecutionId(FlowSpec spec) {
    long flowExecutionId;
    if (spec.getConfig().hasPath(ConfigurationKeys.FLOW_EXECUTION_ID_KEY)) {
      flowExecutionId = spec.getConfig().getLong(ConfigurationKeys.FLOW_EXECUTION_ID_KEY);
    } else {
      flowExecutionId = System.currentTimeMillis();
    }
    return flowExecutionId;
  }
661860
public ExecutionStatus doExecutionLoop() {

		final String methodName = "doExecutionLoop";
		
		// Before we do anything else, see if we're already in STOPPING state.
		if (runtimeExecution.getBatchStatus().equals(BatchStatus.STOPPING)) {
			logger.fine(methodName + " Exiting execution loop as job is now in stopping state.");
			return new ExecutionStatus(ExtendedBatchStatus.JOB_OPERATOR_STOPPING);
		}

		try {
			currentExecutionElement = modelNavigator.getFirstExecutionElement(runtimeExecution.getRestartOnForThisExecution());
		} catch (IllegalTransitionException e) {
			String errorMsg = "Could not transition to first execution element within job.";
			throw new IllegalArgumentException(errorMsg, e);
		}

		if (logger.isLoggable(Level.FINE)) {
			logger.fine("First execution element = " + currentExecutionElement.getId());
		}

		while (true) {

			IExecutionElementController currentElementController = getNextElementController();
			currentStoppableElementController = currentElementController;
			
			// Now that we've re-established a stoppable element controller, check to see if we missed a stop
			if (runtimeExecution.getBatchStatus().equals(BatchStatus.STOPPING)) {
				logger.fine(methodName + " Exiting execution loop as job is now in stopping state.");
				return new ExecutionStatus(ExtendedBatchStatus.JOB_OPERATOR_STOPPING);
			}
			
			// Restarting after a failure up until this point would cause you to restart at the previous restartOn value.  
			// Now we will reset this to 'null'.   Another alternative would be to only 'null' this out when something actually executed.
			// This could have spec implications..maybe let's think of it more.  Or maybe no one cares even.
			ServicesManagerStaticAnchor.getServicesManager().getPersistenceManagerService().updateJobInstanceNullOutRestartOn(runtimeExecution.getTopLevelInstanceId());

			ExecutionStatus status = currentElementController.execute();

			// Nothing special for decision or step except to get exit status.  For flow and split we want to bubble up though.
			if ((currentExecutionElement instanceof Split) || (currentExecutionElement instanceof Flow)) {
				// Exit status and restartOn should both be in the job context.
				if (!status.getExtendedBatchStatus().equals(ExtendedBatchStatus.NORMAL_COMPLETION)) {
					logger.fine("Breaking out of loop with return status = " + status.getExtendedBatchStatus().name());
					return status;
				}
			} 

			// Seems like this should only happen if an Error is thrown at the step level, since normally a step-level
			// exception is caught and the fact that it was thrown capture in the ExecutionStatus
			if (runtimeExecution.getBatchStatus().equals(BatchStatus.FAILED)) {
				String errorMsg = "Sub-execution returned its own BatchStatus of FAILED.  Deal with this by throwing exception to the next layer.";
				throw new BatchContainerRuntimeException(errorMsg);
			}

			// set the execution element controller to null so we don't try to call stop on it after the element has finished executing
			currentStoppableElementController = null;
			
			if (logger.isLoggable(Level.FINE)) {
				logger.fine("Done executing element=" + currentExecutionElement.getId() + ", exitStatus=" + status.getExitStatus());
			}

			if (runtimeExecution.getBatchStatus().equals(BatchStatus.STOPPING)) {
				logger.fine(methodName + " Exiting as job has been stopped");
				return new ExecutionStatus(ExtendedBatchStatus.JOB_OPERATOR_STOPPING);
			}

			Transition nextTransition = null;
			try {
				nextTransition = modelNavigator.getNextTransition(currentExecutionElement, status);
			} catch (IllegalTransitionException e) {
				String errorMsg = "Problem transitioning to next execution element.";
				throw new BatchContainerRuntimeException(errorMsg, e);
			} 

			//
			// We will find ourselves in one of four states now.  
			// 
			// 1. Finished transitioning after a normal execution, but nothing to do 'next'.
			// 2. We just executed a step which through an exception, but didn't match a transition element.
			// 3. We are going to 'next' to another execution element (and jump back to the top of this '
			//    'while'-loop.
			// 4. We matched a terminating transition element (<end>, <stop> or <fail).
			//
			
			// 1.
			if (nextTransition.isFinishedTransitioning()) {
				logger.fine(methodName + " , No next execution element, and no transition element found either.  Looks like we're done and ready for COMPLETED state.");
				this.stepExecIds =  currentElementController.getLastRunStepExecutions();
				// Consider just passing the last 'status' back, but let's unwrap the exit status and pass a new NORMAL_COMPLETION
				// status back instead.
				return new ExecutionStatus(ExtendedBatchStatus.NORMAL_COMPLETION, status.getExitStatus());
			// 2.
			} else if (nextTransition.noTransitionElementMatchedAfterException()) {
				return new ExecutionStatus(ExtendedBatchStatus.EXCEPTION_THROWN, status.getExitStatus());
			// 3.
			} else if (nextTransition.getNextExecutionElement() != null) {
				// hold on to the previous execution element for the decider
				// we need it because we need to inject the context of the
				// previous execution element into the decider
				previousExecutionElement = currentExecutionElement;
				previousElementController = currentElementController;
				currentExecutionElement = nextTransition.getNextExecutionElement();
			// 4.
			} else if (nextTransition.getTransitionElement() != null) {
				ExecutionStatus terminatingStatus = handleTerminatingTransitionElement(nextTransition.getTransitionElement());
				logger.finer(methodName + " , Breaking out of execution loop after processing terminating transition element.");
				return terminatingStatus;
			} else {
				throw new IllegalStateException("Not sure how we'd end up in this state...aborting rather than looping.");
			}
		}
	}
1097041
public void updateJobStatus(final JobIdentifier jobIdentifier, final JobState jobState) throws Exception {
        // have to synchronize at stage-level because cancellation happens at stage-level
        final String stageMutex = mutexForStageInstance(jobIdentifier);
        synchronized (stageMutex) {
            synchronized (mutexForJob(jobIdentifier)) {
                final JobInstance job = jobInstanceService.buildByIdWithTransitions(jobIdentifier.getBuildId());

                transactionTemplate.executeWithExceptionHandling(new com.thoughtworks.go.server.transaction.TransactionCallbackWithoutResult() {
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        if (job.isNull() || job.getState() == JobState.Rescheduled || job.getResult() == JobResult.Cancelled) {
                            return;
                        }

                        job.changeState(jobState);
                        //TODO: #2318 JobInstance should contain identifier after it's loaded from database
                        job.setIdentifier(jobIdentifier);
                        jobInstanceService.updateStateAndResult(job);

                        synchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                            @Override
                            public void afterCommit() {
                                stageDao.clearCachedAllStages(jobIdentifier.getPipelineName(), jobIdentifier.getPipelineCounter(), jobIdentifier.getStageName());
                            }
                        });

                        if (job.isCompleted()) {
                            Stage stage = stageService.stageById(job.getStageId());
                            stageService.updateResult(stage);
                        }
                    }
                });

                // this has to be in a separate transaction because the above should not fail due to errors when scheduling a the next stage
                // (e.g. CannotScheduleException thrown when there are no agents for run-on-all-agent jobs)
                transactionTemplate.executeWithExceptionHandling(new com.thoughtworks.go.server.transaction.TransactionCallbackWithoutResult() {
                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) throws Exception {
                        if (job.isCompleted()) {
                            Stage stage = stageService.stageById(job.getStageId());
                            automaticallyTriggerRelevantStagesFollowingCompletionOf(stage);
                        }
                    }
                });
            }
        }
    }
693589
@SuppressWarnings("unchecked")
  public void updateExecutions() {
    this.updaterStage.set("Starting update all flows.");
    final Map<Optional<Executor>, List<ExecutableFlow>> exFlowMap = getFlowToExecutorMap();
    final ArrayList<ExecutableFlow> finalizeFlows =
        new ArrayList<>();

    for (final Map.Entry<Optional<Executor>, List<ExecutableFlow>> entry : exFlowMap
        .entrySet()) {

      final Optional<Executor> executorOption = entry.getKey();
      if (!executorOption.isPresent()) {
        for (final ExecutableFlow flow : entry.getValue()) {
          logger.warn("Finalizing execution " + flow.getExecutionId()
              + ". Executor id of this execution doesn't exist");
          finalizeFlows.add(flow);
        }
        continue;
      }
      final Executor executor = executorOption.get();

      this.updaterStage.set("Starting update flows on " + executor.getHost() + ":"
          + executor.getPort());

      Map<String, Object> results = null;
      try {
        results = this.apiGateway.updateExecutions(executor, entry.getValue());
      } catch (final ExecutorManagerException e) {
        handleException(entry, executor, e, finalizeFlows);
      }

      if (results != null) {
        final List<Map<String, Object>> executionUpdates =
            (List<Map<String, Object>>) results
                .get(ConnectorParams.RESPONSE_UPDATED_FLOWS);
        for (final Map<String, Object> updateMap : executionUpdates) {
          try {
            final ExecutableFlow flow = updateExecution(updateMap);

            this.updaterStage.set("Updated flow " + flow.getExecutionId());

            if (ExecutionControllerUtils.isFinished(flow)) {
              finalizeFlows.add(flow);
            }
          } catch (final ExecutorManagerException e) {
            final ExecutableFlow flow = e.getExecutableFlow();
            logger.error(e);

            if (flow != null) {
              logger.warn("Finalizing execution " + flow.getExecutionId());
              finalizeFlows.add(flow);
            }
          }
        }
      }
    }

    this.updaterStage.set("Finalizing " + finalizeFlows.size() + " error flows.");

    for (final ExecutableFlow flow : finalizeFlows) {
      this.executionFinalizer
          .finalizeFlow(flow, "Not running on the assigned executor (any more)", null);
    }

    this.updaterStage.set("Updated all active flows. Waiting for next round.");
  }
89224
def getstate(self):
        
        # the jobstore never existed
        if not os.path.exists(self.jobstorefile):
            logging.info('Workflow ' + self.run_id + ': QUEUED')
            return "QUEUED", -1

        # completed earlier
        if os.path.exists(self.statcompletefile):
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            return "COMPLETE", 0

        # errored earlier
        if os.path.exists(self.staterrorfile):
            logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
            return "EXECUTOR_ERROR", 255

        # the workflow is staged but has not run yet
        if not os.path.exists(self.errfile):
            logging.info('Workflow ' + self.run_id + ': INITIALIZING')
            return "INITIALIZING", -1

        # TODO: Query with "toil status"
        completed = False
        with open(self.errfile, 'r') as f:
            for line in f:
                if 'Traceback (most recent call last)' in line:
                    logging.info('Workflow ' + self.run_id + ': EXECUTOR_ERROR')
                    open(self.staterrorfile, 'a').close()
                    return "EXECUTOR_ERROR", 255
                # run can complete successfully but fail to upload outputs to cloud buckets
                # so save the completed status and make sure there was no error elsewhere
                if 'Finished toil run successfully.' in line:
                    completed = True
        if completed:
            logging.info('Workflow ' + self.run_id + ': COMPLETE')
            open(self.statcompletefile, 'a').close()
            return "COMPLETE", 0

        logging.info('Workflow ' + self.run_id + ': RUNNING')
        return "RUNNING", -1
734847
public void setEvaluationStatus(com.google.api.ads.admanager.axis.v201811.WorkflowEvaluationStatus evaluationStatus) {
        this.evaluationStatus = evaluationStatus;
    }
1099685
private long restartInternal(long oldExecutionId,
                                 Properties restartParameters) throws JobExecutionAlreadyCompleteException, NoSuchJobExecutionException, JobExecutionNotMostRecentException, JobRestartException, JobSecurityException {

        if (authService != null) {
            authService.authorizedJobRestartByExecution(oldExecutionId);
        }

        if (logger.isLoggable(Level.FINE)) {
            logger.fine("JobOperator restart, with old executionId = " + oldExecutionId + "\n" + traceJobParameters(restartParameters));
        }

        //Check if there are no job executions and step executions running.
        BatchStatusValidator.validateStatusAtExecutionRestart(oldExecutionId, restartParameters);
        //Set instance state to submitted to be consistent with start
        long instanceId = getPersistenceManagerService().getJobInstanceIdFromExecutionId(oldExecutionId);
        getPersistenceManagerService().updateJobInstanceOnRestart(instanceId, new Date());

        WSJobExecution jobExecution = getPersistenceManagerService().createJobExecution(instanceId, restartParameters, new Date());
        long newExecutionId = getBatchKernelService().restartJob(jobExecution.getExecutionId(), restartParameters).getKey();

        if (logger.isLoggable(Level.FINE)) {
            logger.fine("Restarted job with new executionId: " + newExecutionId + ", and old executionID: " + oldExecutionId);
        }

        return newExecutionId;
    }
423203
public void setWorkflowState(java.util.Collection<StringFilter> workflowState) {
        if (workflowState == null) {
            this.workflowState = null;
            return;
        }

        this.workflowState = new java.util.ArrayList<StringFilter>(workflowState);
    }