Send the result of a job back to the backend. Must be called *once and only once* for each job
        :exception JobNotRunningException: is raised when send_job_result is called more than once for a given job_id
346722
async def send_job_result(self, job_id: BackendJobId, result: str, text: str = "", grade: float = None, problems: Dict[str, SPResult] = None,
                              tests: Dict[str, Any] = None, custom: Dict[str, Any] = None, state: str = "", archive: Optional[bytes] = None,
                              stdout: Optional[str] = None, stderr: Optional[str] = None):
        
        if job_id not in self.__running_job:
            raise JobNotRunningException()
        del self.__running_job[job_id]

        if grade is None:
            if result == "success":
                grade = 100.0
            else:
                grade = 0.0
        if problems is None:
            problems = {}
        if custom is None:
            custom = {}
        if tests is None:
            tests = {}

        await ZMQUtils.send(self.__backend_socket, AgentJobDone(job_id, (result, text), round(grade, 2), problems, tests, custom, state, archive, stdout, stderr))
494093
def _serialiseExistingJob(self, jobGraph, jobStore, returnValues):
        
        self._serialiseJobGraph(jobGraph, jobStore, returnValues, False)
        #Drop the completed command, if not dropped already
        jobGraph.command = None
        #Merge any children (follow-ons) created in the initial serialisation
        #with children (follow-ons) created in the subsequent scale-up.
        assert len(jobGraph.stack) >= 4
        combinedChildren = jobGraph.stack[-1] + jobGraph.stack[-3]
        combinedFollowOns = jobGraph.stack[-2] + jobGraph.stack[-4]
        jobGraph.stack = jobGraph.stack[:-4]
        if len(combinedFollowOns) > 0:
            jobGraph.stack.append(combinedFollowOns)
        if len(combinedChildren) > 0:
            jobGraph.stack.append(combinedChildren)
20429
def wait_for_jobs(jobs):
    

    all_running = False
    while not all_running:
        all_running = True
        time.sleep(5)
        for job in jobs:
            job.refresh()
            scheduled = getattr(job, "scheduled_at", None)
            if scheduled is not None:
                logger.info("Waiting for %s on %s [%s]" % (job.uid,
                                                           job.site,
                                                           _date2h(scheduled)))
            all_running = all_running and job.state == "running"
            if job.state == "error":
                raise Exception("The job %s is in error state" % job)
    logger.info("All jobs are Running !")
539353
def run_with_retry(&block)
      Log.debug "Running job '#{@job_id}' with status '#{@status}'"
      # If we are not the first job in this group, wait @delay
      ChimpDaemon.instance.semaphore.synchronize do
        if @group.started >= @concurrency && @delay.nonzero?
          Log.info "[#{@job_uuid}] Sleeping #{@delay} seconds between tasks"
          sleep @delay
        end
        @group.started += 1
      end

      @status = STATUS_RUNNING
      @time_start = Time.now

      Log.info self.describe_work_start unless @quiet

      #
      # The inner level of exception handling here tries to catch anything
      # that can be easily retired or failed-- normal exceptions.
      #
      # The outer level of exception handling handles weird stuff; for example,
      # sometimes rest_connection raises RuntimeError exceptions...
      #
      # This fixes acu75562.
      #
      begin
        begin
          yield if not @dry_run

          if @owner != nil
            @status = STATUS_DONE
            @group.job_completed
          else
            Log.warn "[#{@job_uuid}][#{@job_id}] Ownership of job_id #{job_id} lost. User cancelled operation?"
          end

        rescue SystemExit, Interrupt => ex
          $stderr.puts 'Exiting!'
          raise ex

        rescue Interrupt => ex
          name = @array['name'] if @array
          name = @server['name'] || @server['nickname'] if @server
          Log.error self.describe_work_error

          if @retry_count > 0
            @status = STATUS_RETRYING
            Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\". Retrying in #{@retry_sleep} seconds..."
            @retry_count -= 1
            sleep @retry_sleep
            retry
          end

          @status = STATUS_ERROR
          @error = ex
          Log.error "[#{@job_uuid}][#{@job_id}] Error executing on \"#{name}\": #{ex}"

        ensure
          @time_end = Time.now
          Log.info self.describe_work_done unless @quiet
        end

      rescue RuntimeError => ex
        err = ex.message + "IP: #{@server.params["ip_address"]}\n" if @server.params['ip_address']
        err += " Group: #{@group.group_id}\n" if @group.group_id
        err += " Notes: #{@job_notes}\n" if @job_notes
        err += " Notes: #{@job_notes}\n" if @job_notes
        Log.error "[#{@job_uuid}][#{@job_id}] Caught RuntimeError: #{err} Job failed.\n"
        @status = STATUS_ERROR
        @error = ex
      end
    end
