Change an existing cron job's query

        Args:
            iden (bytes):  The iden of the cron job to be changed
5140
async def updateCronJob(self, iden, query):
        '''
        
        '''
        cron = self.cell.agenda.appts.get(iden)
        if cron is None:
            raise s_exc.NoSuchIden()
        self._trig_auth_check(cron.useriden)
        await self.cell.agenda.mod(iden, query)
439413
def add_job(self, id, func, **kwargs):
        

        job_def = dict(kwargs)
        job_def['id'] = id
        job_def['func'] = func
        job_def['name'] = job_def.get('name') or id

        fix_job_def(job_def)

        return self._scheduler.add_job(**job_def)
628710
def mogrify(self, query, args=None):
        
        conn = self._get_db()
        if PY2:  # Use bytes on Python 2 always
            query = self._ensure_bytes(query, encoding=conn.encoding)

        if args is not None:
            query = query % self._escape_args(args, conn)

        return query
1289353
def enqueue_job(self, job):
        
        self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))

        interval = job.meta.get('interval', None)
        repeat = job.meta.get('repeat', None)
        cron_string = job.meta.get('cron_string', None)

        # If job is a repeated job, decrement counter
        if repeat:
            job.meta['repeat'] = int(repeat) - 1

        queue = self.get_queue_for_job(job)
        queue.enqueue_job(job)
        self.connection.zrem(self.scheduled_jobs_key, job.id)

        if interval:
            # If this is a repeat job and counter has reached 0, don't repeat
            if repeat is not None:
                if job.meta['repeat'] == 0:
                    return
            self.connection.zadd(self.scheduled_jobs_key,
                                  {job.id: to_unix(datetime.utcnow()) + int(interval)})
        elif cron_string:
            # If this is a repeat job and counter has reached 0, don't repeat
            if repeat is not None:
                if job.meta['repeat'] == 0:
                    return
            self.connection.zadd(self.scheduled_jobs_key,
                                  {job.id: to_unix(get_next_scheduled_time(cron_string))})
1022107
def db_exec(self, query, args=None):
        
        if args is None:
            self.db_query(query)
        else:
            self.db_query(query, args)

        self.db.commit()
1327234
def _CronJobFromRow(self, row):
    """"""
    (job, create_time, enabled, forced_run_requested, last_run_status,
     last_run_time, current_run_id, state, leased_until, leased_by) = row

    job = rdf_cronjobs.CronJob.FromSerializedString(job)
    job.current_run_id = db_utils.IntToCronJobRunID(current_run_id)
    job.enabled = enabled
    job.forced_run_requested = forced_run_requested
    job.last_run_status = last_run_status
    job.last_run_time = mysql_utils.TimestampToRDFDatetime(last_run_time)
    if state:
      job.state = rdf_protodict.AttributedDict.FromSerializedString(state)
    job.created_at = mysql_utils.TimestampToRDFDatetime(create_time)
    job.leased_until = mysql_utils.TimestampToRDFDatetime(leased_until)
    job.leased_by = leased_by
    return job
1207097
def LeaseCronJobs(self, cronjob_ids=None, lease_time=None, cursor=None):
    """"""
    now = rdfvalue.RDFDatetime.Now()
    now_str = mysql_utils.RDFDatetimeToTimestamp(now)
    expiry_str = mysql_utils.RDFDatetimeToTimestamp(now + lease_time)
    id_str = utils.ProcessIdString()

    query = ("UPDATE cron_jobs "
             "SET leased_until=FROM_UNIXTIME(%s), leased_by=%s "
             "WHERE (leased_until IS NULL OR leased_until < FROM_UNIXTIME(%s))")
    args = [expiry_str, id_str, now_str]

    if cronjob_ids:
      query += " AND job_id in (%s)" % ", ".join(["%s"] * len(cronjob_ids))
      args += cronjob_ids

    updated = cursor.execute(query, args)

    if updated == 0:
      return []

    cursor.execute(
        "SELECT job, UNIX_TIMESTAMP(create_time), enabled,"
        "forced_run_requested, last_run_status, UNIX_TIMESTAMP(last_run_time), "
        "current_run_id, state, UNIX_TIMESTAMP(leased_until), leased_by "
        "FROM cron_jobs "
        "FORCE INDEX (cron_jobs_by_lease) "
        "WHERE leased_until=FROM_UNIXTIME(%s) AND leased_by=%s",
        [expiry_str, id_str])
    return [self._CronJobFromRow(row) for row in cursor.fetchall()]
1125287
def _update_job(self, target, args, kwargs):
        """"""
        target_path, options = get_function_path_and_options(target)

        assert isinstance(args, (tuple, list)) or args is None
        assert isinstance(kwargs, dict) or kwargs is None

        if options:
            self.update_options(**options)

        self._options['job'] = (target_path, args, kwargs)
1283815
def request_change_variable(self, py_db, seq, thread_id, frame_id, scope, attr, value):
        '''
        
        '''
        py_db.post_method_as_internal_command(
            thread_id, internal_change_variable, seq, thread_id, frame_id, scope, attr, value)
