Resolve a URN of a flow with this id belonging to a given cron job.
14639
def ResolveCronJobFlowURN(self, cron_job_id):
    """"""
    if not self._value:
      raise ValueError("Can't call ResolveCronJobFlowURN on an empty "
                       "client id.")

    return cron_job_id.ToURN().Add(self._value)
957339
def do_resolve(self, line):
        """"""
        pid, = self._split_args(line, 1, 0)
        self._command_processor.resolve(pid)
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
22042
public CronPattern getPattern(String id) {
		final int index = ids.indexOf(id);
		if (index > -1) {
			return getPattern(index);
		}
		return null;
	}
1348106
def _resolve_image(ret, image, client_timeout):
    '''
    
    '''
    image_id = __salt__['docker.resolve_image_id'](image)

    if image_id is False:
        if not __opts__['test']:
            # Image not pulled locally, so try pulling it
            try:
                pull_result = __salt__['docker.pull'](
                    image,
                    client_timeout=client_timeout,
                )
            except Exception as exc:
                raise CommandExecutionError(
                    'Failed to pull {0}: {1}'.format(image, exc)
                )
            else:
                ret['changes']['image'] = pull_result
                # Try resolving again now that we've pulled
                image_id = __salt__['docker.resolve_image_id'](image)
                if image_id is False:
                    # Shouldn't happen unless the pull failed
                    raise CommandExecutionError(
                        'Image \'{0}\' not present despite a docker pull '
                        'raising no errors'.format(image)
                    )
    return image_id
758897
def UpdateFlow(self,
                 client_id,
                 flow_id,
                 flow_obj=db.Database.unchanged,
                 flow_state=db.Database.unchanged,
                 client_crash_info=db.Database.unchanged,
                 pending_termination=db.Database.unchanged,
                 processing_on=db.Database.unchanged,
                 processing_since=db.Database.unchanged,
                 processing_deadline=db.Database.unchanged):
    """"""

    try:
      flow = self.flows[(client_id, flow_id)]
    except KeyError:
      raise db.UnknownFlowError(client_id, flow_id)

    if flow_obj != db.Database.unchanged:
      self.flows[(client_id, flow_id)] = flow_obj
      flow = flow_obj

    if flow_state != db.Database.unchanged:
      flow.flow_state = flow_state
    if client_crash_info != db.Database.unchanged:
      flow.client_crash_info = client_crash_info
    if pending_termination != db.Database.unchanged:
      flow.pending_termination = pending_termination
    if processing_on != db.Database.unchanged:
      flow.processing_on = processing_on
    if processing_since != db.Database.unchanged:
      flow.processing_since = processing_since
    if processing_deadline != db.Database.unchanged:
      flow.processing_deadline = processing_deadline
    flow.last_update_time = rdfvalue.RDFDatetime.Now()
665610
def resolve(self, path):
        '''
        
        '''
        match = super().resolve(path)
        if match:
            try:
                routing_data = RoutingData(
                    match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'],
                    match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'],
                    match.kwargs.pop('dmp_function', None) or 'process_request',
                    match.kwargs.pop('dmp_urlparams', '').strip(),
                )
                if VERSION < (2, 2):
                    return ResolverMatch(
                        RequestViewWrapper(routing_data),
                        match.args,
                        match.kwargs,
                        url_name=match.url_name,
                        app_names=routing_data.app,
                    )
                else:
                    return ResolverMatch(
                        RequestViewWrapper(routing_data),
                        match.args,
                        match.kwargs,
                        url_name=match.url_name,
                        app_names=routing_data.app,
                        route=str(self.pattern),
                    )
            except ViewDoesNotExist as vdne:
                # we had a pattern match, but we couldn't get a callable using kwargs from the pattern
                # create a "pattern" so the programmer can see what happened
                # this is a hack, but the resolver error page doesn't give other options.
                # the sad face is to catch the dev's attention in Django's printout
                msg = "◉︵◉ Pattern matched, but discovery failed: {}".format(vdne)
                log.debug("%s %s", match.url_name, msg)
                raise Resolver404({
                    # this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x
                    'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]],
                    'path': path,
                })
        raise Resolver404({'path': path})
1277081
def _LoadFlows(self, client_id, min_create_time, token):
    
    if data_store.RelationalDBEnabled():
      if isinstance(client_id, rdfvalue.RDFURN):
        client_id = client_id.Basename()

      flow_list = data_store.REL_DB.ReadAllFlowObjects(
          client_id=client_id,
          min_create_time=min_create_time,
          include_child_flows=False)
      for flow_obj in flow_list:
        yield flow_obj
    else:
      now = rdfvalue.RDFDatetime.Now()
      client_id_urn = rdf_client.ClientURN(client_id)
      flows_dir = aff4.FACTORY.Open(client_id_urn.Add("flows"), token=token)
      # Save DB roundtrips by checking both conditions at once.
      flow_list = flows_dir.ListChildren(
          age=(min_create_time.AsMicrosecondsSinceEpoch(),
               now.AsMicrosecondsSinceEpoch()))
      for flow_obj in aff4.FACTORY.MultiOpen(flow_list, token=token):
        yield rdf_flow_objects.Flow(
            args=flow_obj.args,
            flow_class_name=flow_obj.runner_args.flow_name,
            flow_id=flow_obj.urn.Basename(),
            create_time=flow_obj.context.create_time,
            creator=flow_obj.creator,
        )
