Look for hung/abandoned tasks in the given tenant.
340401
private void checkForDeadTenantTasks(Tenant tenant) {
        m_logger.debug("Checking tenant {} for abandoned tasks", tenant);
        try {
            for(DRow row: DBService.instance(tenant).getAllRows(TaskManagerService.TASKS_STORE_NAME)) {
                TaskRecord taskRecord = buildTaskRecord(row.getKey(), row.getAllColumns(1024).iterator());
                if (taskRecord.getStatus() == TaskStatus.IN_PROGRESS) {
                    checkForDeadTask(tenant, taskRecord);
                }
            }
        } catch (Throwable e) {
            m_logger.warn("Unable to check tenant '{}' for dead tasks: {}", tenant.getName(), e.toString());
        }
    }
316956
def monitor_tasks(self, tasks=None, status=None, age=None):
        ''''''
        self.engine_ready.wait()
        if not tasks:
            tasks = self.task_status.keys()
        else:
            tasks = [x for x in tasks if x in self.task_status]

        # we only monitor running tasks
        with threading.Lock():
            for task in tasks:
                if self.task_status[task] in (
                        'submitted',
                        'running') and task not in self.running_tasks:
                    # these tasks will be actively monitored
                    self.running_tasks.append(task)
        #
        if age is not None:
            age = expand_time(age, default_unit='d')
        return sorted([
            (x, self.task_status[x], self.task_info[x].get(
                'data', (time.time(), None, None)))
            for x in tasks
            if (status is None or self.task_status[x] in status) and
            (age is None or (
                (age > 0 and time.time() -
                 self.task_info[x].get('date',
                                       (time.time(), None, None))[0] > age) or
                (age < 0 and time.time() -
                 self.task_info[x].get('date',
                                       (time.time(), None, None))[0] < -age)))
        ],
                      key=lambda x: -x[2][0])
165933
def get_task_history(last_task):
    """"""
    if hasattr(last_task, 'branch') and last_task.branch:
        return
    elif hasattr(last_task, 'hide') and last_task.hide:
        return
    else:
        return get_func_info(last_task)
538611
def examine(self):
        """"""
        if self._changes:
            return self._changes.pop()

        # clean filepath
        self.filepath = None
        delays = set()
        for path in self._tasks:
            item = self._tasks[path]
            if self.is_changed(path, item['ignore']):
                func = item['func']
                delay = item['delay']
                if delay and isinstance(delay, float):
                    delays.add(delay)
                if func:
                    name = getattr(func, 'name', None)
                    if not name:
                        name = getattr(func, '__name__', 'anonymous')
                    logger.info(
                        "Running task: {} (delay: {})".format(name, delay))
                    func()

        if delays:
            delay = max(delays)
        else:
            delay = None
        return self.filepath, delay
134932
def GetStatusInformation(self):
    
    status = processing_status.TasksStatus()

    with self._lock:
      status.number_of_abandoned_tasks = len(self._tasks_abandoned)
      status.number_of_queued_tasks = len(self._tasks_queued)
      status.number_of_tasks_pending_merge = (
          len(self._tasks_pending_merge) + len(self._tasks_merging))
      status.number_of_tasks_processing = len(self._tasks_processing)
      status.total_number_of_tasks = self._total_number_of_tasks

    return status
995578
def HasPendingTasks(self):
    
    with self._lock:
      self._AbandonInactiveProcessingTasks()

      if self._tasks_processing:
        return True

      # There are no tasks being processed, but we might be
      # waiting for some tasks to be merged.
      if self._HasTasksPendingMerge():
        return True

      # There are no tasks processing or pending merge, but there may
      # still be some waiting to be retried, so we check that.
      if self._HasTasksPendingRetry():
        return True

      # It is possible that a worker has processed a task and the foreman has
      # not been informed about it, since there is no feedback from the worker
      # when it pops a task from the queue.

      # If we believe all the workers are idle for longer than the task
      # inactive time (timeout) abandon all queued tasks. This ensures
      # that processing actually stops when the foreman never gets an
      # update from a worker.

      if self._tasks_queued:
        inactive_time = time.time() - self._TASK_INACTIVE_TIME
        inactive_time = int(inactive_time * definitions.MICROSECONDS_PER_SECOND)

        if self._latest_task_processing_time < inactive_time:
          self._AbandonQueuedTasks()

      if self._tasks_queued:
        return True

      if self._tasks_merging:
        return True

    # There are no tasks pending any work.
    return False
