Convert a salt job id into the time when the job was invoked
494770
def jid_to_time(jid):
    '''
    
    '''
    jid = six.text_type(jid)
    if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):
        return ''
    year = jid[:4]
    month = jid[4:6]
    day = jid[6:8]
    hour = jid[8:10]
    minute = jid[10:12]
    second = jid[12:14]
    micro = jid[14:20]

    ret = '{0}, {1} {2} {3}:{4}:{5}.{6}'.format(year,
                                                months[int(month)],
                                                day,
                                                hour,
                                                minute,
                                                second,
                                                micro)
    return ret
442144
def print_job(jid, ext_source=None):
    '''
    
    '''
    ret = {}

    returner = _get_returner((
        __opts__['ext_job_cache'],
        ext_source,
        __opts__['master_job_cache']
    ))
    mminion = salt.minion.MasterMinion(__opts__)

    try:
        job = mminion.returners['{0}.get_load'.format(returner)](jid)
        ret[jid] = _format_jid_instance(jid, job)
    except TypeError:
        ret[jid]['Result'] = (
            'Requested returner {0} is not available. Jobs cannot be '
            'retrieved. Check master log for details.'.format(returner)
        )
        return ret
    ret[jid]['Result'] = mminion.returners['{0}.get_jid'.format(returner)](jid)

    fstr = '{0}.get_endtime'.format(__opts__['master_job_cache'])
    if (__opts__.get('job_cache_store_endtime')
            and fstr in mminion.returners):
        endtime = mminion.returners[fstr](jid)
        if endtime:
            ret[jid]['EndTime'] = endtime

    return ret
889349
def active(display_progress=False):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        active_ = client.cmd('*', 'saltutil.running', timeout=__opts__['timeout'])
    except SaltClientError as client_error:
        print(client_error)
        return ret

    if display_progress:
        __jid_event__.fire_event({
            'message': 'Attempting to contact minions: {0}'.format(list(active_.keys()))
            }, 'progress')
    for minion, data in six.iteritems(active_):
        if display_progress:
            __jid_event__.fire_event({'message': 'Received reply from minion {0}'.format(minion)}, 'progress')
        if not isinstance(data, list):
            continue
        for job in data:
            if not job['jid'] in ret:
                ret[job['jid']] = _format_jid_instance(job['jid'], job)
                ret[job['jid']].update({'Running': [{minion: job.get('pid', None)}], 'Returned': []})
            else:
                ret[job['jid']]['Running'].append({minion: job['pid']})

    mminion = salt.minion.MasterMinion(__opts__)
    for jid in ret:
        returner = _get_returner((__opts__['ext_job_cache'], __opts__['master_job_cache']))
        data = mminion.returners['{0}.get_jid'.format(returner)](jid)
        if data:
            for minion in data:
                if minion not in ret[jid]['Returned']:
                    ret[jid]['Returned'].append(minion)

    return ret
1181845
def job_to_dict(job):
    """"""

    data = OrderedDict()
    data['id'] = job.id
    data['name'] = job.name
    data['func'] = job.func_ref
    data['args'] = job.args
    data['kwargs'] = job.kwargs

    data.update(trigger_to_dict(job.trigger))

    if not job.pending:
        data['misfire_grace_time'] = job.misfire_grace_time
        data['max_instances'] = job.max_instances
        data['next_run_time'] = None if job.next_run_time is None else job.next_run_time

    return data
247840
def _get_logs(job_id):
    """"""
    # Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
    # warnings.
    job_id = unicode(job_id)

    results = ENGINE.execute(
        LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall()

    results = [dict(result) for result in results]

    for result in results:
        result.pop("job_id")

    return results
311075
def stats_job(self, job_id):
        
        with self._sock_ctx() as socket:
            if hasattr(job_id, 'job_id'):
                job_id = job_id.job_id
            self._send_message('stats-job {0}'.format(job_id), socket)
            body = self._receive_data_with_prefix(b'OK', socket)
            job_status = yaml_load(body)
            return job_status
498839
def serialize
      {
        "job_class"  => self.class.name,
        "job_id"     => job_id,
        "provider_job_id" => provider_job_id,
        "queue_name" => queue_name,
        "priority"   => priority,
        "arguments"  => serialize_arguments_if_needed(arguments),
        "executions" => executions,
        "exception_executions" => exception_executions,
        "locale"     => I18n.locale.to_s,
        "timezone"   => Time.zone.try(:name),
        "enqueued_at" => Time.now.utc.iso8601
      }
    end
451298
function(callback, timeInMs) {
    var timeout = makeTimeout(callback);
    setTriggerTime(timeout, timeInMs);
    s_timeoutsToInsert.push(timeout);
    return timeout.id;
  }
1352911
def get_load(jid):
    '''
    
    '''
    serv = _get_serv(ret=None)
    data = serv.get('load:{0}'.format(jid))
    if data:
        return salt.utils.json.loads(data)
    return {}
1305849
def update_job(name, config):
    '''
    
    '''
    if 'name' not in config:
        config['name'] = name
    data = salt.utils.json.dumps(config)
    try:
        response = salt.utils.http.query(
            "{0}/scheduler/iso8601".format(_base_url()),
            method='POST',
            data=data,
            header_dict={
                'Content-Type': 'application/json',
            },
        )
        log.debug('update response: %s', response)
        return {'success': True}
    except Exception as ex:
        log.error('unable to update chronos job: %s', get_error_message(ex))
        return {
            'exception': {
                'message': get_error_message(ex),
            }
        }
315800
def atq(tag=None):
    '''
    
    '''
    jobs = []

    res = __salt__['cmd.run_all']('atq')

    if res['retcode'] > 0:
        return {'error': res['stderr']}

    # No jobs so return
    if res['stdout'] == 'no files in queue.':
        return {'jobs': jobs}

    # Jobs created with at.at() will use the following
    # comment to denote a tagged job.
    job_kw_regex = re.compile(r'^### SALT: (\w+)')

    # Split each job into a dictionary and handle
    # pulling out tags or only listing jobs with a certain
    # tag
    for line in res['stdout'].splitlines():
        job_tag = ''

        # skip header
        if line.startswith(' Rank'):
            continue

        # parse job output
        tmp = line.split()
        timestr = ' '.join(tmp[1:5])
        job = tmp[6]
        specs = datetime.datetime(
            *(time.strptime(timestr, '%b %d, %Y %H:%M')[0:5])
        ).isoformat().split('T')
        specs.append(tmp[7])
        specs.append(tmp[5])

        # make sure job is str
        job = six.text_type(job)

        # search for any tags
        atjob_file = '/var/spool/cron/atjobs/{job}'.format(
            job=job
        )
        if __salt__['file.file_exists'](atjob_file):
            with salt.utils.files.fopen(atjob_file, 'r') as atjob:
                for line in atjob:
                    line = salt.utils.stringutils.to_unicode(line)
                    tmp = job_kw_regex.match(line)
                    if tmp:
                        job_tag = tmp.groups()[0]

        # filter on tags
        if not tag:
            jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
                'queue': specs[2], 'user': specs[3], 'tag': job_tag})
        elif tag and tag in [job_tag, job]:
            jobs.append({'job': job, 'date': specs[0], 'time': specs[1],
                'queue': specs[2], 'user': specs[3], 'tag': job_tag})

    return {'jobs': jobs}
