Process a single GRR client.

    Args:
      client: a GRR client object.
517780
def _process_thread(self, client):
    
    system_type = client.data.os_info.system
    print('System type: {0:s}'.format(system_type))

    # If the list is supplied by the user via a flag, honor that.
    artifact_list = []
    if self.artifacts:
      print('Artifacts to be collected: {0!s}'.format(self.artifacts))
      artifact_list = self.artifacts
    else:
      default_artifacts = self.artifact_registry.get(system_type, None)
      if default_artifacts:
        print('Collecting default artifacts for {0:s}: {1:s}'.format(
            system_type, ', '.join(default_artifacts)))
        artifact_list.extend(default_artifacts)

    if self.extra_artifacts:
      print('Throwing in an extra {0!s}'.format(self.extra_artifacts))
      artifact_list.extend(self.extra_artifacts)
      artifact_list = list(set(artifact_list))

    if not artifact_list:
      return

    flow_args = flows_pb2.ArtifactCollectorFlowArgs(
        artifact_list=artifact_list,
        use_tsk=self.use_tsk,
        ignore_interpolation_errors=True,
        apply_parsers=False)
    flow_id = self._launch_flow(client, 'ArtifactCollectorFlow', flow_args)
    self._await_flow(client, flow_id)
    collected_flow_data = self._download_files(client, flow_id)
    if collected_flow_data:
      print('{0!s}: Downloaded: {1:s}'.format(flow_id, collected_flow_data))
      fqdn = client.data.os_info.fqdn.lower()
      self.state.output.append((fqdn, collected_flow_data))
1329941
def client_connected(
        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
    ) -> None:
        
        self.reader = reader
        self.writer = writer
1069752
def incr(name, value=1, rate=1, tags=None):
    
    client().incr(name, value, rate, tags)
100614
def client_call(method, *args)
      key = cache_key(method, args)
      cached = dalli.get(key)
      return cached if cached
      response = client.send(method, *args)
      dalli.set(key, response)
      response
    end
1003825
async def process(client: Client, transaction_signed_raw: str) -> ClientResponse:
    
    return await client.post(MODULE + '/process', {'transaction': transaction_signed_raw}, rtype=RESPONSE_AIOHTTP)
528906
def _process(self, data):
        
        try:
            packet = json.loads(data)
        except ValueError:
            # So far, this never happened. But it would be good to have some
            # protection.
            logger.warning('Received invalid JSON from client. Ignoring.')
            return

        # Handle commands.
        if packet['cmd'] == 'run-command':
            self._run_command(packet)

        # Handle stdin.
        elif packet['cmd'] == 'in':
            self._pipeinput.send_text(packet['data'])

#        elif packet['cmd'] == 'flush-input':
#            self._inputstream.flush()  # Flush escape key.  # XXX: I think we no longer need this.

        # Set size. (The client reports the size.)
        elif packet['cmd'] == 'size':
            data = packet['data']
            self.size = Size(rows=data[0], columns=data[1])
            self.pymux.invalidate()

        # Start GUI. (Create CommandLineInterface front-end for pymux.)
        elif packet['cmd'] == 'start-gui':
            detach_other_clients = bool(packet['detach-others'])
            color_depth = packet['color-depth']
            term = packet['term']

            if detach_other_clients:
                for c in self.pymux.connections:
                    c.detach_and_close()

            print('Create app...')
            self._create_app(color_depth=color_depth, term=term)
899911
private function processSignature(\Skeleton\SDK\Common\Client &$client)
    {
        // Proceed with the signature
        switch ($this->client->getConfig()['method']) {
            case 'hmac':
                Hmac::init($client, $this->request);
                break;
        }
    }
1344103
def handle_subscribe(client, data)
      topic = @engine.subscribe_client_to_topic client, data[0]

      trigger(:subscribe, client, topic.uri)
    end
1228950
def _build_client(self, name=None):
        
        url_path = self._url_path + [name] if name else self._url_path
        return Client(host=self.host,
                      version=self._version,
                      request_headers=self.request_headers,
                      url_path=url_path,
                      append_slash=self.append_slash,
                      timeout=self.timeout)
599996
def get_results(self, client):
        
        data = self._request('GET', '/results/{}'.format(client))
        return data.json()
477962
def call_receivers(self, client, clients_list, message):
        
        # Try to parse JSON
        try:
            json_message = json.loads(message)
        except ValueError:
            json_message = None

        for func, to_json in self.receivers:

            # Check if json version is available
            if to_json:
                if json_message is None:
                    continue
                msg = json_message
            else:
                msg = message

            # Call callback
            func(client, clients_list, msg)
