text
stringlengths
81
112k
Name of the file where plugin's output should be written to. def output_file_name(self): """Name of the file where plugin's output should be written to.""" safe_path = re.sub(r":|/", "_", self.source_urn.Path().lstrip("/")) return "results_%s%s" % (safe_path, self.output_file_extension)
Fetches metadata for a given list of clients. def _GetMetadataForClients(self, client_urns): """Fetches metadata for a given list of clients.""" result = {} metadata_to_fetch = set() for urn in client_urns: try: result[urn] = self._cached_metadata[urn] except KeyError: met...
Yields responses of a given type only. _GenerateSingleTypeIteration iterates through converted_responses and only yields responses of the same type. The type is either popped from next_types or inferred from the first item of converted_responses. The type is added to a set of processed_types. Alon...
Generates converted values using given converter from given messages. Groups values in batches of BATCH_SIZE size and applies the converter to each batch. Args: converter: ExportConverter instance. grr_messages: An iterable (a generator is assumed) with GRRMessage values. Yields: Va...
Parses a categorized path string into type and list of components. def ParseCategorizedPath(path): """Parses a categorized path string into type and list of components.""" components = tuple(component for component in path.split("/") if component) if components[0:2] == ("fs", "os"): return PathInfo.PathType....
Translates a path type and a list of components to a categorized path. def ToCategorizedPath(path_type, components): """Translates a path type and a list of components to a categorized path.""" try: prefix = { PathInfo.PathType.OS: ("fs", "os"), PathInfo.PathType.TSK: ("fs", "tsk"), Pat...
Returns the client installation-name and GRR version as a string. def GetGRRVersionString(self): """Returns the client installation-name and GRR version as a string.""" client_info = self.startup_info.client_info client_name = client_info.client_description or client_info.client_name if client_info.cli...
MAC addresses from all interfaces. def GetMacAddresses(self): """MAC addresses from all interfaces.""" result = set() for interface in self.interfaces: if (interface.mac_address and interface.mac_address != b"\x00" * len(interface.mac_address)): result.add(Text(interface.mac_address...
IP addresses from all interfaces. def GetIPAddresses(self): """IP addresses from all interfaces.""" result = [] filtered_ips = ["127.0.0.1", "::1", "fe80::1"] for interface in self.interfaces: for address in interface.addresses: if address.human_readable_address not in filtered_ips: ...
Gets a client summary object. Returns: rdf_client.ClientSummary Raises: ValueError: on bad cloud type def GetSummary(self): """Gets a client summary object. Returns: rdf_client.ClientSummary Raises: ValueError: on bad cloud type """ summary = rdf_client.ClientSumma...
Constructs a path info corresponding to the parent of current path. The root path (represented by an empty list of components, corresponds to `/` on Unix-like systems) does not have a parent. Returns: Instance of `rdf_objects.PathInfo` or `None` if parent does not exist. def GetParent(self): ""...
Yields all ancestors of a path. The ancestors are returned in order from closest to the farthest one. Yields: Instances of `rdf_objects.PathInfo`. def GetAncestors(self): """Yields all ancestors of a path. The ancestors are returned in order from closest to the farthest one. Yields: ...
Merge path info records. Merges src into self. Args: src: An rdfvalues.objects.PathInfo record, will be merged into self. Raises: ValueError: If src does not represent the same path. def UpdateFrom(self, src): """Merge path info records. Merges src into self. Args: src: An ...
Converts a reference into an URN. def ToURN(self): """Converts a reference into an URN.""" if self.path_type in [PathInfo.PathType.OS, PathInfo.PathType.TSK]: return rdfvalue.RDFURN(self.client_id).Add("fs").Add( self.path_type.name.lower()).Add("/".join(self.path_components)) elif self.pa...
Converts a reference into a VFS file path. def ToPath(self): """Converts a reference into a VFS file path.""" if self.path_type == PathInfo.PathType.OS: return os.path.join("fs", "os", *self.path_components) elif self.path_type == PathInfo.PathType.TSK: return os.path.join("fs", "tsk", *self.p...
Configure the logging subsystem. def LogInit(): """Configure the logging subsystem.""" logging.debug("Initializing client logging subsystem.") # The root logger. logger = logging.getLogger() memory_handlers = [ m for m in logger.handlers if m.__class__.__name__ == "PreLoggingMemoryHandler" ] ...
Updates ApiClient records to include info from Fleetspeak. def UpdateClientsFromFleetspeak(clients): """Updates ApiClient records to include info from Fleetspeak.""" if not fleetspeak_connector.CONN or not fleetspeak_connector.CONN.outgoing: # FS not configured, or an outgoing connection is otherwise unavailab...
Removes labels with given names from a given client object. def RemoveClientLabels(self, client, labels_names): """Removes labels with given names from a given client object.""" affected_owners = set() for label in client.GetLabels(): if label.name in labels_names and label.owner != "GRR": a...
Normalize a time to be an int measured in microseconds. def _NormalizeTime(self, time): """Normalize a time to be an int measured in microseconds.""" if isinstance(time, rdfvalue.RDFDatetime): return time.AsMicrosecondsSinceEpoch() if isinstance(time, rdfvalue.Duration): return time.microsecond...
Adds value at timestamp. Values must be added in order of increasing timestamp. Args: value: An observed value. timestamp: The timestamp at which value was observed. Raises: RuntimeError: If timestamp is smaller than the previous timstamp. def Append(self, value, timestamp): """Add...
Adds multiple value<->timestamp pairs. Args: value_timestamp_pairs: Tuples of (value, timestamp). def MultiAppend(self, value_timestamp_pairs): """Adds multiple value<->timestamp pairs. Args: value_timestamp_pairs: Tuples of (value, timestamp). """ for value, timestamp in value_timest...
Filter the series to lie between start_time and stop_time. Removes all values of the series which are outside of some time range. Args: start_time: If set, timestamps before start_time will be dropped. stop_time: If set, timestamps at or past stop_time will be dropped. def FilterRange(self, start...
Normalize the series to have a fixed period over a fixed time range. Supports two modes, depending on the type of data: NORMALIZE_MODE_GAUGE: support gauge values. If multiple original data points lie within an output interval, the output value is an average of the original data point. if n...
Makes the time series increasing. Assumes that series is based on a counter which is occasionally reset, and using this assumption converts the sequence to estimate the total number of counts which occurred. NOTE: Could give inacurate numbers in either of the following cases: 1) Multiple resets oc...
Convert the sequence to the sequence of differences between points. The value of each point v[i] is replaced by v[i+1] - v[i], except for the last point which is dropped. def ToDeltas(self): """Convert the sequence to the sequence of differences between points. The value of each point v[i] is replace...
Add other to self pointwise. Requires that both self and other are of the same length, and contain identical timestamps. Typically this means that Normalize has been called on both with identical time parameters. Args: other: The sequence to add to self. Raises: RuntimeError: other do...
Return the arithmatic mean of all values. def Mean(self): """Return the arithmatic mean of all values.""" values = [v for v, _ in self.data if v is not None] if not values: return None # TODO(hanuszczak): Why do we return a floored division result instead of # the exact value? return sum...
Check the source is well constructed. def Validate(self): """Check the source is well constructed.""" self._ValidateReturnedTypes() self._ValidatePaths() self._ValidateType() self._ValidateRequiredAttributes() self._ValidateCommandArgs()
Handle dict generation specifically for Artifacts. def ToPrimitiveDict(self): """Handle dict generation specifically for Artifacts.""" artifact_dict = super(Artifact, self).ToPrimitiveDict() # ArtifactName is not JSON-serializable, so convert name to string. artifact_dict["name"] = utils.SmartStr(self...
Verifies this filter set can process the result data. def Validate(self): """Verifies this filter set can process the result data.""" # All filters can handle the input type. bad_filters = [] for f in self.filters: try: f.Validate() except DefinitionError as e: bad_filters.a...
Take the data and yield results that passed through the filters. The output of each filter is added to a result set. So long as the filter selects, but does not modify, raw data, the result count will remain accurate. Args: raw_data: An iterable series of rdf values. Returns: A list o...
Take the results and yield results that passed through the filters. The output of each filter is used as the input for successive filters. Args: raw_data: An iterable series of rdf values. Returns: A list of rdf values that matched all filters. def Parse(self, raw_data): """Take the resu...
Return an initialized filter. Only initialize filters once. Args: filter_name: The name of the filter, as a string. Returns: an initialized instance of the filter. Raises: DefinitionError if the type of filter has not been defined. def GetFilter(cls, filter_name): """Return an init...
Recurse down an attribute chain to the actual result data. def _GetVal(self, obj, key): """Recurse down an attribute chain to the actual result data.""" if "." in key: lhs, rhs = key.split(".", 1) obj2 = getattr(obj, lhs, None) if obj2 is None: return None return self._GetVal(ob...
Parse one or more objects using an objectfilter expression. def ParseObjs(self, objs, expression): """Parse one or more objects using an objectfilter expression.""" filt = self._Compile(expression) for result in filt.Filter(objs): yield result
Generate lambdas for uid and gid comparison. def _Comparator(self, operator): """Generate lambdas for uid and gid comparison.""" if operator == "=": return lambda x, y: x == y elif operator == ">=": return lambda x, y: x >= y elif operator == ">": return lambda x, y: x > y elif op...
Initialize the filter configuration from a validated configuration. The configuration is read. Active filters are added to the matcher list, which is used to process the Stat values. def _Initialize(self): """Initialize the filter configuration from a validated configuration. The configuration is rea...
Parse one or more objects by testing if it has matching stat results. Args: objs: An iterable of objects that should be checked. expression: A StatFilter expression, e.g.: "uid:>0 gid:=0 file_type:link" Yields: matching objects. def ParseObjs(self, objs, expression): """Parse on...
Validates that a parsed rule entry is valid for fschecker. Args: expression: A rule expression. Raises: DefinitionError: If the filter definition could not be validated. Returns: True if the expression validated OK. def Validate(self, expression): """Validates that a parsed rule en...
Parse one or more objects by testing if it is a known RDF class. def ParseObjs(self, objs, type_names): """Parse one or more objects by testing if it is a known RDF class.""" for obj in objs: for type_name in self._RDFTypes(type_names): if isinstance(obj, self._GetClass(type_name)): yie...
Filtered types need to be RDFValues. def Validate(self, type_names): """Filtered types need to be RDFValues.""" errs = [n for n in self._RDFTypes(type_names) if not self._GetClass(n)] if errs: raise DefinitionError("Undefined RDF Types: %s" % ",".join(errs))
Main. def main(argv): """Main.""" del argv # Unused. if flags.FLAGS.version: print("GRR worker {}".format(config_server.VERSION["packageversion"])) return config.CONFIG.AddContext(contexts.WORKER_CONTEXT, "Context applied when running a worker.") # Initialise flows and ...
A compatibility wrapper for getting object's name. In Python 2 class names are returned as `bytes` (since class names can contain only ASCII characters) whereas in Python 3 they are `unicode` (since class names can contain arbitrary unicode characters). This function makes this behaviour consistent and always...
A compatibility wrapper for setting object's name. See documentation for `GetName` for more information. Args: obj: A type or function object to set the name for. name: A name to set. def SetName(obj, name): """A compatibility wrapper for setting object's name. See documentation for `GetName` for mo...
A compatibility wrapper for listing class attributes. This method solves similar Python 2 compatibility issues for `dir` function as `GetName` does for `__name__` invocations. See documentation for `GetName` for more details. Once support for Python 2 is dropped all invocations of this function should be re...
A compatibility wrapper for the `type` built-in function. In Python 2 `type` (used as a type constructor) requires the name argument to be a `bytes` object whereas in Python 3 it is required to be an `unicode` object. Since class name is human readable text rather than arbitrary stream of bytes, the Python 3 b...
A compatibility wrapper for the `strftime` function. It is guaranteed to always take unicode string as an argument and return an unicode string as a result. Args: fmt: A format string specifying formatting of the output. stime: A time representation as returned by `gmtime` or `localtime`. Returns: ...
A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string to split. Returns: A list of unicode strings representing parts of the input string. def ShlexSplit(string): """A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string ...
A wrapper for `os.environ.get` that works the same way in both Pythons. Args: variable: A name of the variable to get the value of. default: A default value to return in case no value for the given variable is set. Returns: An environment value of the given variable. def Environ(variable, defau...
Stringifies a Python object into its JSON representation. Args: obj: A Python object to convert to JSON. sort_keys: If True, output dictionaries keys in sorted (ascending) order. encoder: An (optional) encoder class to use. Returns: A JSON representation of the given object. def Dump(obj, ...
Attempt to drop privileges if required. def DropPrivileges(): """Attempt to drop privileges if required.""" if config.CONFIG["Server.username"]: try: os.setuid(pwd.getpwnam(config.CONFIG["Server.username"]).pw_uid) except (KeyError, OSError): logging.exception("Unable to switch to user %s", ...
Run all required startup routines and initialization hooks. def Init(): """Run all required startup routines and initialization hooks.""" global INIT_RAN if INIT_RAN: return # Set up a temporary syslog handler so we have somewhere to log problems # with ConfigInit() which needs to happen before we can s...
Returns a path to version.ini. def VersionPath(): """Returns a path to version.ini.""" # Try to get a version.ini. It should be in the resources if the code # was packed with "pip sdist". It will be 2 levels up from grr_response_core # if the code was installed via "pip install -e". version_ini = ( pa...
Return a dict with GRR version information. def Version(): """Return a dict with GRR version information.""" version_ini = VersionPath() config = configparser.SafeConfigParser() config.read(version_ini) return dict( packageversion=config.get("Version", "packageversion"), major=config.getint("Ve...
Iterates over the readable regions for this process. We use mach_vm_region_recurse here to get a fine grained view of the process' memory space. The algorithm is that for some regions, the function returns is_submap=True which means that there are actually subregions that we need to examine by increasi...
Reads at most num_bytes starting from offset <address>. def ReadBytes(self, address, num_bytes): """Reads at most num_bytes starting from offset <address>.""" pdata = ctypes.c_void_p(0) data_cnt = ctypes.c_uint32(0) ret = libc.mach_vm_read(self.task, ctypes.c_ulonglong(address), ...
Converts a binary SID to its string representation. https://msdn.microsoft.com/en-us/library/windows/desktop/aa379597.aspx The byte representation of an SID is as follows: Offset Length Description 00 01 revision 01 01 sub-authority count 02 06 authority (big endian...
Parse WMI Event Consumers. def ParseMultiple(self, result_dicts): """Parse WMI Event Consumers.""" for result_dict in result_dicts: wmi_dict = result_dict.ToDict() try: creator_sid_bytes = bytes(wmi_dict["CreatorSID"]) wmi_dict["CreatorSID"] = BinarySIDtoStringSID(creator_sid_bytes...
Parse the WMI packages output. def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: packages.append( rdf_client.SoftwarePackage( name=result_dic...
Take a US format date and return epoch. def AmericanDateToEpoch(self, date_str): """Take a US format date and return epoch.""" try: epoch = time.strptime(date_str, "%m/%d/%Y") return int(calendar.timegm(epoch)) * 1000000 except ValueError: return 0
Parse the WMI packages output. def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: result = result_dict.ToDict() # InstalledOn comes back in a godawful format ...
Parse the WMI Win32_UserAccount output. def ParseMultiple(self, result_dicts): """Parse the WMI Win32_UserAccount output.""" for result_dict in result_dicts: kb_user = rdf_client.User() for wmi_key, kb_key in iteritems(self.account_mapping): try: kb_user.Set(kb_key, result_dict[wm...
Parse the WMI packages output. def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" for result_dict in result_dicts: result = result_dict.ToDict() winvolume = rdf_client_fs.WindowsVolume( drive_letter=result.get("DeviceID"), drive_type=result.get("DriveTyp...
Parse the WMI output to get Identifying Number. def ParseMultiple(self, result_dicts): """Parse the WMI output to get Identifying Number.""" for result_dict in result_dicts: # Currently we are only grabbing the Identifying Number # as the serial number (catches the unique number for VMs). # T...
Return RDFDatetime from string like 20140825162259.000000-420. Args: timestr: WMI time string Returns: rdfvalue.RDFDatetime We have some timezone manipulation work to do here because the UTC offset is in minutes rather than +-HHMM def WMITimeStrToRDFDatetime(self, timestr): """Return...
Parse the WMI packages output. def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" for result_dict in result_dicts: args = {"ifname": result_dict["Description"]} args["mac_address"] = binascii.unhexlify( result_dict["MACAddress"].replace(":", "")) self._Conv...
Extracts the client id from a session id. def _ClientIDFromSessionID(session_id): """Extracts the client id from a session id.""" parts = session_id.Split(4) client_id = parts[0] if re.match(r"C\.[0-9a-f]{16}", client_id): return client_id # Maybe it's a legacy hunt id (aff4:/hunts/<hunt_id>/<client_id...
Helper function to convert legacy client replies to flow responses. def FlowResponseForLegacyResponse(legacy_msg): """Helper function to convert legacy client replies to flow responses.""" if legacy_msg.type == legacy_msg.Type.MESSAGE: response = FlowResponse( client_id=_ClientIDFromSessionID(legacy_ms...
Iterator returning dict for each entry in history. def Parse(self): """Iterator returning dict for each entry in history.""" for data in self.Query(self.EVENTS_QUERY): (timestamp, agent_bundle_identifier, agent_name, url, sender, sender_address, type_number, title, referrer, referrer_alias) = data...
Retrieves information for an IP4 address. def RetrieveIP4Info(self, ip): """Retrieves information for an IP4 address.""" if ip.is_private: return (IPInfo.INTERNAL, "Internal IP address.") try: # It's an external IP, let's try to do a reverse lookup. res = socket.getnameinfo((str(ip), 0), ...
Gets a connection. Args: blocking: Whether to block when max_size connections are already in use. If false, may return None. Returns: A connection to the database. Raises: PoolAlreadyClosedError: if close() method was already called on this pool. def get(self, blocking=Tr...
Verify we have at least one template that matches maj.minor version. def CheckTemplates(self, base_dir, version): """Verify we have at least one template that matches maj.minor version.""" major_minor = ".".join(version.split(".")[0:2]) templates = glob.glob( os.path.join(base_dir, "templates/*%s*....
Does the actual termination. def _TerminateFlow(rdf_flow, reason=None, flow_state=rdf_flow_objects.Flow.FlowState.ERROR): """Does the actual termination.""" flow_cls = registry.FlowRegistry.FlowClassByName(rdf_flow.flow_class_name) flow_obj = flow_cls(rdf_flow) if not flo...
Terminates a flow and all of its children. Args: client_id: Client ID of a flow to terminate. flow_id: Flow ID of a flow to terminate. reason: String with a termination reason. flow_state: Flow state to be assigned to a flow after termination. Defaults to FlowState.ERROR. def TerminateFlow(cli...
Decorator that creates AFF4 and RELDB flows from a given mixin. def DualDBFlow(cls): """Decorator that creates AFF4 and RELDB flows from a given mixin.""" if issubclass(cls, flow.GRRFlow): raise ValueError("Mixin class shouldn't inherit from GRRFlow.") if cls.__name__[-5:] != "Mixin": raise ValueError(...
This method is used to schedule a new state on a different worker. This is basically the same as CallFlow() except we are calling ourselves. The state will be invoked at a later time. Args: next_state: The state in this flow to be invoked. start_time: Start the flow at this time. This delays...
Calls the client asynchronously. This sends a message to the client to invoke an Action. The run action may send back many responses that will be queued by the framework until a status message is sent by the client. The status message will cause the entire transaction to be committed to the specified s...
Creates a new flow and send its responses to a state. This creates a new flow. The flow may send back many responses which will be queued by the framework until the flow terminates. The final status message will cause the entire transaction to be committed to the specified state. Args: flow_nam...
Allows this flow to send a message to its parent flow. If this flow does not have a parent, the message is ignored. Args: response: An RDFValue() instance to be sent to the parent. tag: If specified, tag the result with this tag. Raises: ValueError: If responses is not of the correct ty...
Method to tally resources. def SaveResourceUsage(self, status): """Method to tally resources.""" user_cpu = status.cpu_time_used.user_cpu_time system_cpu = status.cpu_time_used.system_cpu_time self.rdf_flow.cpu_time_used.user_cpu_time += user_cpu self.rdf_flow.cpu_time_used.system_cpu_time += syste...
Terminates this flow with an error. def Error(self, error_message=None, backtrace=None, status=None): """Terminates this flow with an error.""" stats_collector_instance.Get().IncrementCounter( "flow_errors", fields=[compatibility.GetName(self.__class__)]) client_id = self.rdf_flow.client_id fl...
Marks this flow as done. def MarkDone(self, status=None): """Marks this flow as done.""" stats_collector_instance.Get().IncrementCounter( "flow_completions", fields=[compatibility.GetName(self.__class__)]) # Notify our parent flow or hunt that we are done (if there's a parent flow # or hunt). ...
Logs the message using the flow's standard logging. Args: format_str: Format string *args: arguments to the format string def Log(self, format_str, *args): """Logs the message using the flow's standard logging. Args: format_str: Format string *args: arguments to the format string ...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of FlowMessages responding to the request. def RunStateMethod(self, method_name, request=None, responses=None): """Completes the req...
Processes all requests that are due to run. Returns: The number of processed requests. def ProcessAllReadyRequests(self): """Processes all requests that are due to run. Returns: The number of processed requests. """ request_dict = data_store.REL_DB.ReadFlowRequestsReadyForProcessing( ...
Processes replies with output plugins. def _ProcessRepliesWithFlowOutputPlugins(self, replies): """Processes replies with output plugins.""" created_output_plugins = [] for index, output_plugin_state in enumerate( self.rdf_flow.output_plugins_states): plugin_descriptor = output_plugin_state.p...
Converts an AFF4 URN for a signed binary to a SignedBinaryID. def _SignedBinaryIDFromURN(binary_urn ): """Converts an AFF4 URN for a signed binary to a SignedBinaryID.""" if binary_urn.RelativeName(GetAFF4PythonHackRoot()): return rdf_objects.SignedBinaryID( binary_type=rdf_ob...
Converts a SignedBinaryID to the equivalent AFF4 URN. def _SignedBinaryURNFromID(binary_id ): """Converts a SignedBinaryID to the equivalent AFF4 URN.""" binary_type = binary_id.binary_type if binary_type == rdf_objects.SignedBinaryID.BinaryType.PYTHON_HACK: return GetAFF4PythonHack...
Signs a binary and saves it to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: URN that should serve as a unique identifier for the binary. binary_content: Contents of the binary, as raw bytes. private_key: Key that should be ...
Saves signed blobs to the datastore. If a signed binary with the given URN already exists, its contents will get overwritten. Args: binary_urn: RDFURN that should serve as a unique identifier for the binary. blobs: An Iterable of signed blobs to write to the datastore. token: ACL token to use with t...
Deletes the binary with the given urn from the datastore. Args: binary_urn: RDFURN that serves as a unique identifier for the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: SignedBinaryNotFoundError: If the signed binary does not exist. def DeleteSignedBinary(bina...
Returns URNs for all signed binaries in the datastore. Args: token: ACL token to use with the legacy (non-relational) datastore. def FetchURNsForAllSignedBinaries(token ): """Returns URNs for all signed binaries in the datastore. Args: token: ACL token to use with the l...
Retrieves blobs for the given binary from the datastore. Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Returns: A tuple containing an iterator for all the binary's blobs and an RDFDatetime representing when the bin...
Returns the size of the given binary (in bytes). Args: binary_urn: RDFURN that uniquely identifies the binary. token: ACL token to use with the legacy (non-relational) datastore. Raises: SignedBinaryNotFoundError: If no signed binary with the given URN exists. def FetchSizeOfSignedBinary(binary_urn, ...
Yields the contents of the given binary in chunks of the given size. Args: blob_iterator: An Iterator over all the binary's blobs. chunk_size: Size, in bytes, of the chunks to yield. def StreamSignedBinaryContents(blob_iterator, chunk_size = 1024 ...
Creates or overwrites blobs. def WriteBlobs(self, blob_id_data_map): """Creates or overwrites blobs.""" urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map} mutation_pool = data_store.DB.GetMutationPool() existing = aff4.FACTORY.MultiOpen( urns, aff4_type=aff4.AFF4MemoryS...
Check if blobs for the given digests already exist. def CheckBlobsExist(self, blob_ids): """Check if blobs for the given digests already exist.""" res = {blob_id: False for blob_id in blob_ids} urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_ids} existing = aff4.FACTORY.MultiOpen( ...
Returns named placeholders from all elements of the given iterable. Use this function for VALUES of MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> NamedPlaceholders({"password": "foo", "name": "bar"}) u'(%(name)s...
Returns a string of column names for MySQL INSERTs. To account for Iterables with undefined order (dicts before Python 3.6), this function sorts column names. Examples: >>> Columns({"password": "foo", "name": "bar"}) u'(`name`, `password`)' Args: iterable: The iterable of strings to be used as co...
Converts MySQL `TIMESTAMP(6)` columns to datetime objects. def TimestampToRDFDatetime(timestamp): """Converts MySQL `TIMESTAMP(6)` columns to datetime objects.""" # TODO(hanuszczak): `timestamp` should be of MySQL type `Decimal`. However, # it is unclear where this type is actually defined and how to import it i...