662820
def enable_job(name, **kwargs):
    '''
    
    '''

    ret = {'comment': [],
           'result': True}

    if not name:
        ret['comment'] = 'Job name is required.'
        ret['result'] = False

    if 'test' in __opts__ and __opts__['test']:
        ret['comment'] = 'Job: {0} would be enabled in schedule.'.format(name)
    else:
        persist = True
        if 'persist' in kwargs:
            persist = kwargs['persist']

        if name in list_(show_all=True, where='opts', return_yaml=False):
            event_data = {'name': name, 'func': 'enable_job', 'persist': persist}
        elif name in list_(show_all=True, where='pillar', return_yaml=False):
            event_data = {'name': name, 'where': 'pillar', 'func': 'enable_job', 'persist': False}
        else:
            ret['comment'] = 'Job {0} does not exist.'.format(name)
            ret['result'] = False
            return ret

        try:
            eventer = salt.utils.event.get_event('minion', opts=__opts__)
            res = __salt__['event.fire'](event_data, 'manage_schedule')
            if res:
                event_ret = eventer.get_event(tag='/salt/minion/minion_schedule_enabled_job_complete', wait=30)
                if event_ret and event_ret['complete']:
                    schedule = event_ret['schedule']
                    # check item exists in schedule and is enabled
                    if name in schedule and schedule[name]['enabled']:
                        ret['result'] = True
                        ret['comment'] = 'Enabled Job {0} in schedule.'.format(name)
                    else:
                        ret['result'] = False
                        ret['comment'] = 'Failed to enable job {0} in schedule.'.format(name)
                    return ret
        except KeyError:
            # Effectively a no-op, since we can't really return without an event system
            ret['comment'] = 'Event module not available. Schedule enable job failed.'
    return ret
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)
113761
def WriteCronJobRun(self, run_object):
    """"""
    if run_object.cron_job_id not in self.cronjobs:
      raise db.UnknownCronJobError("Job with id %s not found." %
                                   run_object.cron_job_id)

    clone = run_object.Copy()
    clone.timestamp = rdfvalue.RDFDatetime.Now()
    self.cronjob_runs[(clone.cron_job_id, clone.run_id)] = clone
1221881
def get_job_id(self, response):
        """"""
        match = re.search('Job <([^>]+)> is submitted', response)
        if match:
            return match.group(1)
        else:
            return None
984927
def format_jid_instance(jid, job):
    '''
    
    '''
    ret = format_job_instance(job)
    ret.update({'StartTime': jid_to_time(jid)})
    return ret
979718
def atrm(*args):
    '''
    
    '''

    # Need to do this here also since we use atq()
    if not salt.utils.path.which('at'):
        return '\'at.atrm\' is not available.'

    if not args:
        return {'jobs': {'removed': [], 'tag': None}}

    # Convert all to strings
    args = salt.utils.data.stringify(args)

    if args[0] == 'all':
        if len(args) > 1:
            opts = list(list(map(str, [j['job'] for j in atq(args[1])['jobs']])))
            ret = {'jobs': {'removed': opts, 'tag': args[1]}}
        else:
            opts = list(list(map(str, [j['job'] for j in atq()['jobs']])))
            ret = {'jobs': {'removed': opts, 'tag': None}}
    else:
        opts = list(list(map(str, [i['job'] for i in atq()['jobs']
            if six.text_type(i['job']) in args])))
        ret = {'jobs': {'removed': opts, 'tag': None}}

    # Shim to produce output similar to what __virtual__() should do
    # but __salt__ isn't available in __virtual__()
    output = _cmd('at', '-d', ' '.join(opts))
    if output is None:
        return '\'at.atrm\' is not available.'

    return ret