text
stringlengths
81
112k
Extracts interesting paths from a given path. Args: components: Source string represented as a list of components. Returns: A list of extracted paths (as strings). def Extract(self, components): """Extracts interesting paths from a given path. Args: components: Source string repres...
Processes a given path. Args: path: Path (as a string) to post-process. Returns: A list of paths with environment variables replaced with their values. If the mapping had a list of values for a particular variable, instead of just one value, then all possible replacements will be ...
The main entry point for checking access to AFF4 resources. Args: token: An instance of ACLToken security token. subjects: The list of subject URNs which the user is requesting access to. If any of these fail, the whole request is denied. requested_access: A string specifying the desir...
Writes hunt results from a given client as part of a given hunt. def WriteHuntResults(client_id, hunt_id, responses): """Writes hunt results from a given client as part of a given hunt.""" if not hunt.IsLegacyHunt(hunt_id): data_store.REL_DB.WriteFlowResults(responses) hunt.StopHuntIfCPUOrNetworkLimitsEx...
Processes error and status message for a given hunt-induced flow. def ProcessHuntFlowError(flow_obj, error_message=None, backtrace=None, status_msg=None): """Processes error and status message for a given hunt-induced flow.""" if not hunt....
Notifis hunt about a given hunt-induced flow completion. def ProcessHuntFlowDone(flow_obj, status_msg=None): """Notifis hunt about a given hunt-induced flow completion.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt_obj = hunt.StopHuntIfCPUOrNetworkLimitsExceeded( flow_obj.parent_hunt_id) ...
Processes log message from a given hunt-induced flow. def ProcessHuntFlowLog(flow_obj, log_msg): """Processes log message from a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): return hunt_urn = rdfvalue.RDFURN("hunts").Add(flow_obj.parent_hunt_id) flow_urn = hunt_urn.Add(f...
Processes client crash triggerted by a given hunt-induced flow. def ProcessHuntClientCrash(flow_obj, client_crash_info): """Processes client crash triggerted by a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt.StopHuntIfCrashLimitExceeded(flow_obj.parent_hunt_id) retur...
Validates a VFS path. def ValidateVfsPath(path): """Validates a VFS path.""" components = (path or "").lstrip("/").split("/") if not components: raise ValueError("Empty path is not a valid path: %s." % utils.SmartStr(path)) if components[0] not in ROOT_FILES_WHITELIST: raise Valu...
Generate file details based on path infos history. def _GenerateApiFileDetails(path_infos): """Generate file details based on path infos history.""" type_attrs = [] hash_attrs = [] size_attrs = [] stat_attrs = [] pathspec_attrs = [] def _Value(age, value): """Generate ApiAff4ObjectAttributeValue fr...
Retrieves the total size in bytes of an AFF4 object. Args: aff4_obj: An AFF4 stream instance to retrieve size for. Returns: An integer representing number of bytes. Raises: TypeError: If `aff4_obj` is not an instance of AFF4 stream. def _Aff4Size(aff4_obj): """Retrieves the total size in bytes o...
Reads contents of given AFF4 file. Args: aff4_obj: An AFF4 stream instance to retrieve contents for. offset: An offset to start the reading from. length: A number of bytes to read. Reads the whole file if 0. Returns: Contents of specified AFF4 stream. Raises: TypeError: If `aff4_obj` is not...
Gets timeline entries from AFF4. def _GetTimelineStatEntriesLegacy(client_id, file_path, with_history=True): """Gets timeline entries from AFF4.""" folder_urn = aff4.ROOT_URN.Add(str(client_id)).Add(file_path) child_urns = [] for _, children in aff4.FACTORY.RecursiveMultiListChildren([folder_urn]): child...
Gets timeline entries from REL_DB. def _GetTimelineStatEntriesRelDB(api_client_id, file_path, with_history=True): """Gets timeline entries from REL_DB.""" path_type, components = rdf_objects.ParseCategorizedPath(file_path) client_id = str(api_client_id) try: root_path_info = data_store.REL_DB.ReadPathInf...
Gets timeline entries from the appropriate data source (AFF4 or REL_DB). def _GetTimelineStatEntries(client_id, file_path, with_history=True): """Gets timeline entries from the appropriate data source (AFF4 or REL_DB).""" if data_store.RelationalDBEnabled(): fn = _GetTimelineStatEntriesRelDB else: fn = ...
Gets timeline items for a given client id and path. def _GetTimelineItems(client_id, file_path): """Gets timeline items for a given client id and path.""" items = [] for file_path, stat_entry, _ in _GetTimelineStatEntries( client_id, file_path, with_history=True): # It may be that for a given timest...
Initializes the current instance from an Aff4Object. Iterates over all attributes of the Aff4Object defined by a given class and adds a representation of them to the current instance. Args: aff4_obj: An Aff4Object to take the attributes from. aff4_cls: A class in the inheritance hierarchy of t...
Initializes the current instance from an Aff4Object. Iterates the inheritance hierarchy of the given Aff4Object and adds a ApiAff4ObjectType for each class found in the hierarchy. Args: aff4_obj: An Aff4Object as source for the initialization. Returns: A reference to the current instance....
Initializes the current instance from an Aff4Stream. Args: file_obj: An Aff4Stream representing a file. stat_entry: An optional stat entry object to be used. If none is provided, the one stored in the AFF4 data store is used. hash_entry: An optional hash entry object to be used. If none i...
Decode data with the given codec name. def _Decode(self, codec_name, data): """Decode data with the given codec name.""" try: return data.decode(codec_name, "replace") except LookupError: raise RuntimeError("Codec could not be found.") except AssertionError: raise RuntimeError("Codec ...
Signs multiple files at once. def SignFiles(self, filenames): """Signs multiple files at once.""" file_list = " ".join(filenames) subprocess.check_call("%s %s" % (self._signing_cmdline, file_list)) if self._verification_cmdline: subprocess.check_call("%s %s" % (self._verification_cmdline, file_li...
Sign a buffer via temp files. Our signing tool can't sign a buffer, so we work around it using temporary files. Args: in_buffer: data to sign Returns: signed data def SignBuffer(self, in_buffer): """Sign a buffer via temp files. Our signing tool can't sign a buffer, so we work a...
Sign a file using osslsigncode. Args: in_filename: file to read from out_filename: file to output to, if none we output to the same filename as the input with a .signed suffix. Returns: output filename string Raises: pexpect.ExceptionPexpect: if the expect invocation of oss...
Sign RPM with rpmsign. def AddSignatureToRPMs(self, rpm_filenames): """Sign RPM with rpmsign.""" # The horrible second argument here is necessary to get a V3 signature to # support CentOS 5 systems. See: # http://ilostmynotes.blogspot.com/2016/03/the-horror-of-signing-rpms-that-support.html args = ...
Search indexes for clients. Returns list (client, hostname, os version). def SearchClients(query_str, token=None, limit=1000): """Search indexes for clients. Returns list (client, hostname, os version).""" client_schema = aff4.AFF4Object.classes["VFSGRRClient"].SchemaCls index = client_index.CreateClientIndex(to...
Take an aff4 path and download all files in it to output_dir. Args: aff4_path: Any aff4 path as a string output_dir: A local directory to write to, will be created if not there. bufsize: Buffer size to use. preserve_path: If set all paths will be created. Note that this works for collections a...
Opens the client, getting potential approval tokens. Args: client_id: The client id that should be opened. token: Token to use to open the client Returns: tuple containing (client, token) objects or (None, None) on if no appropriate aproval tokens were found. def OpenClient(client_id=None, token=...
Show pending notifications for a user. def GetNotifications(user=None, token=None): """Show pending notifications for a user.""" if not user: user = getpass.getuser() user_obj = aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(user), token=token) return list(user_obj.Get(user_obj.Schema.PENDING_NOTI...
Iterate through requested access approving or not. def ApprovalGrant(token=None): """Iterate through requested access approving or not.""" user = getpass.getuser() notifications = GetNotifications(user=user, token=token) requests = [n for n in notifications if n.type == "GrantAccess"] for request in requests...
Find approvals issued for a specific client. def ApprovalFind(object_id, token=None): """Find approvals issued for a specific client.""" user = getpass.getuser() object_id = rdfvalue.RDFURN(object_id) try: approved_token = security.Approval.GetApprovalForObject( object_id, token=token, username=use...
Creates an approval with raw access. This method requires raw datastore access to manipulate approvals directly. This currently doesn't work for hunt or cron approvals, because they check that each approver has the admin label. Since the fake users don't exist the check fails. Args: aff4_path: The aff4...
Revokes an approval for a given token. This method requires raw datastore access to manipulate approvals directly. Args: aff4_path: The aff4_path or client id the approval should be created for. token: The token that should be revoked. def ApprovalRevokeRaw(aff4_path, token): """Revokes an approval for...
Opens the given clients in batches and returns hardware information. def _GetHWInfos(client_list, batch_size=10000, token=None): """Opens the given clients in batches and returns hardware information.""" # This function returns a dict mapping each client_id to a set of reported # hardware serial numbers reporte...
A script to find multiple machines reporting the same client_id. This script looks at the hardware serial numbers that a client reported in over time (they get collected with each regular interrogate). We have seen that sometimes those serial numbers change - for example when a disk is put in a new machine - s...
A script to remove excessive client versions. Especially when a client is heavily cloned, we sometimes write an excessive number of versions of it. Since these version all go into the same database row and are displayed as a dropdown list in the adminui, it is sometimes necessary to clear them out. This del...
A script to remove no-op client versions. This script removes versions of a client when it is identical to the previous, in the sense that no versioned attributes were changed since the previous client version. Args: clients: A list of ClientURN, if empty cleans all clients. dry_run: whether this is a...
r"""A script to export clients summaries selected by a keyword search. This script does a client search for machines matching all of keywords and writes a .csv summary of the results to filename. Multi-value fields are '\n' separated. Args: keywords: a list of keywords to search for filename: the name...
Launches the flow and worker and waits for it to finish. Args: client_id: The client common name we issue the request. flow_name: The name of the flow to launch. **kwargs: passthrough to flow. Returns: A flow session id. Note: you need raw access to run this flow as it requires running a wo...
Wake up stuck flows. A stuck flow is one which is waiting for the client to do something, but the client requests have been removed from the client queue. This can happen if the system is too loaded and the client messages have TTLed out. In this case we reschedule the client requests for this session. Args...
Start HTTPServer. def Start(self): """Start HTTPServer.""" try: self._http_server = http_server.HTTPServer(("", self.port), StatsServerHandler) except socket.error as e: if e.errno == errno.EADDRINUSE: raise base_stats_server.PortInUseErr...
Main method of this registry hook. StatsServer implementation may be overriden. If there's a "stats_server" module present in grr/local directory then grr.local.stats_server.StatsServer implementation will be used instead of a default one. def RunOnce(self): """Main method of this registry hook. ...
Parse the status file. def Parse(self, stat, file_object, knowledge_base): """Parse the status file.""" _, _ = stat, knowledge_base packages = [] sw_data = utils.ReadFileBytesAsUnicode(file_object) try: for pkg in self._deb822.Packages.iter_paragraphs(sw_data.splitlines()): if self.i...
Returns true if this is a 64 bit process. def Is64bit(self): """Returns true if this is a 64 bit process.""" if "64" not in platform.machine(): return False iswow64 = ctypes.c_bool(False) if IsWow64Process is None: return False if not IsWow64Process(self.h_process, ctypes.byref(iswow64)...
Opens the process for reading. def Open(self): """Opens the process for reading.""" self.h_process = kernel32.OpenProcess( PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, self.pid) if not self.h_process: raise process_error.ProcessError( "Failed to open process (pid %d)." % self.pi...
Reads at most num_bytes starting from offset <address>. def ReadBytes(self, address, num_bytes): """Reads at most num_bytes starting from offset <address>.""" address = int(address) buf = ctypes.create_string_buffer(num_bytes) bytesread = ctypes.c_size_t(0) res = ReadProcessMemory(self.h_process, a...
Converts migration filename to a migration number. def _MigrationFilenameToInt(fname): """Converts migration filename to a migration number.""" base, _ = os.path.splitext(fname) return int(base)
Lists filenames of migrations with numbers bigger than a given one. def ListMigrationsToProcess(migrations_root, current_migration_number ): """Lists filenames of migrations with numbers bigger than a given one.""" migrations = [] for m in os.listdir(migrati...
Processes migrations from a given folder. This function uses LOCK TABLE MySQL command on _migrations table to ensure that only one GRR process is actually performing the migration. We have to use open_conn_fn to open 2 connections to the database, since LOCK TABLE command is per-connection and it's not allo...
Dumps current database schema. def DumpCurrentSchema(cursor): """Dumps current database schema.""" cursor.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES " "WHERE table_schema = (SELECT DATABASE())") defs = [] for table, in sorted(cursor.fetchall()): cursor.execute("SHOW CREATE T...
Filters a list, getting count elements, starting at offset. def FilterList(l, offset, count=0, filter_value=None): """Filters a list, getting count elements, starting at offset.""" if offset < 0: raise ValueError("Offset needs to be greater than or equal to zero") if count < 0: raise ValueError("Count ...
Filters an aff4 collection, getting count elements, starting at offset. def FilterCollection(aff4_collection, offset, count=0, filter_value=None): """Filters an aff4 collection, getting count elements, starting at offset.""" if offset < 0: raise ValueError("Offset needs to be greater than or equal to zero") ...
Get INI parser with version.ini data. def get_config(): """Get INI parser with version.ini data.""" # TODO(hanuszczak): See comment in `setup.py` for `grr-response-proto`. ini_path = os.path.join(THIS_DIRECTORY, "version.ini") if not os.path.exists(ini_path): ini_path = os.path.join(THIS_DIRECTORY, "../../...
This sets up the template directory. def CopyFiles(self): """This sets up the template directory.""" if self.fleetspeak_enabled: # Copy files needed for dpkg-buildpackage. shutil.copytree( config_lib.Resource().Filter( "install_data/debian/dpkg_client/fleetspeak-debian"), ...
Creates a ZIP archive of the files in the input directory. Args: input_dir: the name of the input directory. output_file: the name of the output ZIP archive without extension. def MakeZip(self, input_dir, output_file): """Creates a ZIP archive of the files in the input directory. Args: ...
This sets up the template directory. def CopyFiles(self): """This sets up the template directory.""" shutil.move( os.path.join(self.package_dir, "debian"), os.path.join(self.package_dir, "rpmbuild")) if self.fleetspeak_enabled: rpm_spec_filename = "fleetspeak.grr.spec.in" else: ...
A decorator applied to protected web handlers. def SecurityCheck(func): """A decorator applied to protected web handlers.""" def Wrapper(request, *args, **kwargs): """Wrapping function.""" if WEBAUTH_MANAGER is None: raise RuntimeError("Attempt to initialize before WEBAUTH_MANAGER set.") return ...
Wrapping function. def SecurityCheck(self, func, request, *args, **kwargs): """Wrapping function.""" if self.IAP_HEADER not in request.headers: return werkzeug_wrappers.Response("Unauthorized", status=401) jwt = request.headers.get(self.IAP_HEADER) try: request.user, _ = validate_iap.Valid...
Wrapping function. def SecurityCheck(self, func, request, *args, **kwargs): """Wrapping function.""" request.user = u"" authorized = False try: auth_type, authorization = request.headers.get("Authorization", " ").split(" ", 1) if auth_t...
Check if access should be allowed for the request. def SecurityCheck(self, func, request, *args, **kwargs): """Check if access should be allowed for the request.""" try: auth_header = request.headers.get("Authorization", "") if not auth_header.startswith(self.BEARER_PREFIX): raise ValueErr...
A decorator applied to protected web handlers. def SecurityCheck(self, func, request, *args, **kwargs): """A decorator applied to protected web handlers.""" request.user = self.username request.token = access_control.ACLToken( username="Testing", reason="Just a test") return func(request, *args...
Run this once on init. def RunOnce(self): """Run this once on init.""" global WEBAUTH_MANAGER # pylint: disable=global-statement # pylint: disable=g-bad-name WEBAUTH_MANAGER = BaseWebAuthManager.GetPlugin( config.CONFIG["AdminUI.webauth_manager"])() # pylint: enable=g-bad-name loggin...
This extracts all parameters from URL paths for logging. This extracts the name of all parameters that are sent inside the URL path for the given route. For example the path /api/clients/<client_id>/last-ip would return ["client_id"]. Some URL paths contain annotated parameters - for example paths as ...
Returns a dictionary of annotated router methods. def GetAnnotatedMethods(cls): """Returns a dictionary of annotated router methods.""" result = {} # We want methods with the highest call-order to be processed last, # so that their annotations have precedence. for i_cls in reversed(inspect.getmro...
Publish the message into all listeners of the event. We send the message to all event handlers which contain this string in their EVENT static member. This allows the event to be sent to multiple interested listeners. Args: event_name: An event name. msg: The message to send to the event h...
Publishes multiple messages at once. Args: events: A dict with keys being event names and values being lists of messages. token: ACL token. Raises: ValueError: If the message is invalid. The message must be a Semantic Value (instance of RDFValue) or a full GrrMessage. def Pu...
Adds hint attributes to a child hint if they are not defined. def Overlay(child, parent): """Adds hint attributes to a child hint if they are not defined.""" for arg in child, parent: if not isinstance(arg, collections.Mapping): raise DefinitionError("Trying to merge badly defined hints. Child: %s, " ...
Expand values from various attribute types. Strings are returned as is. Dictionaries are returned with a key string, and an expanded set of values. Other iterables are expanded until they flatten out. Other items are returned in string format. Args: obj: The object to expand out. paren...
Apply string formatting templates to rdf data. Uses some heuristics to coerce rdf values into a form compatible with string formatter rules. Repeated items are condensed into a single comma separated list. Unlike regular string.Formatter operations, we use objectfilter expansion to fully acquire the ta...
Refresh an old attribute. Note that refreshing the attribute is asynchronous. It does not change anything about the current object - you need to reopen the same URN some time later to get fresh data. Attributes: CONTAINS - Refresh the content of the directory listing. Args: attribute: An at...
Returns the relevant chunk from the datastore and reads ahead. def _GetChunkForReading(self, chunk): """Returns the relevant chunk from the datastore and reads ahead.""" try: return self.chunk_cache.Get(chunk) except KeyError: pass # We don't have this chunk already cached. The most common...
Returns the relevant chunk from the datastore. def _GetChunkForWriting(self, chunk): """Returns the relevant chunk from the datastore.""" try: chunk = self.chunk_cache.Get(chunk) chunk.dirty = True return chunk except KeyError: pass try: chunk = self._ReadChunk(chunk) ...
Read as much as possible, but not more than length. def _ReadPartial(self, length): """Read as much as possible, but not more than length.""" chunk = self.offset // self.chunksize chunk_offset = self.offset % self.chunksize # If we're past the end of the file, we don't have a chunk to read from, so ...
Add another blob to this image using its hash. def AddBlob(self, blob_hash, length, chunk_number): """Add another blob to this image using its hash.""" if len(blob_hash.AsBytes()) != self._HASH_SIZE: raise ValueError("Hash '%s' doesn't have correct length (%d)." % (blob_hash, self....
Do we have this chunk in the index? def ChunksExist(self, chunk_numbers): """Do we have this chunk in the index?""" index_urns = { self.urn.Add(self.CHUNK_ID_TEMPLATE % chunk_number): chunk_number for chunk_number in chunk_numbers } res = {chunk_number: False for chunk_number in chunk_...
Flush the data to the index. def Flush(self): """Flush the data to the index.""" super(LabelSet, self).Flush() self.to_delete = self.to_delete.difference(self.to_set) with data_store.DB.GetMutationPool() as mutation_pool: mutation_pool.LabelUpdateLabels( self.urn, self.to_set, to_dele...
Writes a cronjob to the database. def WriteCronJob(self, cronjob, cursor=None): """Writes a cronjob to the database.""" query = ("INSERT INTO cron_jobs " "(job_id, job, create_time, enabled) " "VALUES (%s, %s, FROM_UNIXTIME(%s), %s) " "ON DUPLICATE KEY UPDATE " ...
Creates a cronjob object from a database result row. def _CronJobFromRow(self, row): """Creates a cronjob object from a database result row.""" (job, create_time, enabled, forced_run_requested, last_run_status, last_run_time, current_run_id, state, leased_until, leased_by) = row job = rdf_cronjobs.Cr...
Reads all cronjobs from the database. def ReadCronJobs(self, cronjob_ids=None, cursor=None): """Reads all cronjobs from the database.""" query = ("SELECT job, UNIX_TIMESTAMP(create_time), enabled, " "forced_run_requested, last_run_status, " "UNIX_TIMESTAMP(last_run_time), current_run_...
Updates run information for an existing cron job. def UpdateCronJob(self, cronjob_id, last_run_status=db.Database.unchanged, last_run_time=db.Database.unchanged, current_run_id=db.Database.unchanged, state=db.Database.u...
Leases all available cron jobs. def LeaseCronJobs(self, cronjob_ids=None, lease_time=None, cursor=None): """Leases all available cron jobs.""" now = rdfvalue.RDFDatetime.Now() now_str = mysql_utils.RDFDatetimeToTimestamp(now) expiry_str = mysql_utils.RDFDatetimeToTimestamp(now + lease_time) id_str ...
Makes leased cron jobs available for leasing again. def ReturnLeasedCronJobs(self, jobs, cursor=None): """Makes leased cron jobs available for leasing again.""" if not jobs: return unleased_jobs = [] conditions = [] args = [] for job in jobs: if not job.leased_by or not job.leased...
Stores a cron job run object in the database. def WriteCronJobRun(self, run_object, cursor=None): """Stores a cron job run object in the database.""" query = ("INSERT INTO cron_job_runs " "(job_id, run_id, write_time, run) " "VALUES (%s, %s, FROM_UNIXTIME(%s), %s) " "ON D...
Reads all cron job runs for a given job id. def ReadCronJobRuns(self, job_id, cursor=None): """Reads all cron job runs for a given job id.""" query = """ SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs WHERE job_id = %s """ cursor.execute(query, [job_id]) runs = [self._Cron...
Reads a single cron job run from the db. def ReadCronJobRun(self, job_id, run_id, cursor=None): """Reads a single cron job run from the db.""" query = ("SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs " "WHERE job_id = %s AND run_id = %s") num_runs = cursor.execute( query, [j...
Deletes cron job runs that are older then the given timestamp. def DeleteOldCronJobRuns(self, cutoff_timestamp, cursor=None): """Deletes cron job runs that are older then the given timestamp.""" query = "DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)" cursor.execute(query, ...
Inserts one or multiple rows into the given table. Args: cursor: The MySQL cursor to perform the insertion. table: The table name, where rows should be inserted. values: A list of dicts, associating column names to values. def _Insert(cursor, table, values): """Inserts one or multiple rows into the gi...
Splits a Blob into chunks of size BLOB_CHUNK_SIZE. def _BlobToChunks(blob_id, blob): """Splits a Blob into chunks of size BLOB_CHUNK_SIZE.""" # In case of empty blob (with empty range), use [0]. chunk_begins = list(range(0, len(blob), BLOB_CHUNK_SIZE)) or [0] chunks = [] for i, chunk_begin in enumerate(chun...
Groups chunks into partitions of size safe for a single INSERT. def _PartitionChunks(chunks): """Groups chunks into partitions of size safe for a single INSERT.""" partitions = [[]] partition_size = 0 for chunk in chunks: cursize = len(chunk["blob_chunk"]) if (cursize + partition_size > BLOB_CHUNK_SIZ...
Writes given blobs. def WriteBlobs(self, blob_id_data_map, cursor=None): """Writes given blobs.""" chunks = [] for blob_id, blob in iteritems(blob_id_data_map): chunks.extend(_BlobToChunks(blob_id.AsBytes(), blob)) for values in _PartitionChunks(chunks): _Insert(cursor, "blobs", values)
Reads given blobs. def ReadBlobs(self, blob_ids, cursor=None): """Reads given blobs.""" if not blob_ids: return {} query = ("SELECT blob_id, blob_chunk " "FROM blobs " "FORCE INDEX (PRIMARY) " "WHERE blob_id IN {} " "ORDER BY blob_id, chunk_index A...
Checks if given blobs exist. def CheckBlobsExist(self, blob_ids, cursor=None): """Checks if given blobs exist.""" if not blob_ids: return {} exists = {blob_id: False for blob_id in blob_ids} query = ("SELECT blob_id " "FROM blobs " "FORCE INDEX (PRIMARY) " ...
Writes blob references for a given set of hashes. def WriteHashBlobReferences(self, references_by_hash, cursor): """Writes blob references for a given set of hashes.""" values = [] for hash_id, blob_refs in iteritems(references_by_hash): refs = rdf_objects.BlobReferences(items=blob_refs).SerializeToS...
Reads blob references of a given set of hashes. def ReadHashBlobReferences(self, hashes, cursor): """Reads blob references of a given set of hashes.""" query = ("SELECT hash_id, blob_references FROM hash_blob_references WHERE " "hash_id IN {}").format(mysql_utils.Placeholders(len(hashes))) cur...
Calculates hash ids and writes contents of given data blobs. Args: blobs_data: An iterable of bytes. Returns: A list of rdf_objects.BlobID objects with each blob id corresponding to an element in the original blobs_data argument. def WriteBlobsWithUnknownHashes( self, blobs_data): ...
Returns q's client id, if q is a client task queue, otherwise None. Args: q: rdfvalue.RDFURN Returns: string or None def _GetClientIdFromQueue(q): """Returns q's client id, if q is a client task queue, otherwise None. Args: q: rdfvalue.RDFURN Returns: string or None """ split = q.Spli...
Gets a single shard for a given queue. def GetNotificationShard(self, queue): """Gets a single shard for a given queue.""" queue_name = str(queue) QueueManager.notification_shard_counters.setdefault(queue_name, 0) QueueManager.notification_shard_counters[queue_name] += 1 notification_shard_index = ...
Return a copy of the queue manager. Returns: Copy of the QueueManager object. NOTE: pending writes/deletions are not copied. On the other hand, if the original object has a frozen timestamp, a copy will have it as well. def Copy(self): """Return a copy of the queue manager. Returns: Copy ...
Freezes the timestamp used for resolve/delete database queries. Frozen timestamp is used to consistently limit the datastore resolve and delete queries by time range: from 0 to self.frozen_timestamp. This is done to avoid possible race conditions, like accidentally deleting notifications that were writ...
Unfreezes the timestamp used for resolve/delete database queries. def UnfreezeTimestamp(self): """Unfreezes the timestamp used for resolve/delete database queries.""" if not self.prev_frozen_timestamps: raise RuntimeError("Unbalanced UnfreezeTimestamp call.") self.frozen_timestamp = self.prev_frozen_...
Fetch all the requests with a status message queued for them. def FetchCompletedRequests(self, session_id, timestamp=None): """Fetch all the requests with a status message queued for them.""" if timestamp is None: timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now()) for request, stat...