1017614
async def _handle_stat(self, core, opts):
        '''  '''
        prefix = opts.prefix
        crons = await core.listCronJobs()
        idens = [cron[0] for cron in crons]
        matches = [iden for iden in idens if iden.startswith(prefix)]
        if len(matches) == 0:
            self.printf('Error: provided iden does not match any valid authorized cron job')
            return
        elif len(matches) > 1:
            self.printf('Error: provided iden matches more than one cron job')
            return

        iden = matches[0]
        cron = [cron[1] for cron in crons if cron[0] == iden][0]

        user = cron.get('username') or '<None>'
        query = cron.get('query') or '<missing>'
        isrecur = 'Yes' if cron.get('recur') else 'No'
        startcount = cron.get('startcount') or 0
        recs = cron.get('recs', [])
        laststart = cron.get('laststarttime')
        lastend = cron.get('lastfinishtime')
        laststart = 'Never' if laststart is None else self._format_timestamp(laststart)
        lastend = 'Never' if lastend is None else self._format_timestamp(lastend)
        lastresult = cron.get('lastresult') or '<None>'

        self.printf(f'iden:            {iden}')
        self.printf(f'user:            {user}')
        self.printf(f'recurring:       {isrecur}')
        self.printf(f'# starts:        {startcount}')
        self.printf(f'last start time: {laststart}')
        self.printf(f'last end time:   {lastend}')
        self.printf(f'last result:     {lastresult}')
        self.printf(f'query:           {query}')
        if not recs:
            self.printf(f'entries:         <None>')
        else:
            self.printf(f'entries:         {"incunit":10} {"incval":6} {"required"}')
            for reqdict, incunit, incval in recs:
                reqdict = reqdict or '<None>'
                incunit = incunit or '<None>'
                incval = incval or '<None>'
                self.printf(f'                 {incunit:10} {incval:6} {reqdict}')
1324902
def DeleteCronJob(self, cronjob_id):
    """"""
    if cronjob_id not in self.cronjobs:
      raise db.UnknownCronJobError("Cron job %s not known." % cronjob_id)
    del self.cronjobs[cronjob_id]
    try:
      del self.cronjob_leases[cronjob_id]
    except KeyError:
      pass
    for job_run in self.ReadCronJobRuns(cronjob_id):
      del self.cronjob_runs[(cronjob_id, job_run.run_id)]
266398
def _replace_service_arg(self, name, index, args):
        
        args[index] = self.get_instantiated_service(name)
788068
public Cron map(final Cron cron) {
        Preconditions.checkNotNull(cron, "Cron must not be null");
        final List<CronField> fields = new ArrayList<>();
        for (final CronFieldName name : CronFieldName.values()) {
            if (mappings.containsKey(name)) {
                fields.add(mappings.get(name).apply(cron.retrieve(name)));
            }
        }
        return cronRules.apply(new SingleCron(to, fields)).validate();
    }
1051652
def call(self, routine, *args):
        

        (query, replacements) = self.__build_query(routine, args)

        return self.__execute_text(query, **replacements)
1041760
def WriteCronJobRun(self, run_object, cursor=None):
    """"""
    query = ("INSERT INTO cron_job_runs "
             "(job_id, run_id, write_time, run) "
             "VALUES (%s, %s, FROM_UNIXTIME(%s), %s) "
             "ON DUPLICATE KEY UPDATE "
             "run=VALUES(run), write_time=VALUES(write_time)")

    write_time_str = mysql_utils.RDFDatetimeToTimestamp(
        rdfvalue.RDFDatetime.Now())
    try:
      cursor.execute(query, [
          run_object.cron_job_id,
          db_utils.CronJobRunIDToInt(run_object.run_id),
          write_time_str,
          run_object.SerializeToString(),
      ])
    except MySQLdb.IntegrityError as e:
      raise db.UnknownCronJobError(
          "CronJob with id %s not found." % run_object.cron_job_id, cause=e)
1037631
def os_replace(src, dst):
    '''
    
    '''

    orig_os_replace_func = getattr(os, 'replace', None)

    if orig_os_replace_func is not None:
        # not need for emulation: we using modern version of Python.
        # fully atomic for this case

        orig_os_replace_func(src, dst)
        return

    if os.name == 'posix':
        # POSIX requirement: `os.rename(..)` works as `os.replace(..)`
        # fully atomic for this case

        os.rename(src, dst)
        return

    # simple emulation for `os.name == 'nt'` and other marginal
    # operation systems.  not fully atomic implementation for this
    # case

    try:
        # trying atomic `os.rename(..)` without `os.remove(..)` or
        # other operations

        os.rename(src, dst)
        error = None
    except OSError as e:
        error = e

    if error is None:
        return

    for i in range(5):
        # some number of tries may be failed
        # because we may be in concurrent environment with other
        # processes/threads

        try:
            os.remove(dst)
        except OSError:
            # destination was not exist
            # or concurrent process/thread is removing it in parallel with us
            pass

        try:
            os.rename(src, dst)
            error = None
        except OSError as e:
            error = e
            continue

        break

    if error is not None:
        raise_from(OSError('failed to replace'), error)
546065
def handle_routine(self, que, opts, host, target, mine=False):
        '''
        
        '''
        opts = copy.deepcopy(opts)
        single = Single(
                opts,
                opts['argv'],
                host,
                mods=self.mods,
                fsclient=self.fsclient,
                thin=self.thin,
                mine=mine,
                **target)
        ret = {'id': single.id}
        stdout, stderr, retcode = single.run()
        # This job is done, yield
        try:
            data = salt.utils.json.find_json(stdout)
            if len(data) < 2 and 'local' in data:
                ret['ret'] = data['local']
            else:
                ret['ret'] = {
                    'stdout': stdout,
                    'stderr': stderr,
                    'retcode': retcode,
                }
        except Exception:
            ret['ret'] = {
                'stdout': stdout,
                'stderr': stderr,
                'retcode': retcode,
            }
        que.put(ret)