137119
def add_job(self, job):
        
        self.cur.execute("INSERT INTO jobs VALUES(?,?,?,?,?)", (
            job["id"], job["description"], job["last-run"], job["next-run"], job["last-run-result"]))

        return True
621297
def run_job(clusterID, packageID, args = {})
      query = args.inject({}) {|v, kv|
        v.merge(
          {
            "job[variables][#{kv.first}]" => kv.last
          })
      }
      query = query.merge(
        {
          'job[cluster_id]' => clusterID,
          'job[package_id]' => packageID
        })

      request(
        :expects => 201,
        :method => :post,
        :path => "/#{account_id}/api/jobs",
        :query => query
      )
    end
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()
1368214
def run_queue(self, pool):
        
        def callback(result):
            """Note: mark_done, at a minimum, must happen here or dbt will
            deadlock during ephemeral result error handling!
            """
            self._handle_result(result)
            self.job_queue.mark_done(result.node.unique_id)

        while not self.job_queue.empty():
            node = self.job_queue.get()
            self._raise_set_error()
            runner = self.get_runner(node)
            # we finally know what we're running! Make sure we haven't decided
            # to skip it due to upstream failures
            if runner.node.unique_id in self._skipped_children:
                cause = self._skipped_children.pop(runner.node.unique_id)
                runner.do_skip(cause=cause)
            args = (runner,)
            self._submit(pool, args, callback)

        # block on completion
        self.job_queue.join()
        # if an error got set during join(), raise it.
        self._raise_set_error()

        return
