Creates a new hunt.
10372
def _HandleLegacy(self, args, token=None):
    """"""

    # We only create generic hunts with /hunts/create requests.
    generic_hunt_args = rdf_hunts.GenericHuntArgs()
    generic_hunt_args.flow_runner_args.flow_name = args.flow_name
    generic_hunt_args.flow_args = args.flow_args

    # Clear all fields marked with HIDDEN, except for output_plugins - they are
    # marked HIDDEN, because we have a separate UI for them, not because they
    # shouldn't be shown to the user at all.
    #
    # TODO(user): Refactor the code to remove the HIDDEN label from
    # HuntRunnerArgs.output_plugins.
    args.hunt_runner_args.ClearFieldsWithLabel(
        rdf_structs.SemanticDescriptor.Labels.HIDDEN,
        exceptions="output_plugins")
    args.hunt_runner_args.hunt_name = standard.GenericHunt.__name__

    if args.original_hunt and args.original_flow:
      raise ValueError(
          "A hunt can't be a copy of a flow and a hunt at the same time.")
    if args.original_hunt:
      ref = rdf_hunts.FlowLikeObjectReference.FromHuntId(
          utils.SmartStr(args.original_hunt.hunt_id))
      args.hunt_runner_args.original_object = ref
    elif args.original_flow:
      ref = rdf_hunts.FlowLikeObjectReference.FromFlowIdAndClientId(
          utils.SmartStr(args.original_flow.flow_id),
          utils.SmartStr(args.original_flow.client_id))
      args.hunt_runner_args.original_object = ref

    # Anyone can create the hunt but it will be created in the paused
    # state. Permissions are required to actually start it.
    with implementation.StartHunt(
        runner_args=args.hunt_runner_args, args=generic_hunt_args,
        token=token) as hunt_obj:

      # Nothing really to do here - hunts are always created in the paused
      # state.
      logging.info("User %s created a new %s hunt (%s)", token.username,
                   hunt_obj.args.flow_runner_args.flow_name, hunt_obj.urn)

      return ApiHunt().InitFromAff4Object(hunt_obj, with_full_summary=True)
1193784
def shot_create_task(self, *args, **kwargs):
        
        if not self.cur_shot:
            return
        task = self.create_task(element=self.cur_shot)
        if task:
            taskdata = djitemdata.TaskItemData(task)
            treemodel.TreeItem(taskdata, self.shot_task_model.root)
1165372
def _Complete(self):
    """"""
    self._RemoveForemanRule()
    if "w" in self.hunt_obj.mode:
      self.hunt_obj.Set(self.hunt_obj.Schema.STATE("COMPLETED"))
      self.hunt_obj.Flush()
870861
def PauseHunt(hunt_id, reason=None):
  """"""

  hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
  if hunt_obj.hunt_state != hunt_obj.HuntState.STARTED:
    raise OnlyStartedHuntCanBePausedError(hunt_obj)

  data_store.REL_DB.UpdateHuntObject(
      hunt_id, hunt_state=hunt_obj.HuntState.PAUSED, hunt_state_comment=reason)
  data_store.REL_DB.RemoveForemanRule(hunt_id=hunt_obj.hunt_id)

  return data_store.REL_DB.ReadHuntObject(hunt_id)
1140529
def create(cls, path_name=None, name=None, project_id=None,
               log_modified_at=None, crawlable=True):
        """"""
        result = cls(path_name, name, project_id, log_modified_at, crawlable)

        db.session.add(result)
        db.session.commit()

        crawl_result(result, True)

        return result
117372
def _create_new(self, request):
        
        self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number)
        head = list(self._newpage_head)
        head.append(request.repo.testing.wiki(False))
        if not self.testmode:
            page = self.site.Pages[self.newpage]
            result = page.save('\n'.join(head), summary='Created by CI bot for unit test details.', bot=True)
            return result[u'result'] == u'Success'
        else:
            return '\n'.join(head)
