Parse a job schedule.
163721
def _parse_schedule(self, schedule):
        
        result = {}

        for param in shlex.split(str(schedule)): # do not feed unicode to shlex
            try:
                key, val = param.split('=', 1)
            except (TypeError, ValueError):
                self.fatal("Bad param '%s' in job schedule '%s'" % (param, schedule))
            else:
                result[key] = val

        return result
353653
def serialize_job(job):
    """"""
    d = dict(
        id=job.get_id(),
        uri=url_for('jobs.get_job', job_id=job.get_id(), _external=True),
        status=job.get_status(),
        result=job.result
    )
    return d
31714
def jobs(opts={})

      opts = { opts => true } if opts.is_a?(Symbol)

      jobs = @jobs.to_a

      if opts[:running]
        jobs = jobs.select { |j| j.running? }
      elsif ! opts[:all]
        jobs = jobs.reject { |j| j.next_time.nil? || j.unscheduled_at }
      end

      tags = Array(opts[:tag] || opts[:tags]).collect(&:to_s)
      jobs = jobs.reject { |j| tags.find { |t| ! j.tags.include?(t) } }

      jobs
    end
492802
def format(self, format):
    """"""

    job_id = "%d - %d" % (self.job.id, self.id)
    queue = self.job.queue_name if self.machine_name is None else self.machine_name
    status = "%s" % self.status + (" (%d)" % self.result if self.result is not None else "" )

    return format.format("", job_id, queue, status)
1195914
def convert_job(row: list) -> dict:
    """"""
    state = row[-2]
    start_time_raw = row[-4]
    end_time_raw = row[-3]
    if state not in ('PENDING', 'CANCELLED'):
        start_time = datetime.strptime(start_time_raw, '%Y-%m-%dT%H:%M:%S')
        if state != 'RUNNING':
            end_time = datetime.strptime(end_time_raw, '%Y-%m-%dT%H:%M:%S')
        else:
            end_time = None
    else:
        start_time = end_time = None

    # parse name of job
    job_name = row[1]
    step_name, step_context = job_name.rstrip('_BOTH').rstrip('_SV').rsplit('_', 1)

    return {
        'id': int(row[0]),
        'name': job_name,
        'step': step_name,
        'context': step_context,
        'state': state,
        'start': start_time,
        'end': end_time,
        'elapsed': time_to_sec(row[-5]),
        'cpu': time_to_sec(row[-6]),
        'is_completed': state == 'COMPLETED',
    }
997066
def _jobs():
    '''
    
    '''
    response = salt.utils.http.query(
        "{0}/scheduler/jobs".format(_base_url()),
        decode_type='json',
        decode=True,
    )
    jobs = {}
    for job in response['dict']:
        jobs[job.pop('name')] = job
    return jobs
365079
def yaml_to_job_list(yaml_file, base_dir):
    """"""
    yaml_dict = get_yaml_dict(yaml_file)
    job_list = []
    for key, value in yaml_dict.items():
        job_list.append((value, rel_to_cwd(base_dir, key)))

    return job_list
206433
def ListJobs(self, token=None):
    """"""
    del token
    return [job.cron_job_id for job in data_store.REL_DB.ReadCronJobs()]
62686
def _atq(**kwargs):
    '''
    
    '''

    jobs = []

    runas = kwargs.get('runas', None)
    tag = kwargs.get('tag', None)
    hour = kwargs.get('hour', None)
    minute = kwargs.get('minute', None)
    day = kwargs.get('day', None)
    month = kwargs.get('month', None)
    year = kwargs.get('year', None)
    if year and len(six.text_type(year)) == 2:
        year = '20{0}'.format(year)

    jobinfo = atq()['jobs']
    if not jobinfo:
        return {'jobs': jobs}

    for job in jobinfo:

        if not runas:
            pass
        elif runas == job['user']:
            pass
        else:
            continue

        if not tag:
            pass
        elif tag == job['tag']:
            pass
        else:
            continue

        if not hour:
            pass
        elif '{0:02d}'.format(int(hour)) == job['time'].split(':')[0]:
            pass
        else:
            continue

        if not minute:
            pass
        elif '{0:02d}'.format(int(minute)) == job['time'].split(':')[1]:
            pass
        else:
            continue

        if not day:
            pass
        elif '{0:02d}'.format(int(day)) == job['date'].split('-')[2]:
            pass
        else:
            continue

        if not month:
            pass
        elif '{0:02d}'.format(int(month)) == job['date'].split('-')[1]:
            pass
        else:
            continue

        if not year:
            pass
        elif year == job['date'].split('-')[0]:
            pass
        else:
            continue

        jobs.append(job)

    if not jobs:
        note = 'No match jobs or time format error'
        return {'jobs': jobs, 'note': note}

    return {'jobs': jobs}
