Find and claim the next pending task in the queue, if any.

    Args:
        context (scriptworker.context.Context): the scriptworker context.

    Returns:
        dict: a dict containing a list of the task definitions of the tasks claimed.
970976
async def claim_work(context):
    
    log.debug("Calling claimWork...")
    payload = {
        'workerGroup': context.config['worker_group'],
        'workerId': context.config['worker_id'],
        # Hardcode one task at a time.  Make this a pref if we allow for
        # parallel tasks in multiple `work_dir`s.
        'tasks': 1,
    }
    try:
        return await context.queue.claimWork(
            context.config['provisioner_id'],
            context.config['worker_type'],
            payload
        )
    except (taskcluster.exceptions.TaskclusterFailure, aiohttp.ClientError) as exc:
        log.warning("{} {}".format(exc.__class__, exc))
1320420
def lookup_task(self, task):
        
        if isinstance(task, str):
            try:
                return self[task]
            except KeyError:
                pass
        raise TaskError('Unknown task %s' % task)
1315903
def task_list(self, pending=True):
        
        log = self._params.get('log', self._discard)
        tasks = [t for t in self._tasks if t.participant()]
        requires = {}
        for t in tasks:
            requires[t] = t.get_requires(pending=pending)
        done = set()
        start_order = []
        cycle = 0
        while len(tasks) > len(start_order):
            cycle += 1
            changed = False
            for t in tasks:
                if t._name in done:
                    continue
                needs = 0
                for req in requires[t]:
                    if req._name in done:
                        needs += 1
                if needs == len(requires[t]):
                    changed = True
                    start_order.append(t)
                    done.add(t._name)
                    log.debug("Found '%s' in scope", t._name)
            if not changed:
                log.error("Cycle %d failed after %s", cycle, [t._name for t in set(tasks).difference(done)])
                raise TaskError(None, "At cycle %d, startup order conflict, processed %s, remaining %s" %
                            (cycle, done, [t._name for t in set(tasks).difference(done)]))
        log.debug("Cycle %d gave %s", cycle, [t._name for t in start_order])
        return start_order
200937
def task(self) -> Tuple[str, Any]:
        
        try:
            items, = self.configuration.items()
        except ValueError:
            raise MultipleTaskDefinitions(
                'Multiple tasks defined in scenario configuration!',
            )
        return items
399798
def task_save(self, ):
        
        if not self.cur_task:
            return
        deadline = self.task_deadline_de.dateTime().toPython()
        status = self.task_status_cb.currentText()
        self.cur_task.deadline = deadline
        self.cur_task.status = status
        self.cur_task.save()
847987
def task_log(self):
        
        if self.task_id is None:
            raise ValueError('task_id is None')
        return self.get_task_log(self.task_id, self.session, self.request_kwargs)
755695
def task_search(self, task_str, **kwargs):
        
        self.prune()
        result = collections.defaultdict(dict)
        for task in self._state.get_active_tasks():
            if task.id.find(task_str) != -1:
                serialized = self._serialize_task(task.id, include_deps=False)
                result[task.status][task.id] = serialized
        return result
234454
def get_task_statuses(self):
        

        params = {'taskstatus': ''}

        resp = self._client.get(self.resource(), params=params)
        self.parse(self._client, resp, obj=self)

        return dict([(task.name, task) for task in self._tasks])
514608
async def invoke(self, context):
        
        try:
            # Note: claim_work(...) might not be safely interruptible! See
            # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069
            tasks = await self._run_cancellable(claim_work(context))
            if not tasks or not tasks.get('tasks', []):
                await self._run_cancellable(asyncio.sleep(context.config['poll_interval']))
                return None

            # Assume only a single task, but should more than one fall through,
            # run them sequentially.  A side effect is our return status will
            # be the status of the final task run.
            status = None
            for task_defn in tasks.get('tasks', []):
                prepare_to_run_task(context, task_defn)
                reclaim_fut = context.event_loop.create_task(reclaim_task(context, context.task))
                try:
                    status = await do_run_task(context, self._run_cancellable, self._to_cancellable_process)
                    artifacts_paths = filepaths_in_dir(context.config['artifact_dir'])
                except WorkerShutdownDuringTask:
                    shutdown_artifact_paths = [os.path.join('public', 'logs', log_file)
                                               for log_file in ['chain_of_trust.log', 'live_backing.log']]
                    artifacts_paths = [path for path in shutdown_artifact_paths
                                       if os.path.isfile(os.path.join(context.config['artifact_dir'], path))]
                    status = STATUSES['worker-shutdown']
                status = worst_level(status, await do_upload(context, artifacts_paths))
                await complete_task(context, status)
                reclaim_fut.cancel()
                cleanup(context)

            return status

        except asyncio.CancelledError:
            return None
1144474
def get_task(self, task=None):
        
        # Iterate over the grindstone tasks
        for t in self.grindstone['tasks']:
            # if they key matches the task
            if key_of(t) == task:
                # Return this task
                return t
        # Otherwise return nothing
        return None
803869
def get_tasks(self, status=None, offset=None, limit=None):
        
        params = {'project': self.id, 'offset': offset, 'limit': limit}
        if status:
            params['status'] = status
        return self._api.tasks.query(api=self._api, **params)
964672
def complete_contexts(self):
        '''
        
        '''
        if self._complete_contexts:
            return self._complete_contexts
        self.context()
        return self._complete_contexts
620534
def get_finished_results(self):
        
        task_and_results = []
        for pending_result in self.pending_results:
            if pending_result.ready():
                ret = pending_result.get()
                task_id, result = ret
                task = self.task_id_to_task[task_id]
                # process any pending messages for this task (will also process other tasks messages)
                self.process_all_messages_in_queue()
                task.after_run(result)
                task_and_results.append((task, result))
                self.pending_results.remove(pending_result)
        return task_and_results
477731
def current_task(self, args):
        
        ctask = self.nice_name if self.nice_name is not None else self.name
        if args is not None:
            if args.update:
                ctask = ctask.replace('%pre', 'Updating')
            else:
                ctask = ctask.replace('%pre', 'Loading')
        return ctask
520204
def inject_context(context):
    
    context_path = tasks.get_context_path()
    try:
        new_context = json.loads(context)
    except ValueError:
        print('Couldn\'t load context parameter')
        return
    with open(context_path) as jsonfile:
        try:
            jsondata = json.loads(jsonfile.read())
            jsondata.update(new_context)
        except ValueError:
            print('Couldn\'t read context.json')
            return
    with open(context_path, 'w') as jsoncontent:
        json.dump(jsondata, jsoncontent, indent=4)
159727
public List<TaskMonitor> getTaskMonitors(RuntimeContext context) {
        return getTaskMonitors().stream().filter(monitor ->
            monitor.isEnabled(context)
        ).collect(Collectors.toList());
    }
554533
def help(self, taskname=None):
        

        if not taskname:
            print(inspect.getdoc(self._tasks))
            print()
            print('Available tasks:')
            print()

            for task in self.get_tasks():
                self.print_task_help(task[1], task[0])
        else:
            try:
                task = self.get_task(taskname)
                self.print_task_help(task, task.__name__)

            except TaskNotFound:
                print('Task "%s" not found! Use "ape help" to get usage information.' % taskname)