800060
def WriteHuntObject(self, hunt_obj, cursor=None):
    """"""
    query = """
    INSERT INTO hunts (hunt_id, creator, description, duration_micros,
                       hunt_state,
                       client_rate, client_limit,
                       hunt)
    VALUES (%(hunt_id)s, %(creator)s, %(description)s, %(duration_micros)s,
            %(hunt_state)s,
            %(client_rate)s, %(client_limit)s,
            %(hunt)s)
    """

    args = {
        "hunt_id": db_utils.HuntIDToInt(hunt_obj.hunt_id),
        "creator": hunt_obj.creator,
        "description": hunt_obj.description,
        "duration_micros": hunt_obj.duration.microseconds,
        "hunt_state": int(rdf_hunt_objects.Hunt.HuntState.PAUSED),
        "client_rate": hunt_obj.client_rate,
        "client_limit": hunt_obj.client_limit,
        "hunt": hunt_obj.SerializeToString(),
    }

    try:
      cursor.execute(query, args)
    except MySQLdb.IntegrityError as error:
      raise db.DuplicatedHuntError(hunt_id=hunt_obj.hunt_id, cause=error)
956797
private Agent createAgent(Task forTask) {

		logger.debug("Creating new agent for task {}", forTask.getClass().getSimpleName());

		Agent agent = null;

		try {

			agent = lookupAgent(forTask);

			if (agent != null) {

				// register us in agent..
				agent.setAgentService(this);
			}

		} catch (Throwable t) {

			t.printStackTrace();
		}

		return (agent);
	}
596551
def new(*args, &block)
      instance = allocate.tap { |obj| obj.__send__(:initialize, *args, &block) }
      IceNine.deep_freeze(instance)
    end
548782
def UpdateHuntObject(self,
                       hunt_id,
                       duration=None,
                       client_rate=None,
                       client_limit=None,
                       hunt_state=None,
                       hunt_state_comment=None,
                       start_time=None,
                       num_clients_at_start_time=None,
                       cursor=None):
    """"""
    vals = []
    args = {}

    if duration is not None:
      vals.append("duration_micros = %(duration_micros)s")
      args["duration_micros"] = duration.microseconds

    if client_rate is not None:
      vals.append("client_rate = %(client_rate)s")
      args["client_rate"] = client_rate

    if client_limit is not None:
      vals.append("client_limit = %(client_limit)s")
      args["client_limit"] = client_limit

    if hunt_state is not None:
      vals.append("hunt_state = %(hunt_state)s")
      args["hunt_state"] = int(hunt_state)

    if hunt_state_comment is not None:
      vals.append("hunt_state_comment = %(hunt_state_comment)s")
      args["hunt_state_comment"] = hunt_state_comment

    if start_time is not None:
      vals.append("""
      init_start_time = IFNULL(init_start_time, FROM_UNIXTIME(%(start_time)s))
      """)
      vals.append("""
      last_start_time = FROM_UNIXTIME(%(start_time)s)
      """)
      args["start_time"] = mysql_utils.RDFDatetimeToTimestamp(start_time)

    if num_clients_at_start_time is not None:
      vals.append("num_clients_at_start_time = %(num_clients_at_start_time)s")
      args["num_clients_at_start_time"] = num_clients_at_start_time

    vals.append("last_update_timestamp = NOW(6)")

    query = """
    UPDATE hunts
       SET {updates}
     WHERE hunt_id = %(hunt_id)s
    """.format(updates=", ".join(vals))
    args["hunt_id"] = db_utils.HuntIDToInt(hunt_id)

    rows_modified = cursor.execute(query, args)
    if rows_modified == 0:
      raise db.UnknownHuntError(hunt_id)
1114803
def _ScheduleGenericHunt(hunt_obj):
  """"""
  # TODO: Migrate foreman conditions to use relation expiration
  # durations instead of absolute timestamps.
  foreman_condition = foreman_rules.ForemanCondition(
      creation_time=rdfvalue.RDFDatetime.Now(),
      expiration_time=hunt_obj.init_start_time + hunt_obj.duration,
      description="Hunt %s %s" % (hunt_obj.hunt_id, hunt_obj.args.hunt_type),
      client_rule_set=hunt_obj.client_rule_set,
      hunt_id=hunt_obj.hunt_id)

  # Make sure the rule makes sense.
  foreman_condition.Validate()

  data_store.REL_DB.WriteForemanRule(foreman_condition)
1134641
def create(self, destination, mask, next_hops=[]):
        """"""
        payload = {
            "rib": self._build_payload(destination, mask, next_hops)
        }

        return self._post(self.url_prefix, payload)