305524
def AssignTasksToClient(self, client_id):
    
    rules = self.Get(self.Schema.RULES)
    if not rules:
      return 0

    if data_store.RelationalDBEnabled():
      last_foreman_run = self._GetLastForemanRunTimeRelational(client_id)
    else:
      last_foreman_run = self._GetLastForemanRunTime(client_id)

    latest_rule = max(rule.created for rule in rules)

    if latest_rule <= last_foreman_run:
      return 0

    # Update the latest checked rule on the client.
    if data_store.RelationalDBEnabled():
      try:
        self._SetLastForemanRunTimeRelational(client_id, latest_rule)
      except db.UnknownClientError:
        pass

    # If the relational db is used for reads, we don't have to update the
    # aff4 object.
    if not data_store.RelationalDBEnabled():
      self._SetLastForemanRunTime(client_id, latest_rule)

    relevant_rules = []
    expired_rules = False

    now = time.time() * 1e6

    for rule in rules:
      if rule.expires < now:
        expired_rules = True
        continue
      if rule.created <= int(last_foreman_run):
        continue

      relevant_rules.append(rule)

    if data_store.RelationalDBEnabled():
      client_data = data_store.REL_DB.ReadClientFullInfo(client_id)
      if client_data is None:
        return
    else:
      client_data = aff4.FACTORY.Open(client_id, mode="rw", token=self.token)

    actions_count = 0
    for rule in relevant_rules:
      if self._EvaluateRules(rule, client_data):
        actions_count += self._RunActions(rule, client_id)

    if expired_rules:
      self.ExpireRules()

    return actions_count
394209
def create_client(self) -> "google.cloud.storage.Client":
        
        # Client should be imported here because grpc starts threads during import
        # and if you call fork after that, a child process will be hang during exit
        from google.cloud.storage import Client
        if self.credentials:
            client = Client.from_service_account_json(self.credentials)
        else:
            client = Client()
        return client
664098
def StartHuntFlowOnClient(client_id, hunt_id):
  """"""

  hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id)
  hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj)
  # There may be a little race between foreman rules being removed and
  # foreman scheduling a client on an (already) paused hunt. Making sure
  # we don't lose clients in such a race by accepting clients for paused
  # hunts.
  if not rdf_hunt_objects.IsHuntSuitableForFlowProcessing(hunt_obj.hunt_state):
    return

  if hunt_obj.args.hunt_type == hunt_obj.args.HuntType.STANDARD:
    hunt_args = hunt_obj.args.standard

    if hunt_obj.client_rate > 0:
      # Given that we use caching in _GetNumClients and hunt_obj may be updated
      # in another process, we have to account for cases where num_clients_diff
      # may go below 0.
      num_clients_diff = max(
          0,
          _GetNumClients(hunt_obj.hunt_id) - hunt_obj.num_clients_at_start_time)
      next_client_due_msecs = int(
          num_clients_diff / hunt_obj.client_rate * 60e6)

      start_at = rdfvalue.RDFDatetime.FromMicrosecondsSinceEpoch(
          hunt_obj.last_start_time.AsMicrosecondsSinceEpoch() +
          next_client_due_msecs)
    else:
      start_at = None

    # TODO(user): remove client_rate support when AFF4 is gone.
    # In REL_DB always work as if client rate is 0.

    flow_cls = registry.FlowRegistry.FlowClassByName(hunt_args.flow_name)
    flow_args = hunt_args.flow_args if hunt_args.HasField("flow_args") else None
    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,
        start_at=start_at,
        parent_hunt_id=hunt_id)

    if hunt_obj.client_limit:
      if _GetNumClients(hunt_obj.hunt_id) >= hunt_obj.client_limit:
        PauseHunt(hunt_id)

  elif hunt_obj.args.hunt_type == hunt_obj.args.HuntType.VARIABLE:
    raise NotImplementedError()
  else:
    raise UnknownHuntTypeError("Can't determine hunt type when starting "
                               "hunt %s on client %s." % (client_id, hunt_id))
1103089
def create_client(self, name):
        ''''''
        client = {'client':{
            'name': name,
        }}
        response = self.post_request('clients/', client, follow = True)
        if response:
            return Client(self, response['client'])
1205690
def _process(self, resource=None, data={}):
        
        # use object's data if no data is passed
        _data = data or self._data
        rsc_url = self.get_rsc_endpoint(resource)
        if _data:
            req = requests.post(rsc_url, data=json.dumps(_data),
                                headers=self.headers)
        else:
            req = requests.get(rsc_url, params=_data,
                               headers=self.headers)
        if req.status_code == 200:
            self._response = json.loads(req.text)
            if int(self._response['response_code']) == 00:
                return (True, self._response)
            else:
                return (False, self._response['response_text'])
        else:
            return (500, "Request Failed")
1128640
def get_client_data(self, client):
        
        data = self._request('GET', '/clients/{}'.format(client))
        return data.json()