Remove jobs from the queue.

    CLI Example:

    .. code-block:: bash

        salt '*' at.atrm <jobid> <jobid> .. <jobid>
        salt '*' at.atrm all
        salt '*' at.atrm all [tag]
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
380647
def delete_job(self, id, jobstore=None):
        
        warnings.warn('delete_job has been deprecated, use remove_job instead.', DeprecationWarning)

        self.remove_job(id, jobstore)
357783
def DeleteJob(self, job_id, token=None):
    """"""
    job_urn = self.CRON_JOBS_PATH.Add(job_id)
    aff4.FACTORY.Delete(job_urn, token=token)
848954
def cancel_job(self, job_id=None, job_name=None):
        
        payload = {}
        if job_name is not None:
            payload['job_name'] = job_name
        if job_id is not None:
            payload['job_id'] = job_id

        jobs_url = self._get_url('jobs_path')
        res = self.rest_client.session.delete(jobs_url, params=payload)
        _handle_http_errors(res)
        return res.json()
710774
def unblockall(self):
        '''
        
        '''
        for q in self.queues.values():
            q.unblockall()
        self.blockEvents.clear()
826802
def pop(self, queue_name):
        
        self._only_watch_from(queue_name)
        job = self.conn.reserve(timeout=0)
        job.delete()
        return job.body
520732
def job_remove_tags(object_id, input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/%s/removeTags' % object_id, input_params, always_retry=always_retry, **kwargs)
108639
def delete(self, job_ids, array_ids = None, delete_logs = True, delete_log_dir = False, status = Status, delete_jobs = True):
    """"""
    def _delete_dir_if_empty(log_dir):
      if log_dir and delete_log_dir and os.path.isdir(log_dir) and not os.listdir(log_dir):
        os.rmdir(log_dir)
        logger.info("Removed empty log directory '%s'" % log_dir)

    def _delete(job, try_to_delete_dir=False):
      # delete the job from the database
      if delete_logs:
        self.delete_logs(job)
        if try_to_delete_dir:
          _delete_dir_if_empty(job.log_dir)
      if delete_jobs:
        self.session.delete(job)


    self.lock()

    # check if array ids are specified
    if array_ids:
      if len(job_ids) != 1: logger.error("If array ids are specified exactly one job id must be given.")
      array_jobs = list(self.session.query(ArrayJob).join(Job).filter(Job.unique.in_(job_ids)).filter(Job.unique == ArrayJob.job_id).filter(ArrayJob.id.in_(array_ids)))
      if array_jobs:
        job = array_jobs[0].job
        for array_job in array_jobs:
          if array_job.status in status:
            if delete_jobs:
              logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
            _delete(array_job)
        if not job.array:
          if job.status in status:
            if delete_jobs:
              logger.info("Deleting job '%d' from the database." % job.unique)
            _delete(job, delete_jobs)

    else:
      # iterate over all jobs
      jobs = self.get_jobs(job_ids)
      for job in jobs:
        # delete all array jobs
        if job.array:
          for array_job in job.array:
            if array_job.status in status:
              if delete_jobs:
                logger.debug("Deleting array job '%d' of job '%d' from the database." % (array_job.id, job.unique))
              _delete(array_job)
        # delete this job
        if job.status in status:
          if delete_jobs:
            logger.info("Deleting job '%d' from the database." % job.unique)
          _delete(job, delete_jobs)

    self.session.commit()
    self.unlock()
562444
def kill_all_jobs():
    '''
    
    '''
    # Some OS's (Win32) don't have SIGKILL, so use salt_SIGKILL which is set to
    # an appropriate value for the operating system this is running on.
    ret = []
    for data in running():
        ret.append(signal_job(data['jid'], salt_SIGKILL))
    return ret
229430
def pop(queue, quantity=1, is_runner=False):
    '''
    
    '''
    cmd = 'SELECT id, data FROM {0}'.format(queue)
    if quantity != 'all':
        try:
            quantity = int(quantity)
        except ValueError as exc:
            error_txt = ('Quantity must be an integer or "all".\n'
                         'Error: "{0}".'.format(exc))
            raise SaltInvocationError(error_txt)
        cmd = ''.join([cmd, ' LIMIT {0};'.format(quantity)])
    log.debug('SQL Query: %s', cmd)
    items = []
    with _conn(commit=True) as cur:
        cur.execute(cmd)
        result = cur.fetchall()
        if result:
            ids = [six.text_type(item[0]) for item in result]
            items = [item[1] for item in result]
            idlist = "','".join(ids)
            del_cmd = '''DELETE FROM {0} WHERE id IN ('{1}');'''.format(
                queue, idlist)

            log.debug('SQL Query: %s', del_cmd)

            cur.execute(del_cmd)
    return items
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}
436317
def kill(self, job_id):
        
        check_jobid(job_id)

        queue = self._get_queue()
        if queue is None:
            raise QueueDoesntExist

        ret, output = self._call('%s %s' % (
                                 shell_escape(queue / 'commands/kill'),
                                 job_id),
                                 False)
        if ret == 3:
            raise JobNotFound
        elif ret != 0:
            raise RemoteCommandFailure(command='commands/kill',
                                       ret=ret)
929431
def clear(self, tag=None):
        
        if tag is None:
            del self.jobs[:]
        else:
            self.jobs[:] = (job for job in self.jobs if tag not in job.tags)
1135094
def cleanup(self):
        

        pending_exits_to_remove = defaultdict(list)

        for func_addr in self._updated_functions:
            if func_addr not in self._jobs:
                continue
            jobs = self._jobs[func_addr]
            for i, pe in enumerate(jobs):
                if pe.returning_source is None:
                    # The original call failed. This pending exit must be followed.
                    continue

                func = self._functions.function(pe.returning_source)
                if func is None:
                    # Why does it happen?
                    l.warning("An expected function at %s is not found. Please report it to Fish.",
                              pe.returning_source if pe.returning_source is not None else 'None')
                    continue

                if func.returning is False:
                    # Oops, it's not returning
                    # Remove this pending exit
                    pending_exits_to_remove[pe.returning_source].append(i)

        for func_addr, indices in pending_exits_to_remove.items():
            jobs = self._jobs[func_addr]
            for index in reversed(indices):
                job = jobs[index]
                self._deregister_job_callback(job.func_addr, job)
                del jobs[index]
                self._job_count -= 1
            if not jobs:
                del self._jobs[func_addr]

        self.clear_updated_functions()
21321
def delete(self, job: JobOrID) -> None:
        
        self._send_cmd(b'delete %d' % _to_id(job), b'DELETED')
371817
def purge(options = {})
      options = options.merge(queue_url: @url)
      resp = @client.purge_queue(options)
      resp.data
    end
358875
def delete_job(self, job_id):
        """"""
        if hasattr(job_id, 'job_id'):
            job_id = job_id.job_id
        with self._sock_ctx() as socket:
            self._send_message('delete {0}'.format(job_id), socket)
            self._receive_word(socket, b'DELETED')