350187
def UpdateHuntObject(self,
                       hunt_id,
                       duration=None,
                       client_rate=None,
                       client_limit=None,
                       hunt_state=None,
                       hunt_state_comment=None,
                       start_time=None,
                       num_clients_at_start_time=None):
    """"""
    _ValidateHuntId(hunt_id)
    precondition.AssertOptionalType(duration, rdfvalue.Duration)
    precondition.AssertOptionalType(client_rate, (float, int))
    precondition.AssertOptionalType(client_limit, int)
    if hunt_state is not None:
      _ValidateEnumType(hunt_state, rdf_hunt_objects.Hunt.HuntState)
    precondition.AssertOptionalType(hunt_state_comment, str)
    precondition.AssertOptionalType(start_time, rdfvalue.RDFDatetime)
    precondition.AssertOptionalType(num_clients_at_start_time, int)

    return self.delegate.UpdateHuntObject(
        hunt_id,
        duration=duration,
        client_rate=client_rate,
        client_limit=client_limit,
        hunt_state=hunt_state,
        hunt_state_comment=hunt_state_comment,
        start_time=start_time,
        num_clients_at_start_time=num_clients_at_start_time)
1276407
def _spawn_new(self, count=1):
        """"""
        free = self.free_cells()
        for x, y in random.sample(free, min(count, len(free))):
            self.grid[y][x] = random.randint(0, 10) and 2 or 4
1099190
def _Process(self, request, responses, thread_pool=None, events=None):
    """"""
    # This function is called and runs within the main processing thread. We do
    # not need to lock the hunt object while running in this method.
    if request.next_state == "AddClient":
      if not self.IsHuntStarted():
        logging.debug(
            "Unable to start client %s on hunt %s which is in state %s",
            request.client_id, self.session_id,
            self.hunt_obj.Get(self.hunt_obj.Schema.STATE))
        return

      # Get the client count.
      client_count = int(
          self.hunt_obj.Get(self.hunt_obj.Schema.CLIENT_COUNT, 0))

      # Pause the hunt if we exceed the client limit.
      if 0 < self.runner_args.client_limit <= client_count:
        # Remove our rules from the foreman so we dont get more clients sent to
        # this hunt. Hunt will be paused.
        self.Pause()

        # Ignore this client since it had gone over the limit.
        return

      # Update the client count.
      self.hunt_obj.Set(self.hunt_obj.Schema.CLIENT_COUNT(client_count + 1))

      # Add client to list of clients and optionally run it
      # (if client_rate == 0).

      self._AddClient(request.client_id)
      return

    if request.next_state == "RegisterClient":
      state = self.hunt_obj.Get(self.hunt_obj.Schema.STATE)
      # This allows the client limit to operate with a client rate. We still
      # want clients to get registered for the hunt at times in the future.
      # After they have been run, hunts only ever go into the paused state by
      # hitting the client limit. If a user stops a hunt, it will go into the
      # "STOPPED" state.
      if state in ["STARTED", "PAUSED"]:
        self._RegisterAndRunClient(request.client_id)
      else:
        logging.debug(
            "Not starting client %s on hunt %s which is not running: %s",
            request.client_id, self.session_id,
            self.hunt_obj.Get(self.hunt_obj.Schema.STATE))
      return

    event = threading.Event()
    events.append(event)
    # In a hunt, all requests are independent and can be processed
    # in separate threads.
    thread_pool.AddTask(
        target=self.RunStateMethod,
        args=(request.next_state, request, responses, event),
        name="Hunt processing")
731907
def WriteHuntObject(self, hunt_obj):
    """"""
    if hunt_obj.hunt_id in self.hunts:
      raise db.DuplicatedHuntError(hunt_id=hunt_obj.hunt_id)

    clone = self._DeepCopy(hunt_obj)
    clone.create_time = rdfvalue.RDFDatetime.Now()
    clone.last_update_time = rdfvalue.RDFDatetime.Now()
    self.hunts[(hunt_obj.hunt_id)] = clone
771868
@Override
  public Request newRequest(URI uri) {
    Request request = super.newRequest(uri);
    Request.Listener listener = new HttpRequestListener(tracer.getCurrentSpan(), handler);
    request.listener(listener);
    request.onComplete((Response.CompleteListener) listener);
    request.onResponseContent((Response.ContentListener) listener);
    return request;
  }