Get information for the last build of a job
435785
function last_build_info(jobName, customParams, callback) {
      var _doArgs11 = doArgs(arguments, ['string', ['object', {}], 'function']);

      var _doArgs12 = _slicedToArray(_doArgs11, 3);

      jobName = _doArgs12[0];
      customParams = _doArgs12[1];
      callback = _doArgs12[2];


      doRequest({
        urlPattern: [LAST_BUILD, jobName]
      }, customParams, callback);
    }
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)
749108
def _maybe_finish_job(self, job_id):
        """"""
        job = brozzler.Job.load(self.rr, job_id)
        if not job:
            return False
        if job.status.startswith("FINISH"):
            self.logger.warn("%s is already %s", job, job.status)
            return True

        results = self.rr.table("sites").get_all(job_id, index="job_id").run()
        n = 0
        for result in results:
            site = brozzler.Site(self.rr, result)
            if not site.status.startswith("FINISH"):
                results.close()
                return False
            n += 1

        self.logger.info(
                "all %s sites finished, job %s is FINISHED!", n, job.id)
        job.finish()
        job.save()
        return True
368846
def get_last(self):
        
        query = self.table().where('batch', self.get_last_batch_number())

        return query.order_by('migration', 'desc').get()
1371913
function (jobName, customParams, callback) {
      [jobName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']);

      doRequest({
        urlPattern: [LAST_COMPLETED_BUILD, jobName]
      }, customParams, callback);
    }
619482
def gather_job_info(self, jid, tgt, tgt_type, listen=True, **kwargs):
        '''
        
        '''
        log.debug('Checking whether jid %s is still running', jid)
        timeout = int(kwargs.get('gather_job_timeout', self.opts['gather_job_timeout']))

        pub_data = self.run_job(tgt,
                                'saltutil.find_job',
                                arg=[jid],
                                tgt_type=tgt_type,
                                timeout=timeout,
                                listen=listen,
                                **kwargs
                               )

        if 'jid' in pub_data:
            self.event.subscribe(pub_data['jid'])

        return pub_data
550586
function formatBuildInfo(timestamp, scmRevision) {
				var info = [];
				if ( timestamp ) {
					var match = /^(\d{4})(\d{2})(\d{2})-?(\d{2})(\d{2})$/.exec(timestamp);
					if ( match ) {
						timestamp = match[1] + '-' + match[2] + '-' + match[3] + 'T' + match[4] + ":" + match[5];
					}
					info.push("built at " + encode(timestamp));
				}
				if ( scmRevision ) {
					info.push("last change " + encode(scmRevision));
				}
				return info.length === 0 ? "" : " (" + info.join(", ") + ")";
			}
336890
def _find_last_good_run(build):
    """"""
    run_name = request.form.get('run_name', type=str)
    utils.jsonify_assert(run_name, 'run_name required')

    last_good_release = (
        models.Release.query
        .filter_by(
            build_id=build.id,
            status=models.Release.GOOD)
        .order_by(models.Release.created.desc())
        .first())

    last_good_run = None

    if last_good_release:
        logging.debug('Found last good release for: build_id=%r, '
                      'release_name=%r, release_number=%d',
                      build.id, last_good_release.name,
                      last_good_release.number)
        last_good_run = (
            models.Run.query
            .filter_by(release_id=last_good_release.id, name=run_name)
            .first())
        if last_good_run:
            logging.debug('Found last good run for: build_id=%r, '
                          'release_name=%r, release_number=%d, '
                          'run_name=%r',
                          build.id, last_good_release.name,
                          last_good_release.number, last_good_run.name)

    return last_good_release, last_good_run
63846
def get_job_statuses(github_token, api_url, build_id,
                     polling_interval, job_number):
    
    auth = get_json('{api_url}/auth/github'.format(api_url=api_url),
                    data={'github_token': github_token})['access_token']

    while True:
        build = get_json('{api_url}/builds/{build_id}'.format(
            api_url=api_url, build_id=build_id), auth=auth)
        jobs = [job for job in build['jobs']
                if job['number'] != job_number and
                not job['allow_failure']]  # Ignore allowed failures
        if all(job['finished_at'] for job in jobs):
            break  # All the jobs have completed
        elif any(job['state'] != 'passed'
                 for job in jobs if job['finished_at']):
            break  # Some required job that finished did not pass

        print('Waiting for jobs to complete: {job_numbers}'.format(
            job_numbers=[job['number'] for job in jobs
                         if not job['finished_at']]))
        time.sleep(polling_interval)

    return [job['state'] == 'passed' for job in jobs]
110368
def get_job_image_info(project: 'Project', job: Any) -> Tuple[str, str]:
    """"""
    project_name = project.name
    repo_name = project_name

    image_name = '{}/{}'.format(conf.get('REGISTRY_URI'), repo_name)
    try:
        last_commit = project.repo.last_commit
    except ValueError:
        raise ValueError('Repo was not found for project `{}`.'.format(project))
    return image_name, last_commit[0]
166194
function (jobName, buildNumber, customParams, callback) {
      [jobName, buildNumber, customParams, callback] = doArgs(arguments, ['string', 'string|number', ['object', {}], 'function']);

      doRequest({
        urlPattern: [BUILD_INFO, jobName, buildNumber]
      }, customParams, callback);
    }
607572
def query_pending_jobs(auth, repo_name=None, return_raw=False):
    """"""
    url = '%s/pending?format=json' % HOST_ROOT
    LOG.debug('About to fetch %s' % url)
    req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT)

    # If the revision doesn't exist on buildapi, that means there are
    # no builapi jobs for this revision
    if req.status_code not in [200]:
        return []

    raw = req.json()

    # If we don't want the data structure to be reduced
    if return_raw:
        return raw

    # If we only want pending jobs of a specific repo
    if repo_name and repo_name in list(raw['pending'].keys()):
        repo_list = [repo_name]
    else:
        repo_list = list(raw['pending'].keys())

    # Data structure to return
    data = {}
    for repo in repo_list:
        data[repo] = {}
        repo_jobs = raw['pending'][repo]
        for revision in repo_jobs.items():
            data[repo][revision[0]] = revision[1]

    return data
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)
        );
    }
