text
stringlengths
81
112k
Constructs a copy of given stats but downsampled to given interval. Args: stats: A `ClientStats` instance. interval: A downsampling interval. Returns: A downsampled `ClientStats` instance. def Downsampled(cls, stats, interval=None): """Constructs a copy of given stats but downsampled to...
Get a User protobuf for a specific user. Args: knowledge_base: An rdf_client.KnowledgeBase object. user: Username as string. May contain domain like DOMAIN\\user. Returns: A User rdfvalue or None def GetUserInfo(knowledge_base, user): # TODO: This docstring cannot be a raw literal because there are...
Waits for a file to be updated on the client. Calls the UpdateVFSFile flow on a urn and waits for both it and the ListDirectory flow it calls to finish. Note that this is needed because any flows UpdateVFSFile calls via VFS Update methods will not become child flows of UpdateVFSFile, and therefore waiting f...
Waits for a flow to finish, polling while we wait. Args: flow_urn: The urn of the flow to wait for. token: The datastore access token. timeout: How long to wait before giving up, usually because the client has gone away. max_sleep_time: The initial and longest time to wait in between polls. ...
Runs a flow and waits for it to finish. Args: client_id: The client id of the client to run on. token: The datastore access token. timeout: How long to wait for a flow to complete, maximum. **flow_args: Pass through to flow. Returns: The urn of the flow that was run. def StartFlowAndWait(clie...
Take a string as a path on a client and interpolate with client data. Args: path: A single string/unicode to be interpolated. knowledge_base: An rdf_client.KnowledgeBase object. users: A list of string usernames, or None. path_args: A dict of additional args to use in interpolation. These take ...
A recursive generator of files. def ListDirectory(self, pathspec, depth=0): """A recursive generator of files.""" # Limit recursion depth if depth >= self.request.max_depth: return try: fd = vfs.VFSOpen(pathspec, progress_callback=self.Progress) files = fd.ListFiles(ext_attrs=self.re...
Parses request and returns a list of filter callables. Each callable will be called with the StatEntry and returns True if the entry should be suppressed. Args: request: A FindSpec that describes the search. Returns: a list of callables which return True if the file is to be suppressed. ...
Runs the Find action. def Run(self, request): """Runs the Find action.""" self.request = request filters = self.BuildChecks(request) files_checked = 0 for f in self.ListDirectory(request.pathspec): self.Progress() # Ignore this file if any of the checks fail. if not any((check(...
Search the data for a hit. def FindRegex(self, regex, data): """Search the data for a hit.""" for match in re.finditer(regex, data, flags=re.I | re.S | re.M): yield (match.start(), match.end())
Search the data for a hit. def FindLiteral(self, pattern, data): """Search the data for a hit.""" pattern = utils.Xor(pattern, self.xor_in_key) offset = 0 while 1: # We assume here that data.find does not make a copy of pattern. offset = data.find(pattern, offset) if offset < 0: ...
Search the file for the pattern. This implements the grep algorithm used to scan files. It reads the data in chunks of BUFF_SIZE (10 MB currently) and can use different functions to search for matching patterns. In every step, a buffer that is a bit bigger than the block size is used in order to re...
Stops the hunt if number of crashes exceeds the limit. def StopHuntIfCrashLimitExceeded(hunt_id): """Stops the hunt if number of crashes exceeds the limit.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) # Do nothing if the hunt is already stopped. if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntS...
Stops the hunt if average limites are exceeded. def StopHuntIfCPUOrNetworkLimitsExceeded(hunt_id): """Stops the hunt if average limites are exceeded.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) # Do nothing if the hunt is already stopped. if hunt_obj.hunt_state == rdf_hunt_objects.Hunt.HuntState.S...
Marks the hunt as complete if it's past its expiry time. def CompleteHuntIfExpirationTimeReached(hunt_obj): """Marks the hunt as complete if it's past its expiry time.""" # TODO(hanuszczak): This should not set the hunt state to `COMPLETED` but we # should have a sparate `EXPIRED` state instead and set that. i...
Creates a hunt using a given hunt object. def CreateHunt(hunt_obj): """Creates a hunt using a given hunt object.""" data_store.REL_DB.WriteHuntObject(hunt_obj) if hunt_obj.HasField("output_plugins"): output_plugins_states = flow.GetOutputPluginStates( hunt_obj.output_plugins, source="hunts/%...
Creates and starts a new hunt. def CreateAndStartHunt(flow_name, flow_args, creator, **kwargs): """Creates and starts a new hunt.""" # This interface takes a time when the hunt expires. However, the legacy hunt # starting interface took an rdfvalue.Duration object which was then added to # the current time to...
Adds foreman rules for a generic hunt. def _ScheduleGenericHunt(hunt_obj): """Adds foreman rules for a generic hunt.""" # TODO: Migrate foreman conditions to use relation expiration # durations instead of absolute timestamps. foreman_condition = foreman_rules.ForemanCondition( creation_time=rdfvalue.RDFD...
Schedules flows for a variable hunt. def _ScheduleVariableHunt(hunt_obj): """Schedules flows for a variable hunt.""" if hunt_obj.client_rate != 0: raise VariableHuntCanNotHaveClientRateError(hunt_obj.hunt_id, hunt_obj.client_rate) seen_clients = set() for fl...
Starts a hunt with a given id. def StartHunt(hunt_id): """Starts a hunt with a given id.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) num_hunt_clients = data_store.REL_DB.CountHuntFlows(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHuntCanBeStartedError(hunt_obj...
Pauses a hunt with a given id. def PauseHunt(hunt_id, reason=None): """Pauses a hunt with a given id.""" 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( hun...
Stops a hunt with a given id. def StopHunt(hunt_id, reason=None): """Stops a hunt with a given id.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state not in [ hunt_obj.HuntState.STARTED, hunt_obj.HuntState.PAUSED ]: raise OnlyStartedOrPausedHuntCanBeStoppedError(hunt_obj)...
Updates a hunt (it must be paused to be updated). def UpdateHunt(hunt_id, client_limit=None, client_rate=None, duration=None): """Updates a hunt (it must be paused to be updated).""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) if hunt_obj.hunt_state != hunt_obj.HuntState.PAUSED: raise OnlyPausedHun...
Starts a flow corresponding to a given hunt on a given client. def StartHuntFlowOnClient(client_id, hunt_id): """Starts a flow corresponding to a given hunt on a given client.""" hunt_obj = data_store.REL_DB.ReadHuntObject(hunt_id) hunt_obj = CompleteHuntIfExpirationTimeReached(hunt_obj) # There may be a litt...
Checks if the hunt has expired. def expired(self): """Checks if the hunt has expired.""" expiry_time = self.expiry_time if expiry_time is not None: return expiry_time < rdfvalue.RDFDatetime.Now() else: return False
Looks for approvals for an object and returns available valid tokens. Args: object_urn: Urn of the object we want access to. token: The token to use to lookup the ACLs. username: The user to get the approval for, if "" we get it from the token. Returns: A token for access to ...
Enforce a dual approver policy for access. def CheckAccess(self, token): """Enforce a dual approver policy for access.""" namespace, _ = self.urn.Split(2) if namespace != "ACL": raise access_control.UnauthorizedAccess( "Approval object has invalid urn %s." % self.urn, subject=sel...
Returns a list of usernames of approvers who approved this approval. def GetNonExpiredApprovers(self): """Returns a list of usernames of approvers who approved this approval.""" lifetime = rdfvalue.Duration( self.Get(self.Schema.LIFETIME) or config.CONFIG["ACL.token_expiry"]) # Check that there a...
Infers user name and subject urn from self.urn. def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, client_id, user, _ = self.urn.Split(4) return (user, rdf_client.ClientURN(client_id))
Infers user name and subject urn from self.urn. def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, hunts_str, hunt_id, user, _ = self.urn.Split(5) if hunts_str != "hunts": raise access_control.UnauthorizedAccess( "Approval object has invalid urn ...
Infers user name and subject urn from self.urn. def InferUserAndSubjectFromUrn(self): """Infers user name and subject urn from self.urn.""" _, cron_str, cron_job_name, user, _ = self.urn.Split(5) if cron_str != "cron": raise access_control.UnauthorizedAccess( "Approval object has invalid u...
Encode an approval URN. def ApprovalUrnBuilder(subject, user, approval_id): """Encode an approval URN.""" return aff4.ROOT_URN.Add("ACL").Add(subject).Add(user).Add(approval_id)
Build an approval symlink URN. def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id): """Build an approval symlink URN.""" return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add( approval_type).Add(subject_id).Add(approval_id)
Create the Approval object and notify the Approval Granter. def Request(self): """Create the Approval object and notify the Approval Granter.""" approval_id = "approval:%X" % random.UInt32() approval_urn = self.BuildApprovalUrn(approval_id) email_msg_id = email.utils.make_msgid() with aff4.FACTO...
Create the Approval object and notify the Approval Granter. def Grant(self): """Create the Approval object and notify the Approval Granter.""" approvals_root_urn = aff4.ROOT_URN.Add("ACL").Add( self.subject_urn.Path()).Add(self.delegate) children_urns = list(aff4.FACTORY.ListChildren(approvals_roo...
Builds approval object urn. def BuildApprovalUrn(self, approval_id): """Builds approval object urn.""" event = rdf_events.AuditEvent( user=self.token.username, action="CLIENT_APPROVAL_REQUEST", client=self.subject_urn, description=self.reason) events.Events.PublishEvent("Aud...
Builds list of symlinks URNs for the approval object. def BuildApprovalSymlinksUrns(self, approval_id): """Builds list of symlinks URNs for the approval object.""" return [ self.ApprovalSymlinkUrnBuilder("cron", self.subject_urn.Basename(), self.token.username, ap...
Reads given blobs. def ReadBlobs(self, blob_ids): """Reads given blobs.""" result = {} for blob_id in blob_ids: result[blob_id] = self.blobs.get(blob_id, None) return result
Checks if given blobs exit. def CheckBlobsExist(self, blob_ids): """Checks if given blobs exit.""" result = {} for blob_id in blob_ids: result[blob_id] = blob_id in self.blobs return result
This function expands paths from the args and returns related stat entries. Args: args: An `rdf_file_finder.FileFinderArgs` object. Yields: `rdf_paths.PathSpec` instances. def FileFinderOSFromClient(args): """This function expands paths from the args and returns related stat entries. Args: args:...
Expands given path patterns. Args: args: A `FileFinderArgs` instance that dictates the behaviour of the path expansion. Yields: Absolute paths (as string objects) derived from input patterns. Raises: ValueError: For unsupported path types. def GetExpandedPaths( args): """Expands given ...
Fetches a list of mountpoints. Args: only_physical: Determines whether only mountpoints for physical devices (e.g. hard disks) should be listed. If false, mountpoints for things such as memory partitions or `/dev/shm` will be returned as well. Returns: A set of mountpoints. def _GetMountpoint...
Builds a list of mountpoints to ignore during recursive searches. Args: xdev: A `XDev` value that determines policy for crossing device boundaries. Returns: A set of mountpoints to ignore. Raises: ValueError: If `xdev` value is invalid. def _GetMountpointBlacklist(xdev): """Builds a list of moun...
Writes a hunt object to the database. def WriteHuntObject(self, hunt_obj): """Writes a hunt object to the database.""" 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() clo...
Updates the hunt object by applying the update function. def UpdateHuntObject(self, hunt_id, start_time=None, **kwargs): """Updates the hunt object by applying the update function.""" hunt_obj = self.ReadHuntObject(hunt_id) delta_suffix = "_delta" for k, v in kwargs.items(): if v is None: ...
Updates hunt output plugin state for a given output plugin. def UpdateHuntOutputPluginState(self, hunt_id, state_index, update_fn): """Updates hunt output plugin state for a given output plugin.""" if hunt_id not in self.hunts: raise db.UnknownHuntError(hunt_id) try: state = rdf_flow_runner.O...
Reads a hunt object from the database. def ReadHuntObject(self, hunt_id): """Reads a hunt object from the database.""" try: return self._DeepCopy(self.hunts[hunt_id]) except KeyError: raise db.UnknownHuntError(hunt_id)
Reads all hunt objects from the database. def ReadHuntObjects(self, offset, count, with_creator=None, created_after=None, with_description_match=None): """Reads all hunt objects from the database.""" f...
Reads hunt log entries of a given hunt using given query options. def ReadHuntLogEntries(self, hunt_id, offset, count, with_substring=None): """Reads hunt log entries of a given hunt using given query options.""" all_entries = [] for flow_obj in self._GetHuntFlows(hunt_id): for entry in self.ReadFlow...
Reads hunt results of a given hunt using given query options. def ReadHuntResults(self, hunt_id, offset, count, with_tag=None, with_type=None, with_substring=None, w...
Counts hunt results of a given hunt using given query options. def CountHuntResults(self, hunt_id, with_tag=None, with_type=None): """Counts hunt results of a given hunt using given query options.""" return len( self.ReadHuntResults( hunt_id, 0, sys.maxsize, with_tag=with_tag, with_type=wit...
Reads hunt flows matching given conditins. def ReadHuntFlows(self, hunt_id, offset, count, filter_condition=db.HuntFlowsCondition.UNSET): """Reads hunt flows matching given conditins.""" if filter_condition == db.HuntFlowsCondition...
Counts hunt flows matching given conditions. def CountHuntFlows(self, hunt_id, filter_condition=db.HuntFlowsCondition.UNSET): """Counts hunt flows matching given conditions.""" return len( self.ReadHuntFlows( hunt_id, 0, sys.maxsize, filter_conditi...
Reads hunt counters. def ReadHuntCounters(self, hunt_id): """Reads hunt counters.""" num_clients = self.CountHuntFlows(hunt_id) num_successful_clients = self.CountHuntFlows( hunt_id, filter_condition=db.HuntFlowsCondition.SUCCEEDED_FLOWS_ONLY) num_failed_clients = self.CountHuntFlows( h...
Read/calculate hunt client resources stats. def ReadHuntClientResourcesStats(self, hunt_id): """Read/calculate hunt client resources stats.""" result = rdf_stats.ClientResourcesStats() for f in self._GetHuntFlows(hunt_id): cr = rdf_client_stats.ClientResources( session_id="%s/%s" % (f.clie...
Reads hunt flows states and timestamps. def ReadHuntFlowsStatesAndTimestamps(self, hunt_id): """Reads hunt flows states and timestamps.""" result = [] for f in self._GetHuntFlows(hunt_id): result.append( db.FlowStateAndTimestamps( flow_state=f.flow_state, create...
Reads hunt output plugin log entries. def ReadHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, offset, count, with_type=Non...
Counts hunt output plugin log entries. def CountHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, with_type=None): """Counts hunt output plugin log entries.""" return len( self.R...
Writes a foreman rule to the database. def WriteForemanRule(self, rule, cursor=None): """Writes a foreman rule to the database.""" query = ("INSERT INTO foreman_rules " " (hunt_id, expiration_time, rule) " "VALUES (%s, FROM_UNIXTIME(%s), %s) " "ON DUPLICATE KEY UPDATE " ...
Run the main test harness. def main(_): """Run the main test harness.""" if flags.FLAGS.version: print("GRR Admin UI {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext( contexts.ADMIN_UI_CONTEXT, "Context applied when running the admin user interface GUI.")...
Updates the last crash attribute of the client. def WriteAllCrashDetails(client_id, crash_details, flow_session_id=None, hunt_session_id=None, token=None): """Updates the last crash attribute of the client.""" # AFF...
Processes this event. def ProcessMessages(self, msgs=None, token=None): """Processes this event.""" nanny_msg = "" for crash_details in msgs: client_urn = crash_details.client_id client_id = client_urn.Basename() # The session id of the flow that crashed. session_id = crash_detail...
Actually processes the contents of the response. def ProcessResponse(self, client_id, response): """Actually processes the contents of the response.""" precondition.AssertType(client_id, Text) downsampled = rdf_client_stats.ClientStats.Downsampled(response) if data_store.AFF4Enabled(): urn = rdf...
Processes a stats response from the client. def ProcessMessage(self, message): """Processes a stats response from the client.""" self.ProcessResponse(message.source.Basename(), message.payload)
Run the foreman on the client. def ProcessMessage(self, message): """Run the foreman on the client.""" # Only accept authenticated messages if (message.auth_state != rdf_flows.GrrMessage.AuthorizationState.AUTHENTICATED): return now = time.time() # Maintain a cache of the foreman ...
Processes this event. def SendEmail(self, client_id, message): """Processes this event.""" logging.info(self.logline, client_id, message) client_info = None hostname = None # Write crash data. if data_store.RelationalDBEnabled(): client = data_store.REL_DB.ReadClientSnapshot(client_id) ...
Handle a startup event. def WriteClientStartupInfo(self, client_id, new_si): """Handle a startup event.""" drift = rdfvalue.Duration("5m") if data_store.RelationalDBEnabled(): current_si = data_store.REL_DB.ReadClientStartupInfo(client_id) # We write the updated record if the client_info has ...
Writes a list of message handler requests to the database. def WriteMessageHandlerRequests(self, requests): """Writes a list of message handler requests to the database.""" now = rdfvalue.RDFDatetime.Now() for r in requests: flow_dict = self.message_handler_requests.setdefault(r.handler_name, {}) ...
Reads all message handler requests from the database. def ReadMessageHandlerRequests(self): """Reads all message handler requests from the database.""" res = [] leases = self.message_handler_leases for requests in itervalues(self.message_handler_requests): for r in itervalues(requests): r...
Deletes a list of message handler requests from the database. def DeleteMessageHandlerRequests(self, requests): """Deletes a list of message handler requests from the database.""" for r in requests: flow_dict = self.message_handler_requests.get(r.handler_name, {}) if r.request_id in flow_dict: ...
Leases a number of message handler requests up to the indicated limit. def RegisterMessageHandler(self, handler, lease_time, limit=1000): """Leases a number of message handler requests up to the indicated limit.""" self.UnregisterMessageHandler() self.handler_stop = False self.handler_thread = threadi...
Unregisters any registered message handler. def UnregisterMessageHandler(self, timeout=None): """Unregisters any registered message handler.""" if self.handler_thread: self.handler_stop = True self.handler_thread.join(timeout) if self.handler_thread.isAlive(): raise RuntimeError("Mess...
Read and lease some outstanding message handler requests. def _LeaseMessageHandlerRequests(self, lease_time, limit): """Read and lease some outstanding message handler requests.""" leased_requests = [] now = rdfvalue.RDFDatetime.Now() zero = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0) expiration...
Reads all client action requests available for a given client_id. def ReadAllClientActionRequests(self, client_id): """Reads all client action requests available for a given client_id.""" res = [] for key, orig_request in iteritems(self.client_action_requests): request_client_id, _, _ = key if ...
Leases available client action requests for a client. def LeaseClientActionRequests(self, client_id, lease_time=None, limit=sys.maxsize): """Leases available client action requests for a client.""" leased_requests ...
Writes messages that should go to the client to the db. def WriteClientActionRequests(self, requests): """Writes messages that should go to the client to the db.""" for r in requests: req_dict = self.flow_requests.get((r.client_id, r.flow_id), {}) if r.request_id not in req_dict: request_ke...
Writes a flow object to the database. def WriteFlowObject(self, flow_obj): """Writes a flow object to the database.""" if flow_obj.client_id not in self.metadatas: raise db.UnknownClientError(flow_obj.client_id) clone = flow_obj.Copy() clone.last_update_time = rdfvalue.RDFDatetime.Now() self...
Reads a flow object from the database. def ReadFlowObject(self, client_id, flow_id): """Reads a flow object from the database.""" try: return self.flows[(client_id, flow_id)].Copy() except KeyError: raise db.UnknownFlowError(client_id, flow_id)
Returns all flow objects. def ReadAllFlowObjects( self, client_id = None, min_create_time = None, max_create_time = None, include_child_flows = True, ): """Returns all flow objects.""" res = [] for flow in itervalues(self.flows): if ((client_id is None or flow.client_i...
Reads flows that were started by a given flow from the database. def ReadChildFlowObjects(self, client_id, flow_id): """Reads flows that were started by a given flow from the database.""" res = [] for flow in itervalues(self.flows): if flow.client_id == client_id and flow.parent_flow_id == flow_id: ...
Marks a flow as being processed on this worker and returns it. def LeaseFlowForProcessing(self, client_id, flow_id, processing_time): """Marks a flow as being processed on this worker and returns it.""" rdf_flow = self.ReadFlowObject(client_id, flow_id) # TODO(user): remove the check for a legacy hunt pref...
Updates flow objects in the database. 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...
Updates flow objects in the database. def UpdateFlows(self, client_id_flow_id_pairs, pending_termination=db.Database.unchanged): """Updates flow objects in the database.""" for client_id, flow_id in client_id_flow_id_pairs: try: self.UpdateFlow( cli...
Writes a list of flow requests to the database. def WriteFlowRequests(self, requests): """Writes a list of flow requests to the database.""" flow_processing_requests = [] for request in requests: if (request.client_id, request.flow_id) not in self.flows: raise db.AtLeastOneUnknownFlowError([...
Deletes a list of flow requests from the database. def DeleteFlowRequests(self, requests): """Deletes a list of flow requests from the database.""" for request in requests: if (request.client_id, request.flow_id) not in self.flows: raise db.UnknownFlowError(request.client_id, request.flow_id) ...
Writes FlowMessages and updates corresponding requests. def WriteFlowResponses(self, responses): """Writes FlowMessages and updates corresponding requests.""" status_available = set() requests_updated = set() task_ids_by_request = {} for response in responses: flow_key = (response.client_id,...
Reads all requests and responses for a given flow from the database. def ReadAllFlowRequestsAndResponses(self, client_id, flow_id): """Reads all requests and responses for a given flow from the database.""" flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: return []...
Deletes all requests and responses for a given flow from the database. def DeleteAllFlowRequestsAndResponses(self, client_id, flow_id): """Deletes all requests and responses for a given flow from the database.""" flow_key = (client_id, flow_id) try: self.flows[flow_key] except KeyError: rai...
Reads all requests for a flow that can be processed by the worker. def ReadFlowRequestsReadyForProcessing(self, client_id, flow_id, next_needed_request=None): """Reads all requests for a flow ...
Releases a flow that the worker was processing to the database. def ReleaseProcessedFlow(self, flow_obj): """Releases a flow that the worker was processing to the database.""" key = (flow_obj.client_id, flow_obj.flow_id) next_id_to_process = flow_obj.next_request_to_process request_dict = self.flow_req...
Writes a list of flow processing requests to the database. def WriteFlowProcessingRequests(self, requests): """Writes a list of flow processing requests to the database.""" # If we don't have a handler thread running, we might be able to process the # requests inline. If we are not, we start the handler th...
Deletes a list of flow processing requests from the database. def AckFlowProcessingRequests(self, requests): """Deletes a list of flow processing requests from the database.""" for r in requests: key = (r.client_id, r.flow_id) if key in self.flow_processing_requests: del self.flow_processin...
Registers a handler to receive flow processing messages. def _RegisterFlowProcessingHandler(self, handler): """Registers a handler to receive flow processing messages.""" self.flow_handler_stop = False self.flow_handler_thread = threading.Thread( name="flow_processing_handler", target=self....
Unregisters any registered flow processing handler. def UnregisterFlowProcessingHandler(self, timeout=None): """Unregisters any registered flow processing handler.""" self.flow_handler_target = None if self.flow_handler_thread: self.flow_handler_stop = True self.flow_handler_thread.join(timeou...
Waits until flow processing thread is done processing flows. Args: timeout: If specified, is a max number of seconds to spend waiting. Raises: TimeOutWhileWaitingForFlowsToBeProcessedError: if timeout is reached. def WaitUntilNoFlowsToProcess(self, timeout=None): """Waits until flow processin...
Handler thread for the FlowProcessingRequest queue. def _HandleFlowProcessingRequestLoop(self, handler): """Handler thread for the FlowProcessingRequest queue.""" while not self.flow_handler_stop: with self.lock: todo = self._GetFlowRequestsReadyForProcessing() for request in todo: ...
Writes flow results for a given flow. def WriteFlowResults(self, results): """Writes flow results for a given flow.""" for r in results: dest = self.flow_results.setdefault((r.client_id, r.flow_id), []) to_write = r.Copy() to_write.timestamp = rdfvalue.RDFDatetime.Now() dest.append(to_w...
Reads flow results of a given flow using given query options. def ReadFlowResults(self, client_id, flow_id, offset, count, with_tag=None, with_type=None, with_substr...
Counts flow results of a given flow using given query options. def CountFlowResults(self, client_id, flow_id, with_tag=None, with_type=None): """Counts flow results of a given flow using given query options.""" return len( self.ReadFlowResults( client_id, flow_id, 0,...
Returns counts of flow results grouped by result type. def CountFlowResultsByType(self, client_id, flow_id): """Returns counts of flow results grouped by result type.""" result = collections.Counter() for hr in self.ReadFlowResults(client_id, flow_id, 0, sys.maxsize): key = compatibility.GetName(hr.p...