1203785
def Jobs(self):
        """"""
        url = self._url + "/jobs"
        return Jobs(url=url,
                    securityHandler=self._securityHandler,
                    proxy_url=self._proxy_url,
                    proxy_port=self._proxy_port,
                    initialize=True)
88658
def run_job(self, name):
        '''
        
        '''
        data = self._get_schedule().get(name, {})

        if 'function' in data:
            func = data['function']
        elif 'func' in data:
            func = data['func']
        elif 'fun' in data:
            func = data['fun']
        else:
            func = None
        if not isinstance(func, list):
            func = [func]
        for _func in func:
            if _func not in self.functions:
                log.error(
                    'Invalid function: %s in scheduled job %s.',
                    _func, name
                )

        if 'name' not in data:
            data['name'] = name
        log.info('Running Job: %s', name)

        # Grab run, assume True
        run = data.get('run', True)
        if run:
            self._run_job(_func, data)
1304203
def _schedule_log_parsing(job, job_logs, result):
    

    # importing here to avoid an import loop
    from treeherder.log_parser.tasks import parse_logs

    task_types = {
        "errorsummary_json",
        "buildbot_text",
        "builds-4h"
    }

    job_log_ids = []
    for job_log in job_logs:
        # a log can be submitted already parsed.  So only schedule
        # a parsing task if it's ``pending``
        # the submitter is then responsible for submitting the
        # text_log_summary artifact
        if job_log.status != JobLog.PENDING:
            continue

        # if this is not a known type of log, abort parse
        if job_log.name not in task_types:
            continue

        job_log_ids.append(job_log.id)

    # TODO: Replace the use of different queues for failures vs not with the
    # RabbitMQ priority feature (since the idea behind separate queues was
    # only to ensure failures are dealt with first if there is a backlog).
    if result != 'success':
        queue = 'log_parser_fail'
        priority = 'failures'
    else:
        queue = 'log_parser'
        priority = "normal"

    parse_logs.apply_async(queue=queue,
                           args=[job.id, job_log_ids, priority])
1254681
def _parse_weekday(val):
        '''  '''
        val = val.title()
        try:
            return list(calendar.day_abbr).index(val)
        except ValueError:
            try:
                return list(calendar.day_name).index(val)
            except ValueError:
                return None
291014
def scheduled_jobs(with_times=False, connection=None):
    
    if connection is None:
        connection = r
    jobs = connection.zrangebyscore(REDIS_KEY, 0, sys.maxsize,
                                    withscores=with_times)
    for job in jobs:
        if with_times:
            yield job[0].decode('utf-8'), job[1]
        else:
            yield job.decode('utf-8')
21828
private JobID parseJobId(String jobIdString) throws CliArgsException {
		if (jobIdString == null) {
			throw new CliArgsException("Missing JobId");
		}

		final JobID jobId;
		try {
			jobId = JobID.fromHexString(jobIdString);
		} catch (IllegalArgumentException e) {
			throw new CliArgsException(e.getMessage());
		}
		return jobId;
	}
948431
def _parse_sacct(sacct_jobs: List[dict], jobs_count: int=None):
        """"""
        failed_jobs = sacct_api.filter_jobs(sacct_jobs, failed=True)
        completed_jobs = [job for job in sacct_jobs if job['is_completed']]
        last_job_end = completed_jobs[-1]['end'] if len(completed_jobs) > 0 else None
        data = {
            'jobs': jobs_count,
            'completed_jobs': len(completed_jobs),
            'progress': (len(completed_jobs) / jobs_count) if jobs_count else None,
            'failed_jobs': [{
                'slurm_id': job['id'],
                'started_at': job['start'],
                'elapsed': job['elapsed'],
                'status': job['state'].lower(),
                'name': job['step'],
                'context': job['context'],
            } for job in failed_jobs]
        }
        return data, last_job_end
801145
def schedule_jobs(job_list)
      Jobbr::Ohm.models(Jobbr::Scheduled).each do |job|
        if job.every
          job_list.every job.every[0], job.every[1] do
            job_list.jobbr job.task_name
          end
        end
      end
    end