1209121
protected void success(final Job job, final Object runner, final Object result, final String curQueue) {
        try {
            PoolUtils.doWorkInPool(this.jedisPool, new PoolWork<Jedis, Void>() {
                /**
                 * {@inheritDoc}
                 */
                @Override
                public Void doWork(final Jedis jedis) {
                    jedis.incr(key(STAT, PROCESSED));
                    jedis.incr(key(STAT, PROCESSED, name));
                    return null;
                }
            });
        } catch (JedisException je) {
            LOG.warn("Error updating success stats for job=" + job, je);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        this.listenerDelegate.fireEvent(JOB_SUCCESS, this, curQueue, job, runner, result, null);
    }
1118499
def requeue_job(self, job, queue, priority, delayed_for=None):
        
        job.requeue(queue_name=queue._cached_name,
                    priority=priority,
                    delayed_for=delayed_for,
                    queue_model=self.queue_model)

        if hasattr(job, 'on_requeued'):
            job.on_requeued(queue)

        self.log(self.job_requeue_message(job, queue))
1194216
def _get_job_results(query=None):
    '''
    
    '''
    if not query:
        raise CommandExecutionError("Query parameters cannot be empty.")

    response = __proxy__['panos.call'](query)

    # If the response contains a job, we will wait for the results
    if 'result' in response and 'job' in response['result']:
        jid = response['result']['job']

        while get_job(jid)['result']['job']['status'] != 'FIN':
            time.sleep(5)

        return get_job(jid)
    else:
        return response
402172
function JobQueue (job, callback) {
     // ignore null job but notify the queue.
     var device;

    if (job === null) {
         callback (null);
         return;
    }
    
    var gateway = job.gateway;
    var status = 0;
    
    // set few defaults
    if (job.timeout === undefined) job.timeout=0;  // no retry
    if (job.retry   === undefined) job.retry  =0;  // retry counter
    if (job.args    === undefined) job.args   =""; // optional arguments
    
    gateway.Debug (4,"Queue Request=%s DevId=%s Command=%s Retry=%d", job.request, job.devId, job.command, job.retry);
    
    // broadcast command loop on active device list to split commands
    if (parseInt (job.devId) === 0) {
        var subrqst=1;
        for (var devid in gateway.activeClients) {
            // we only broadcast to device with a valid TCP session
            if (device && device.socket !== null) {
                var request = {
                  gateway : job.gateway,
                  devId  : gateway.activeClients[devid].devid,
                  command: job.command,
                  request: [job.request, subrqst++],
                  retry  : job.retry, 
                  timeout: job.timeout
                };
            gateway.queue.push (request, JobCallback); // broadcast to all active devices
            }
        }
        var broadcast = {
            gateway  : job.gateway,
            command : 'Broadcast',
            request : [request, subrqst++]
        };
        callback (broadcast);
        return;
    };
    
    // search for devId withing global active devices list
    if (gateway.activeClients [job.devId] !== undefined) {
        // device is present check if it is logged
        gateway.Debug (5,"Queue Request=%s DevId=%s Command=%s args=%s Sent", job.request, job.devId, job.command, job.args);
        device  = gateway.activeClients [job.devId];
        status  = device.RequestAction (job.command, job.args);
    } else {
        gateway.event.emit ("queue","NOTLOG",job);
        status = 1; // device not present in active list
    }

    // process status result and notify callback function
    switch (status) {
        case 0 : // command was accepted by device
            // wait JOB_QUEUE_PAUSE time before processing Job next request
            gateway.queue.pause ();
            setTimeout(function () {gateway.queue.resume();}, JOB_QUEUE_TIMER);
            gateway.event.emit ("queue", "ACCEPT", job);
            break;
            
        case 1: // device not present command will be retry later  
            if (job.timeout === 0) break;     // no retry
            if (job.timeout >= new Date()) {  // check time out and either push or notify users
                job.retry ++;
                gateway.event.emit ("queue", "RETRY", job);
                setTimeout(function () {gateway.queue.push (job, JobCallback);}, JOB_RETRY_TIMER);
            } else {
                gateway.event.emit ("queue", "TIMEOUT", job);
            }                
            break;
               
        case -1 : // device exits but command was refused
            gateway.event.emit ("queue", "REFUSED", job);
            break;
            
        case -2 : // device does not exist in active device list
            gateway.event.emit ("queue", "UNKNOWN", job);
            break;
               
        default:
            gateway.Debug (2,"Hoops invalid status code: Device DevId=%s Status=%s", job.devId, status);
            break;
    }
    callback (job);
}
1280310
function JobCallback (job) {
    if (job !== null) {
       job.gateway.Debug (6,"Queued Request:%s command=%s devid=%s [done]", job.request, job.command, job.devId);
    }
}
1272037
@NotOnCli
  public JobExecutionResult run() throws InterruptedException, TimeoutException, ExecutionException {
    JobExecutionDriver jobDriver = runAsync();
    return jobDriver.get(this.jobTimeout.getTimeout(), this.jobTimeout.getTimeUnit());
  }
752510
def send_to_backends(self, event):
        

        for name, backend in six.iteritems(self.backends):
            try:
                backend.send(event)
            except Exception:  # pylint: disable=broad-except
                LOG.exception(
                    'Unable to send event to backend: %s', name
                )
1301970
def add_result(self, job):
        
        self.cur.execute(
            "INSERT INTO history VALUES(?,?,?,?)",
            (job["id"], job["description"], job["last-run"], job["last-run-result"]))

        return True
286537
def update(self, job):
        
        self.cur.execute('''UPDATE jobs
            SET last_run=?,next_run=?,last_run_result=? WHERE hash=?''', (
            job["last-run"], job["next-run"], job["last-run-result"], job["id"]))