text stringlengths 81 112k |
|---|
Converts a list of path components to a canonical path representation.
Args:
components: A sequence of path components.
Returns:
A canonical MySQL path representation.
def ComponentsToPath(components):
"""Converts a list of path components to a canonical path representation.
Args:
components: A ... |
Converts a canonical path representation to a list of components.
Args:
path: A canonical MySQL path representation.
Returns:
A sequence of path components.
def PathToComponents(path):
"""Converts a canonical path representation to a list of components.
Args:
path: A canonical MySQL path represe... |
Log any invalid run states found.
def _LogInvalidRunLevels(states, valid):
"""Log any invalid run states found."""
invalid = set()
for state in states:
if state not in valid:
invalid.add(state)
if invalid:
logging.warning("Invalid init runlevel(s) encountered: %s",
", ".join(i... |
Accepts a string and returns a list of strings of numeric LSB runlevels.
def GetRunlevelsLSB(states):
"""Accepts a string and returns a list of strings of numeric LSB runlevels."""
if not states:
return set()
valid = set(["0", "1", "2", "3", "4", "5", "6"])
_LogInvalidRunLevels(states, valid)
return vali... |
Accepts a string and returns a list of strings of numeric LSB runlevels.
def GetRunlevelsNonLSB(states):
"""Accepts a string and returns a list of strings of numeric LSB runlevels."""
if not states:
return set()
convert_table = {
"0": "0",
"1": "1",
"2": "2",
"3": "3",
"4": "4",... |
Expand insserv variables.
def _InsservExpander(self, facilities, val):
"""Expand insserv variables."""
expanded = []
if val.startswith("$"):
vals = facilities.get(val, [])
for v in vals:
expanded.extend(self._InsservExpander(facilities, v))
elif val.startswith("+"):
expanded.a... |
/etc/insserv.conf* entries define system facilities.
Full format details are in man 8 insserv, but the basic structure is:
$variable facility1 facility2
$second_variable facility3 $variable
Any init script that specifies Required-Start: $second_variable needs to be
expanded to facil... |
Extract entries from the xinetd config files.
def _ProcessEntries(self, fd):
"""Extract entries from the xinetd config files."""
p = config_file.KeyValueParser(kv_sep="{", term="}", sep=None)
data = utils.ReadFileBytesAsUnicode(fd)
entries = p.ParseEntries(data)
for entry in entries:
for sect... |
Interpolate configurations with defaults to generate actual configs.
def _GenConfig(self, cfg):
"""Interpolate configurations with defaults to generate actual configs."""
# Some setting names may have a + or - suffix. These indicate that the
# settings modify the default values.
merged = self.default.c... |
Identify the init scripts and the start/stop scripts at each runlevel.
Evaluate all the stat entries collected from the system.
If the path name matches a runlevel spec, and if the filename matches a
sysv init symlink process the link as a service.
Args:
stats: An iterator of StatEntry rdfs.
... |
Checks a given client against labels/owners whitelists.
def CheckClientLabels(client_id,
labels_whitelist=None,
labels_owners_whitelist=None,
token=None):
"""Checks a given client against labels/owners whitelists."""
labels_whitelist = labels_white... |
Returns whether error is likely to be retryable.
def _IsRetryable(error):
"""Returns whether error is likely to be retryable."""
if not isinstance(error, MySQLdb.OperationalError):
return False
if not error.args:
return False
code = error.args[0]
return code in _RETRYABLE_ERRORS |
Checks MySQL collation and warns if misconfigured.
def _CheckCollation(cursor):
"""Checks MySQL collation and warns if misconfigured."""
# Do not fail for wrong collation, because changing it is harder than changing
# the character set. Some providers only allow changing character set and then
# use the defau... |
Enforces a sane UTF-8 encoding for the database connection.
def _CheckConnectionEncoding(cursor):
"""Enforces a sane UTF-8 encoding for the database connection."""
cur_character_set = _ReadVariable("character_set_connection", cursor)
if cur_character_set != CHARACTER_SET:
raise EncodingEnforcementError(
... |
Enforces a sane UTF-8 encoding for the database.
def _CheckDatabaseEncoding(cursor):
"""Enforces a sane UTF-8 encoding for the database."""
cur_character_set = _ReadVariable("character_set_database", cursor)
if cur_character_set != CHARACTER_SET:
raise EncodingEnforcementError(
"Require MySQL charact... |
Sets max_allowed_packet globally for new connections (not current!).
def _SetPacketSizeForFollowingConnections(cursor):
"""Sets max_allowed_packet globally for new connections (not current!)."""
cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor))
if cur_packet_size < MAX_PACKET_SIZE:
logging.... |
Checks that MySQL packet size is big enough for expected query size.
def _CheckPacketSize(cursor):
"""Checks that MySQL packet size is big enough for expected query size."""
cur_packet_size = int(_ReadVariable("max_allowed_packet", cursor))
if cur_packet_size < MAX_PACKET_SIZE:
raise Error(
"MySQL ma... |
Warns if MySQL log file size is not large enough for blob insertions.
def _CheckLogFileSize(cursor):
"""Warns if MySQL log file size is not large enough for blob insertions."""
# Do not fail, because users might not be able to change this for their
# database. Instead, warn the user about the impacts.
innodb... |
Checks if we are running against MariaDB.
def _IsMariaDB(cursor):
"""Checks if we are running against MariaDB."""
for variable in ["version", "version_comment"]:
cursor.execute("SHOW VARIABLES LIKE %s;", (variable,))
version = cursor.fetchone()
if version and "MariaDB" in version[1]:
return True
... |
Connect to the given MySQL host and create a utf8mb4_unicode_ci database.
Args:
host: The hostname to connect to.
port: The port to connect to.
user: The username to connect as.
password: The password to connect with.
database: The database name to create.
client_key_path: The path of the cli... |
Builds connection arguments for MySQLdb.Connect function.
def _GetConnectionArgs(host=None,
port=None,
user=None,
password=None,
database=None,
client_key_path=None,
client_cert_pat... |
Connect to MySQL and check if server fulfills requirements.
def _Connect(host=None,
port=None,
user=None,
password=None,
database=None,
client_key_path=None,
client_cert_path=None,
ca_cert_path=None):
"""Connect to MySQL and c... |
Runs function within a transaction.
Allocates a connection, begins a transaction on it and passes the connection
to function.
If function finishes without raising, the transaction is committed.
If function raises, the transaction will be rolled back, if a retryable
database error is raised, the o... |
See db.Database.
def WriteClientGraphSeries(self, graph_series,
client_label,
timestamp):
"""See db.Database."""
series_key = (client_label, graph_series.report_type, timestamp.Copy())
self.client_graph_series[series_key] = graph_series.Copy() |
See db.Database.
def ReadAllClientGraphSeries(
self,
client_label,
report_type,
time_range = None,
):
"""See db.Database."""
series_with_timestamps = {}
for series_key, series in iteritems(self.client_graph_series):
series_label, series_type, timestamp = series_key
if ... |
See db.Database.
def ReadMostRecentClientGraphSeries(self, client_label,
report_type
):
"""See db.Database."""
series_with_timestamps = self.ReadAllClientGraphSeries(
client_label, report_type)
if not series_with_timestamps:... |
Set the value into the data store.
def Set(self,
subject,
attribute,
value,
timestamp=None,
replace=True,
sync=True):
"""Set the value into the data store."""
subject = utils.SmartUnicode(subject)
_ = sync
attribute = utils.SmartUnicode(attri... |
Resolve all attributes for a subject starting with a prefix.
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None,
limit=None):
"""Resolve all attributes for a subject starting with a prefix."""
subject = utils.SmartUnicode(subject)
if timestamp in [None, self.NEWEST_TIMES... |
Processes a single fleetspeak message.
def Process(self, fs_msg, context):
"""Processes a single fleetspeak message."""
try:
if fs_msg.message_type == "GrrMessage":
grr_message = rdf_flows.GrrMessage.FromSerializedString(
fs_msg.data.value)
self._ProcessGRRMessages(fs_msg.sour... |
Handles messages from GRR clients received via Fleetspeak.
This method updates the last-ping timestamp of the client before beginning
processing.
Args:
fs_client_id: The Fleetspeak client-id for the client.
grr_messages: An Iterable of GrrMessages.
def _ProcessGRRMessages(self, fs_client_id, ... |
Perform all checks on a host using acquired artifacts.
Checks are selected based on the artifacts available and the host attributes
(e.g. os_name/cpe/labels) provided as either parameters, or in the
knowledgebase artifact.
A KnowledgeBase artifact should be provided that contains, at a minimum:
- OS
- Hos... |
Load a single check from a file.
def LoadCheckFromFile(file_path, check_id, overwrite_if_exists=True):
"""Load a single check from a file."""
configs = LoadConfigsFromFile(file_path)
conf = configs.get(check_id)
check = Check(**conf)
check.Validate()
CheckRegistry.RegisterCheck(
check,
source="... |
Load the checks defined in the specified files.
def LoadChecksFromFiles(file_paths, overwrite_if_exists=True):
"""Load the checks defined in the specified files."""
loaded = []
for file_path in file_paths:
configs = LoadConfigsFromFile(file_path)
for conf in itervalues(configs):
check = Check(**con... |
Load checks from all yaml files in the specified directories.
def LoadChecksFromDirs(dir_paths, overwrite_if_exists=True):
"""Load checks from all yaml files in the specified directories."""
loaded = []
for dir_path in dir_paths:
cfg_files = glob.glob(os.path.join(dir_path, "*.yaml"))
loaded.extend(LoadC... |
Processes data according to formatting rules.
def Render(self, rdf_data):
"""Processes data according to formatting rules."""
report_data = rdf_data[:self.max_results]
results = [self.hinter.Render(rdf) for rdf in report_data]
extra = len(rdf_data) - len(report_data)
if extra > 0:
results.app... |
Process rdf data through the filter.
Filters sift data according to filter rules. Data that passes the filter
rule is kept, other data is dropped.
If no filter method is provided, the data is returned as a list.
Otherwise, a items that meet filter conditions are returned in a list.
Args:
rd... |
The filter exists, and has valid filter and hint expressions.
def Validate(self):
"""The filter exists, and has valid filter and hint expressions."""
if self.type not in filters.Filter.classes:
raise DefinitionError("Undefined filter type %s" % self.type)
self._filter.Validate(self.expression)
Va... |
Process rdf data through filters. Test if results match expectations.
Processing of rdf data is staged by a filter handler, which manages the
processing of host data. The output of the filters are compared against
expected results.
Args:
rdf_data: An list containing 0 or more rdf values.
Re... |
Check the test set is well constructed.
def Validate(self):
"""Check the test set is well constructed."""
Validate(self.target, "Probe has invalid target")
self.baseliner.Validate()
self.handler.Validate()
self.hint.Validate() |
Runs probes that evaluate whether collected data has an issue.
Args:
conditions: The trigger conditions.
host_data: A map of artifacts and rdf data.
Returns:
Anomalies if an issue exists.
def Parse(self, conditions, host_data):
"""Runs probes that evaluate whether collected data has an ... |
Check the Method is well constructed.
def Validate(self):
"""Check the Method is well constructed."""
ValidateMultiple(self.probe, "Method has invalid probes")
Validate(self.target, "Method has invalid target")
Validate(self.hint, "Method has invalid hint") |
Merge anomalies from another CheckResult.
def ExtendAnomalies(self, other):
"""Merge anomalies from another CheckResult."""
for o in other:
if o is not None:
self.anomaly.Extend(list(o.anomaly)) |
Determines if the check uses the specified artifact.
Args:
artifacts: Either a single artifact name, or a list of artifact names
Returns:
True if the check uses a specific artifact.
def UsesArtifact(self, artifacts):
"""Determines if the check uses the specified artifact.
Args:
art... |
Runs methods that evaluate whether collected host_data has an issue.
Args:
conditions: A list of conditions to determine which Methods to trigger.
host_data: A map of artifacts and rdf data.
Returns:
A CheckResult populated with Anomalies if an issue exists.
def Parse(self, conditions, host... |
Check the method is well constructed.
def Validate(self):
"""Check the method is well constructed."""
if not self.check_id:
raise DefinitionError("Check has missing check_id value")
cls_name = self.check_id
if not self.method:
raise DefinitionError("Check %s has no methods" % cls_name)
... |
Run host_data through detectors and return them if a detector triggers.
Args:
baseline: The base set of rdf values used to evaluate whether an issue
exists.
host_data: The rdf values passed back by the filters.
Returns:
A CheckResult message containing anomalies if any detectors iden... |
Collect anomalous findings into a CheckResult.
Comparisons with anomalous conditions collect anomalies into a single
CheckResult message. The contents of the result varies depending on whether
the method making the comparison is a Check, Method or Probe.
- Probes evaluate raw host data and generate Ano... |
Anomaly if baseline vs result counts differ, an empty list otherwise.
def GotAll(self, baseline, results):
"""Anomaly if baseline vs result counts differ, an empty list otherwise."""
num_base = len(baseline)
num_rslt = len(results)
if num_rslt > num_base:
raise ProcessingError("Filter generated m... |
Adds a check to the registry, refresh the trigger to check map.
def RegisterCheck(cls, check, source="unknown", overwrite_if_exists=False):
"""Adds a check to the registry, refresh the trigger to check map."""
if not overwrite_if_exists and check.check_id in cls.checks:
raise DefinitionError(
"... |
Encapsulates an argument in a list, if it's not already iterable.
def _AsList(arg):
"""Encapsulates an argument in a list, if it's not already iterable."""
if (isinstance(arg, string_types) or
not isinstance(arg, collections.Iterable)):
return [arg]
else:
return list(arg) |
Provide a series of condition tuples.
A Target can specify multiple artifact, os_name, cpe or label entries. These
are expanded to all distinct tuples. When an entry is undefined or None, it
is treated as a single definition of None, meaning that the condition does
not apply.
Args:
artifact:... |
Takes targeting info, identifies relevant checks.
FindChecks will return results when a host has the conditions necessary for
a check to occur. Conditions with partial results are not returned. For
example, FindChecks will not return checks that if a check targets
os_name=["Linux"], labels=["foo"] and ... |
Takes targeting info, identifies artifacts to fetch.
Args:
os_name: 0+ OS names.
cpe: 0+ CPE identifiers.
labels: 0+ GRR labels.
restrict_checks: A list of check ids whose artifacts should be fetched.
Returns:
the artifacts that should be collected.
def SelectArtifacts(cls,
... |
Runs checks over all host data.
Args:
host_data: The data collected from a host, mapped to artifact name.
os_name: 0+ OS names.
cpe: 0+ CPE identifiers.
labels: 0+ GRR labels.
exclude_checks: A list of check ids not to run. A check id in this list
will not get ru... |
Returns a pseudo-random 32-bit unsigned integer.
def UInt32():
"""Returns a pseudo-random 32-bit unsigned integer."""
with _mutex:
try:
return _random_buffer.pop()
except IndexError:
data = os.urandom(struct.calcsize("=L") * _random_buffer_size)
_random_buffer.extend(
struct.unp... |
Set up some vars for the directories we use.
def SetupVars(self):
"""Set up some vars for the directories we use."""
# Python paths chosen to match appveyor:
# http://www.appveyor.com/docs/installed-software#python
self.python_dir_64 = args.python64_dir
self.python_dir_32 = args.python32_dir
... |
Clean the build environment.
def Clean(self):
"""Clean the build environment."""
# os.unlink doesn't work effectively, use the shell to delete.
if os.path.exists(args.build_dir):
subprocess.call("rd /s /q %s" % args.build_dir, shell=True)
if os.path.exists(args.output_dir):
subprocess.call(... |
Installs GRR.
def InstallGRR(self, path):
"""Installs GRR."""
cmd64 = [self.pip64, "install"]
cmd32 = [self.pip32, "install"]
if args.wheel_dir:
cmd64 += ["--no-index", r"--find-links=file:///%s" % args.wheel_dir]
cmd32 += ["--no-index", r"--find-links=file:///%s" % args.wheel_dir]
c... |
Builds the client templates.
We dont need to run special compilers so just enter the virtualenv and
build. Python will already find its own MSVC for python compilers.
def BuildTemplates(self):
"""Builds the client templates.
We dont need to run special compilers so just enter the virtualenv and
b... |
Repack templates with a dummy config.
def _RepackTemplates(self):
"""Repack templates with a dummy config."""
dummy_config = os.path.join(
args.grr_src, "grr/test/grr_response_test/test_data/dummyconfig.yaml")
if args.build_32:
template_i386 = glob.glob(os.path.join(args.output_dir,
... |
Cleanup from any previous installer enough for _CheckInstallSuccess.
def _CleanupInstall(self):
"""Cleanup from any previous installer enough for _CheckInstallSuccess."""
if os.path.exists(self.install_path):
shutil.rmtree(self.install_path)
if os.path.exists(self.install_path):
raise Runti... |
Checks if the installer installed correctly.
def _CheckInstallSuccess(self):
"""Checks if the installer installed correctly."""
if not os.path.exists(self.install_path):
raise RuntimeError("Install failed, no files at: %s" % self.install_path)
try:
output = subprocess.check_output(["sc", "quer... |
Install the installer built by RepackTemplates.
def _InstallInstallers(self):
"""Install the installer built by RepackTemplates."""
# 32 bit binary will refuse to install on a 64bit system so we only install
# the 64 bit version
installer_amd64 = glob.glob(
os.path.join(args.output_dir, "dbg_*_... |
Build templates.
def Build(self):
"""Build templates."""
self.SetupVars()
self.Clean()
if not os.path.exists(args.grr_src):
self.GitCheckoutGRR()
proto_sdist = self.MakeProtoSdist()
core_sdist = self.MakeCoreSdist()
client_sdist = self.MakeClientSdist()
client_builder_sdist = sel... |
Ensures that given value has certain type.
Args:
value: A value to assert the type for.
expected_type: An expected type for the given value.
Raises:
TypeError: If given value does not have the expected type.
def AssertType(value, expected_type):
"""Ensures that given value has certain type.
Args... |
Ensures that given iterable container has certain type.
Args:
iterable: An iterable container to assert the type for.
expected_item_type: An expected type of the container items.
Raises:
TypeError: If given container does is not an iterable or its items do not
have the expected type.
d... |
Ensures that given dictionary is actually a dictionary of specified type.
Args:
dct: A dictionary to assert the type for.
expected_key_type: An expected type for dictionary keys.
expected_value_type: An expected type for dictionary values.
Raises:
TypeError: If given dictionary is not really a dic... |
Run the single hook specified by resolving all its prerequisites.
def _RunSingleHook(self, hook_cls, executed_set, required=None):
"""Run the single hook specified by resolving all its prerequisites."""
# If we already ran do nothing.
if hook_cls in executed_set:
return
# Ensure all the pre exec... |
Initialize API hunt object from a database hunt object.
Args:
hunt_obj: rdf_hunt_objects.Hunt to read the data from.
hunt_counters: Optional db.HuntCounters object with counters information.
with_full_summary: if True, hunt_runner_args, completion counts and a few
other fields will be fil... |
Init from GrrMessage rdfvalue.
def InitFromGrrMessage(self, message):
"""Init from GrrMessage rdfvalue."""
if message.source:
self.client_id = message.source.Basename()
self.payload_type = compatibility.GetName(message.payload.__class__)
self.payload = message.payload
self.timestamp = messag... |
Init from rdf_flow_objects.FlowResult.
def InitFromFlowResult(self, flow_result):
"""Init from rdf_flow_objects.FlowResult."""
self.payload_type = compatibility.GetName(flow_result.payload.__class__)
self.payload = flow_result.payload
self.client_id = flow_result.client_id
self.timestamp = flow_re... |
Init from FlowLogEntry rdfvalue.
def InitFromFlowLogEntry(self, fle):
"""Init from FlowLogEntry rdfvalue."""
# TODO(user): putting this stub value for backwards compatibility.
# Remove as soon as AFF4 is gone.
self.flow_name = "GenericHunt"
self.client_id = fle.client_id
self.flow_id = fle.fl... |
Initialize from rdf_flow_objects.Flow corresponding to a failed flow.
def InitFromFlowObject(self, fo):
"""Initialize from rdf_flow_objects.Flow corresponding to a failed flow."""
self.client_id = fo.client_id
if fo.HasField("backtrace"):
self.backtrace = fo.backtrace
self.log_message = fo.error... |
Check that this approval applies to the given token.
Args:
start_stats: A list of lists, each containing two values (a timestamp and
the number of clients started at this time).
complete_stats: A list of lists, each containing two values (a timestamp
and the number of clients completed ... |
Resamples the stats to have a specific number of data points.
def _Resample(self, stats, target_size):
"""Resamples the stats to have a specific number of data points."""
t_first = stats[0][0]
t_last = stats[-1][0]
interval = (t_last - t_first) / target_size
result = []
current_t = t_first
... |
Retrieves the stats for a hunt.
def _HandleLegacy(self, args, token=None):
"""Retrieves the stats for a hunt."""
hunt_obj = aff4.FACTORY.Open(
args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token)
stats = hunt_obj.GetRunner().context.usage_stats
return ApiGetHuntStatsResult(sta... |
Retrieves the clients for a hunt.
def _HandleLegacy(self, args, token=None):
"""Retrieves the clients for a hunt."""
hunt_urn = args.hunt_id.ToURN()
hunt_obj = aff4.FACTORY.Open(
hunt_urn, aff4_type=implementation.GRRHunt, token=token)
clients_by_status = hunt_obj.GetClientsByStatus()
hunt... |
Retrieves the context for a hunt.
def _HandleLegacy(self, args, token=None):
"""Retrieves the context for a hunt."""
hunt_obj = aff4.FACTORY.Open(
args.hunt_id.ToURN(), aff4_type=implementation.GRRHunt, token=token)
if isinstance(hunt_obj.context, rdf_hunts.HuntContext): # New style hunt.
... |
Creates a new hunt.
def _HandleLegacy(self, args, token=None):
"""Creates a new hunt."""
# We only create generic hunts with /hunts/create requests.
generic_hunt_args = rdf_hunts.GenericHuntArgs()
generic_hunt_args.flow_runner_args.flow_name = args.flow_name
generic_hunt_args.flow_args = args.flow... |
Registers a new constructor in the factory.
Args:
name: A name associated with given constructor.
constructor: A constructor function that creates instances.
Raises:
ValueError: If there already is a constructor associated with given name.
def Register(self, name, constructor):
"""Regis... |
Unregisters a constructor.
Args:
name: A name of the constructor to unregister.
Raises:
ValueError: If constructor with specified name has never been registered.
def Unregister(self, name):
"""Unregisters a constructor.
Args:
name: A name of the constructor to unregister.
Rais... |
Creates a new instance.
Args:
name: A name identifying the constructor to use for instantiation.
Returns:
An instance of the type that the factory supports.
def Create(self, name):
"""Creates a new instance.
Args:
name: A name identifying the constructor to use for instantiation.
... |
Registers stat entry at a given timestamp.
def AddStatEntry(self, stat_entry, timestamp):
"""Registers stat entry at a given timestamp."""
if timestamp in self._stat_entries:
message = ("Duplicated stat entry write for path '%s' of type '%s' at "
"timestamp '%s'. Old: %s. New: %s.")
... |
Registers hash entry at a given timestamp.
def AddHashEntry(self, hash_entry, timestamp):
"""Registers hash entry at a given timestamp."""
if timestamp in self._hash_entries:
message = ("Duplicated hash entry write for path '%s' of type '%s' at "
"timestamp '%s'. Old: %s. New: %s.")
... |
Updates existing path information of the path record.
def AddPathInfo(self, path_info):
"""Updates existing path information of the path record."""
if self._path_type != path_info.path_type:
message = "Incompatible path types: `%s` and `%s`"
raise ValueError(message % (self._path_type, path_info.p... |
Makes the path aware of some child.
def AddChild(self, path_info):
"""Makes the path aware of some child."""
if self._path_type != path_info.path_type:
message = "Incompatible path types: `%s` and `%s`"
raise ValueError(message % (self._path_type, path_info.path_type))
if self._components != p... |
Generates a summary about the path record.
Args:
timestamp: A point in time from which the data should be retrieved.
Returns:
A `rdf_objects.PathInfo` instance.
def GetPathInfo(self, timestamp=None):
"""Generates a summary about the path record.
Args:
timestamp: A point in time fro... |
Searches for greatest timestamp lower than the specified one.
Args:
dct: A dictionary from timestamps to some items.
upper_bound_timestamp: An upper bound for timestamp to be returned.
Returns:
Greatest timestamp that is lower than the specified one. If no such value
exists, `None` is ... |
Retrieves a path info record for a given path.
def ReadPathInfo(self, client_id, path_type, components, timestamp=None):
"""Retrieves a path info record for a given path."""
try:
path_record = self.path_records[(client_id, path_type, components)]
return path_record.GetPathInfo(timestamp=timestamp)
... |
Retrieves path info records for given paths.
def ReadPathInfos(self, client_id, path_type, components_list):
"""Retrieves path info records for given paths."""
result = {}
for components in components_list:
try:
path_record = self.path_records[(client_id, path_type, components)]
resu... |
Lists path info records that correspond to children of given path.
def ListDescendentPathInfos(self,
client_id,
path_type,
components,
timestamp=None,
max_depth=None):
... |
Writes a single path info record for given client.
def _WritePathInfo(self, client_id, path_info):
"""Writes a single path info record for given client."""
if client_id not in self.metadatas:
raise db.UnknownClientError(client_id)
path_record = self._GetPathRecord(client_id, path_info)
path_reco... |
Clears path history for specified paths of given clients.
def MultiClearPathHistory(self, path_infos):
"""Clears path history for specified paths of given clients."""
for client_id, client_path_infos in iteritems(path_infos):
self.ClearPathHistory(client_id, client_path_infos) |
Clears path history for specified paths of given client.
def ClearPathHistory(self, client_id, path_infos):
"""Clears path history for specified paths of given client."""
for path_info in path_infos:
path_record = self._GetPathRecord(client_id, path_info)
path_record.ClearHistory() |
Writes a collection of hash and stat entries observed for given paths.
def MultiWritePathHistory(self, client_path_histories):
"""Writes a collection of hash and stat entries observed for given paths."""
for client_path, client_path_history in iteritems(client_path_histories):
if client_path.client_id no... |
Reads a collection of hash and stat entries for given paths.
def ReadPathInfosHistories(self, client_id, path_type, components_list):
"""Reads a collection of hash and stat entries for given paths."""
results = {}
for components in components_list:
try:
path_record = self.path_records[(clien... |
Turn supported_os into a condition.
def ConvertSupportedOSToConditions(src_object):
"""Turn supported_os into a condition."""
if src_object.supported_os:
conditions = " OR ".join("os == '%s'" % o for o in src_object.supported_os)
return conditions |
Prepare bundle of artifacts and their dependencies for the client.
Args:
flow_args: An `ArtifactCollectorFlowArgs` instance.
knowledge_base: contains information about the client
Returns:
rdf value object containing a list of extended artifacts and the
knowledge base
def GetArtifactCollectorArgs(... |
Check conditions on the source.
def MeetsConditions(knowledge_base, source):
"""Check conditions on the source."""
source_conditions_met = True
os_conditions = ConvertSupportedOSToConditions(source)
if os_conditions:
source.conditions.append(os_conditions)
for condition in source.conditions:
source_c... |
Wrapper for the ArtifactArranger.
Extend the artifact list by dependencies and sort the artifacts to resolve the
dependencies.
Args:
os_name: String specifying the OS name.
artifact_list: List of requested artifact names.
Returns:
A list of artifacts such that if they are collected in the given o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.