109438
def processData(config, stats):
    
    if 'total_time' not in stats or 'total_clock' not in stats:
        # toil job not finished yet
        stats.total_time = [0.0]
        stats.total_clock = [0.0]

    stats.total_time = sum([float(number) for number in stats.total_time])
    stats.total_clock = sum([float(number) for number in stats.total_clock])

    collatedStatsTag = Expando(total_run_time=stats.total_time,
                               total_clock=stats.total_clock,
                               batch_system=config.batchSystem,
                               default_memory=str(config.defaultMemory),
                               default_cores=str(config.defaultCores),
                               max_cores=str(config.maxCores)
                               )

    # Add worker info
    worker = [_f for _f in getattr(stats, 'workers', []) if _f]
    jobs = [_f for _f in getattr(stats, 'jobs', []) if _f]
    jobs = [item for sublist in jobs for item in sublist]

    def fn4(job):
        try:
            return list(jobs)
        except TypeError:
            return []

    buildElement(collatedStatsTag, worker, "worker")
    createSummary(buildElement(collatedStatsTag, jobs, "jobs"),
                  getattr(stats, 'workers', []), "worker", fn4)
    # Get info for each job
    jobNames = set()
    for job in jobs:
        jobNames.add(job.class_name)
    jobTypesTag = Expando()
    collatedStatsTag.job_types = jobTypesTag
    for jobName in jobNames:
        jobTypes = [ job for job in jobs if job.class_name == jobName ]
        buildElement(jobTypesTag, jobTypes, jobName)
    collatedStatsTag.name = "collatedStatsTag"
    return collatedStatsTag
445268
def _process(self, project, build_system, job_priorities):
        ''''''
        jobs = []

        # we cache the reference data names in order to reduce API calls
        cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system)
        ref_data_names_map = cache.get(cache_key)
        if not ref_data_names_map:
            # cache expired so re-build the reference data names map; the map
            # contains the ref_data_name of every treeherder *test* job for this project
            ref_data_names_map = self._build_ref_data_names(project, build_system)
            # update the cache
            cache.set(cache_key, ref_data_names_map, SETA_REF_DATA_NAMES_CACHE_TIMEOUT)

        # now check the JobPriority table against the list of valid runnable
        for jp in job_priorities:
            # if this JobPriority entry is no longer supported in SETA then ignore it
            if not valid_platform(jp.platform):
                continue
            if is_job_blacklisted(jp.testtype):
                continue

            key = jp.unique_identifier()
            if key in ref_data_names_map:
                # e.g. desktop-test-linux64-pgo/opt-reftest-13 or builder name
                jobs.append(ref_data_names_map[key])
            else:
                logger.warning('Job priority (%s) not found in accepted jobs list', jp)

        return jobs
619841
private <Q, R> void recordFinalStatus(JobIdentifier<Q, R> jobId, JobStatus<Q, R> jobStatus) {
        try {
            _jobStatusDAO.updateJobStatus(jobId, jobStatus);
        } catch (Exception e) {
            _log.error("Failed to record final status for job: [id={}, status={}]", jobId, jobStatus.getStatus(), e);
        }
    }
218145
public function getLastBuild()
    {
        if ($this->lastBuild == null) {
            $build = new self($this->getEngine(), $this->getProject());

            return $build;
        }

        return $this->lastBuild;
    }