1276216
function (identifierUrn) {
    if (identifierUrn) {
      var path = this.constructPath(constants.IDENTIFIERS, identifierUrn);
      return this.Core.DELETE(path);
    } else {
      return this.rejectRequest('Bad request: An identifier URN is required.');
    }
  }
916868
def _ScheduleVariableHunt(hunt_obj):
  """"""
  if hunt_obj.client_rate != 0:
    raise VariableHuntCanNotHaveClientRateError(hunt_obj.hunt_id,
                                                hunt_obj.client_rate)

  seen_clients = set()
  for flow_group in hunt_obj.args.variable.flow_groups:
    for client_id in flow_group.client_ids:
      if client_id in seen_clients:
        raise CanStartAtMostOneFlowPerClientError(hunt_obj.hunt_id, client_id)
      seen_clients.add(client_id)

  now = rdfvalue.RDFDatetime.Now()
  for flow_group in hunt_obj.args.variable.flow_groups:
    flow_cls = registry.FlowRegistry.FlowClassByName(flow_group.flow_name)
    flow_args = flow_group.flow_args if flow_group.HasField(
        "flow_args") else None

    for client_id in flow_group.client_ids:
      flow.StartFlow(
          client_id=client_id,
          creator=hunt_obj.creator,
          cpu_limit=hunt_obj.per_client_cpu_limit,
          network_bytes_limit=hunt_obj.per_client_network_bytes_limit,
          flow_cls=flow_cls,
          flow_args=flow_args,
          # Setting start_at explicitly ensures that flow.StartFlow won't
          # process flow's Start state right away. Only the flow request
          # will be scheduled.
          start_at=now,
          parent_hunt_id=hunt_obj.hunt_id)
122206
def prevId(self):
        
        if self._prev_id is False:
            # Request the next urn
            self._prev_id, self._next_id = self.getPrevNextUrn(reference=self.urn.reference)
        return self._prev_id
732182
def KillOldFlows(self):
    
    if not self.IsRunning():
      return False

    start_time = self.Get(self.Schema.LAST_RUN_TIME)
    lifetime = self.Get(self.Schema.CRON_ARGS).lifetime

    elapsed = rdfvalue.RDFDatetime.Now() - start_time

    if lifetime and elapsed > lifetime:
      self.StopCurrentRun()
      stats_collector_instance.Get().IncrementCounter(
          "cron_job_timeout", fields=[self.urn.Basename()])
      stats_collector_instance.Get().RecordEvent(
          "cron_job_latency", elapsed.seconds, fields=[self.urn.Basename()])
      return True

    return False
884487
def _ExtractClientIdFromPath(entry, event):
  """"""
  match = re.match(r".*(C\.[0-9a-fA-F]{16}).*", entry.http_request_path)
  if match:
    event.client = match.group(1)
479640
private static water.Job resolveJob(JobId request) {
    String strId = request.getJobId();
    Value val = DKV.get(Key.make(strId));
    if (val == null) {
      throw new IllegalArgumentException("Job " + strId + " not found in the DKV");
    }
    Iced iced = val.get();
    if (iced instanceof Job) {
      return (water.Job) iced;
    } else {
      throw new IllegalArgumentException("Id " + strId + " does not reference a Job but a " + iced.getClass());
    }
  }
86527
function(id, crons) {
  for(var i=0, l=crons.length; i<l; i++) {
    if(id === crons[i].id) {
      return true;
    }
  }
  return false;
}
326283
def InferUserAndSubjectFromUrn(self):
    """"""
    _, cron_str, cron_job_name, user, _ = self.urn.Split(5)

    if cron_str != "cron":
      raise access_control.UnauthorizedAccess(
          "Approval object has invalid urn %s." % self.urn,
          requested_access=self.token.requested_access)

    return (user, aff4.ROOT_URN.Add("cron").Add(cron_job_name))
1345234
def root_urns_for_deletion(self):
    """"""
    roots = set()
    for urn in self._urns_for_deletion:
      new_root = True

      str_urn = utils.SmartUnicode(urn)
      fake_roots = []
      for root in roots:
        str_root = utils.SmartUnicode(root)

        if str_urn.startswith(str_root):
          new_root = False
          break
        elif str_root.startswith(str_urn):
          fake_roots.append(root)

      if new_root:
        roots -= set(fake_roots)
        roots.add(urn)

    return roots