925562
private void attemptToExecuteTask(ApplicationDefinition appDef, Task task, TaskRecord taskRecord) {
        Tenant tenant = Tenant.getTenant(appDef);
        String taskID = taskRecord.getTaskID();
        String claimID = "_claim/" + taskID;
        long claimStamp = System.currentTimeMillis();
        writeTaskClaim(tenant, claimID, claimStamp);
        if (taskClaimedByUs(tenant, claimID)) {
            startTask(appDef, task, taskRecord);
        } else {
        	m_logger.info("Will not start task: it was claimed by another service");
        }
    }
933204
def _get_task_statuses(task_ids, cluster):
    
    response = client.describe_tasks(tasks=task_ids, cluster=cluster)

    # Error checking
    if response['failures'] != []:
        raise Exception('There were some failures:\n{0}'.format(
            response['failures']))
    status_code = response['ResponseMetadata']['HTTPStatusCode']
    if status_code != 200:
        msg = 'Task status request received status code {0}:\n{1}'
        raise Exception(msg.format(status_code, response))

    return [t['lastStatus'] for t in response['tasks']]
411061
def get_task_subtasks(self, task_id, completed=False):
        '''  '''
        return subtasks_endpoint.get_task_subtasks(self, task_id, completed=completed)
677478
def find_tasks(self, overrides):
        """"""
        tasks = self.default_tasks()
        configuration = self.collector.configuration

        for image in list(configuration["images"].keys()):
            path = configuration.path(["images", image, "tasks"], joined="images.{0}.tasks".format(image))
            nxt = configuration.get(path, {})
            tasks.update(nxt)

        if overrides:
            tasks.update(overrides)

        self.tasks = tasks
        return tasks
1242300
def wait_for_task_property(service, task, prop, timeout_sec=120):
    """"""
    return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec)
370960
def _service_task(self):  # pragma: no cover
        """"""
        while True:
            if len(self.sockets) == 0:
                # nothing to do
                self.sleep(self.ping_timeout)
                continue

            # go through the entire client list in a ping interval cycle
            sleep_interval = self.ping_timeout / len(self.sockets)

            try:
                # iterate over the current clients
                for s in self.sockets.copy().values():
                    if not s.closing and not s.closed:
                        s.check_ping_timeout()
                    self.sleep(sleep_interval)
            except (SystemExit, KeyboardInterrupt):
                self.logger.info('service task canceled')
                break
            except:
                # an unexpected exception has occurred, log it and continue
                self.logger.exception('service task exception')
256279
private List<TaskTrackerAction> getJobsForCleanup(String taskTracker) {
    Set<JobID> jobs = null;
    synchronized (trackerToJobsToCleanup) {
      jobs = trackerToJobsToCleanup.remove(taskTracker);
    }
    if (jobs != null) {
      // prepare the actions list
      List<TaskTrackerAction> killList = new ArrayList<TaskTrackerAction>();
      for (JobID killJobId : jobs) {
        killList.add(new KillJobAction(killJobId));
        LOG.debug(taskTracker + " -> KillJobAction: " + killJobId);
      }

      return killList;
    }
    return null;
  }
34989
void performCleanUp(@Nullable Runnable task) {
    evictionLock.lock();
    try {
      maintenance(task);
    } finally {
      evictionLock.unlock();
    }
    if ((drainStatus() == REQUIRED) && (executor == ForkJoinPool.commonPool())) {
      scheduleDrainBuffers();
    }
  }
1114521
@Transactional
	public TaskBase findInterruptedTask(ProcessInstance processInstance) {
		TaskBase ret = null;
		for (Audit audit : processInstance.getAudits()) {
			if (audit.isInterrupted()) {
				ret = getTask(
						audit.getProcessDefinitionName(), audit.getTaskId());
				audit.setInterrupted(false);
				break;
			}
		}
		return ret;
	}
882074
def delete_tenant_if_removed(self, tenant_id):
        """"""
        if not db_lib.tenant_provisioned(tenant_id):
            t_res = MechResource(tenant_id, a_const.TENANT_RESOURCE,
                                 a_const.DELETE)
            self.provision_queue.put(t_res)
25639
def _tasks_status(set_tasks):
    
    if set_tasks["ever_failed"]:
        if not set_tasks["failed"]:
            return LuigiStatusCode.SUCCESS_WITH_RETRY
        else:
            if set_tasks["scheduling_error"]:
                return LuigiStatusCode.FAILED_AND_SCHEDULING_FAILED
            return LuigiStatusCode.FAILED
    elif set_tasks["scheduling_error"]:
        return LuigiStatusCode.SCHEDULING_FAILED
    elif set_tasks["not_run"]:
        return LuigiStatusCode.NOT_RUN
    elif set_tasks["still_pending_ext"]:
        return LuigiStatusCode.MISSING_EXT
    else:
        return LuigiStatusCode.SUCCESS