INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create n clients to run in a pool. | def CreateClientPool(n):
"""Create n clients to run in a pool."""
clients = []
# Load previously stored clients.
try:
certificates = []
with open(flags.FLAGS.cert_file, "rb") as fd:
# Certificates are base64-encoded, so that we can use new-lines as
# separators.
for l in fd:
c... |
Checks that the poolclient is not accidentally ran against production. | def CheckLocation():
"""Checks that the poolclient is not accidentally ran against production."""
for url in (config.CONFIG["Client.server_urls"] +
config.CONFIG["Client.control_urls"]):
if "staging" in url or "localhost" in url:
# This is ok.
return
logging.error("Poolclient should ... |
Event loop. | def Run(self):
"""Event loop."""
if data_store.RelationalDBEnabled():
data_store.REL_DB.RegisterMessageHandler(
self._ProcessMessageHandlerRequests,
self.well_known_flow_lease_time,
limit=100)
data_store.REL_DB.RegisterFlowProcessingHandler(self.ProcessFlow)
try:
... |
Processes message handler requests. | def _ProcessMessageHandlerRequests(self, requests):
"""Processes message handler requests."""
logging.debug("Leased message handler request ids: %s",
",".join(str(r.request_id) for r in requests))
grouped_requests = collection.Group(requests, lambda r: r.handler_name)
for handler_name,... |
Processes one set of messages from Task Scheduler. | def RunOnce(self):
"""Processes one set of messages from Task Scheduler.
The worker processes new jobs from the task master. For each job
we retrieve the session from the Task Scheduler.
Returns:
Total number of messages processed by this call.
"""
start_time = time.time()
processe... |
Processes all the flows in the messages. | def ProcessMessages(self, active_notifications, queue_manager, time_limit=0):
"""Processes all the flows in the messages.
Precondition: All tasks come from the same queue.
Note that the server actually completes the requests in the
flow when receiving the messages from the client. We do not really
... |
Processes messages for a given flow. | def _ProcessRegularFlowMessages(self, flow_obj, notification):
"""Processes messages for a given flow."""
session_id = notification.session_id
if not isinstance(flow_obj, flow.FlowBase):
logging.warning("%s is not a proper flow object (got %s)", session_id,
type(flow_obj))
... |
Does the real work with a single flow. | def _ProcessMessages(self, notification, queue_manager):
"""Does the real work with a single flow."""
flow_obj = None
session_id = notification.session_id
try:
# Take a lease on the flow:
flow_name = session_id.FlowName()
if flow_name in self.well_known_flows:
# Well known flo... |
The callback for the flow processing queue. | def ProcessFlow(self, flow_processing_request):
"""The callback for the flow processing queue."""
client_id = flow_processing_request.client_id
flow_id = flow_processing_request.flow_id
data_store.REL_DB.AckFlowProcessingRequests([flow_processing_request])
try:
rdf_flow = data_store.REL_DB.... |
Wait until the operation is done. | def WaitUntilDone(self, timeout=None):
"""Wait until the operation is done.
Args:
timeout: timeout in seconds. None means default timeout (1 hour).
0 means no timeout (wait forever).
Returns:
Operation object with refreshed target_file.
Raises:
PollTimeoutError: if time... |
Fetch file s data and return proper File object. | def Get(self):
"""Fetch file's data and return proper File object."""
args = vfs_pb2.ApiGetFileDetailsArgs(
client_id=self.client_id, file_path=self.path)
data = self._context.SendRequest("GetFileDetails", args).file
return File(client_id=self.client_id, data=data, context=self._context) |
Gets an output plugin index for a plugin with a given id. | def GetOutputPluginIndex(
plugin_descriptors,
plugin_id):
"""Gets an output plugin index for a plugin with a given id.
Historically output plugins descriptors were stored in dicts-like
structures with unique identifiers as keys. In REL_DB-based implementation,
however, both plugin descriptors and their... |
Resolve a URN of a flow with this id belonging to a given cron job. | def ResolveCronJobFlowURN(self, cron_job_id):
"""Resolve a URN of a flow with this id belonging to a given cron job."""
if not self._value:
raise ValueError("Can't call ResolveCronJobFlowURN on an empty "
"client id.")
return cron_job_id.ToURN().Add(self._value) |
Resolve a URN of a flow with this id belonging to a given client. | def ResolveClientFlowURN(self, client_id, token=None):
"""Resolve a URN of a flow with this id belonging to a given client.
Note that this may need a roundtrip to the datastore. Resolving algorithm
is the following:
1. If the flow id doesn't contain slashes (flow is not nested), we just
append... |
Get a simplified description of the args_type for a flow. | def _GetArgsDescription(self, args_type):
"""Get a simplified description of the args_type for a flow."""
args = {}
if args_type:
for type_descriptor in args_type.type_infos:
if not type_descriptor.hidden:
args[type_descriptor.name] = {
"description": type_descriptor.de... |
Get a description of the calling prototype for this flow class. | def _GetCallingPrototypeAsString(self, flow_cls):
"""Get a description of the calling prototype for this flow class."""
output = []
output.append("flow.StartAFF4Flow(client_id=client_id, ")
output.append("flow_name=\"%s\", " % flow_cls.__name__)
prototypes = []
if flow_cls.args_type:
for t... |
Get a string description of the calling prototype for this flow. | def _GetFlowArgsHelpAsString(self, flow_cls):
"""Get a string description of the calling prototype for this flow."""
output = [
" Call Spec:",
" %s" % self._GetCallingPrototypeAsString(flow_cls), ""
]
arg_list = sorted(
iteritems(self._GetArgsDescription(flow_cls.args_type)),... |
Renders list of descriptors for all the flows. | def Handle(self, args, token=None):
"""Renders list of descriptors for all the flows."""
if data_store.RelationalDBEnabled():
flow_iterator = iteritems(registry.FlowRegistry.FLOW_REGISTRY)
else:
flow_iterator = iteritems(registry.AFF4FlowRegistry.FLOW_REGISTRY)
result = []
for name, cl... |
Allow given user access to a given subject. | def AuthorizeUser(self, user, subject):
"""Allow given user access to a given subject."""
user_set = self.authorized_users.setdefault(subject, set())
user_set.add(user) |
Allow given group access to a given subject. | def AuthorizeGroup(self, group, subject):
"""Allow given group access to a given subject."""
# Add the subject to the dict if is isn't present, so it will get checked in
# CheckPermissions
self.authorized_users.setdefault(subject, set())
self.group_access_manager.AuthorizeGroup(group, subject) |
Checks if a given user has access to a given subject. | def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return ((username in self.authorized_users[subject]) or
self.group_access_manager.MemberOfAuthorizedGroup(
username, subject))
... |
Guess windows filenames from a commandline string. | def _GetFilePaths(self, path, pathtype, kb):
"""Guess windows filenames from a commandline string."""
environ_vars = artifact_utils.GetWindowsEnvironmentVariablesMap(kb)
path_guesses = path_detection_windows.DetectExecutablePaths([path],
envir... |
Convert persistence collector output to downloadable rdfvalues. | def Parse(self, persistence, knowledge_base, download_pathtype):
"""Convert persistence collector output to downloadable rdfvalues."""
pathspecs = []
if isinstance(persistence, rdf_client.WindowsServiceInformation):
if persistence.HasField("binary"):
pathspecs.append(persistence.binary.pathsp... |
Hacks to make the filesystem look normal. | def FileHacks(self):
"""Hacks to make the filesystem look normal."""
if sys.platform == "win32":
import win32api # pylint: disable=g-import-not-at-top
# Make the filesystem look like the topmost level are the drive letters.
if self.path == "/":
self.files = win32api.GetLogicalDriveSt... |
Read from the file. | def Read(self, length=None):
"""Read from the file."""
if self.progress_callback:
self.progress_callback()
available_to_read = max(0, (self.size or 0) - self.offset)
if length is None:
to_read = available_to_read
else:
to_read = min(length, available_to_read)
with FileHandle... |
Returns stat information of a specific path. | def _Stat(self, path, ext_attrs=False):
"""Returns stat information of a specific path.
Args:
path: A unicode string containing the path.
ext_attrs: Whether the call should also collect extended attributes.
Returns:
a StatResponse proto
Raises:
IOError when call to os.stat() f... |
List all files in the dir. | def ListFiles(self, ext_attrs=False):
"""List all files in the dir."""
if not self.IsDirectory():
raise IOError("%s is not a directory." % self.path)
for path in self.files:
try:
filepath = utils.JoinPath(self.path, path)
response = self._Stat(filepath, ext_attrs=ext_attrs)
... |
Call os. statvfs for a given list of rdf_paths. | def StatFS(self, path=None):
"""Call os.statvfs for a given list of rdf_paths.
OS X and Linux only.
Note that a statvfs call for a network filesystem (e.g. NFS) that is
unavailable, e.g. due to no network, will result in the call blocking.
Args:
path: a Unicode string containing the path or... |
Walk back from the path to find the mount point. | def GetMountPoint(self, path=None):
"""Walk back from the path to find the mount point.
Args:
path: a Unicode string containing the path or None. If path is None the
value in self.path is used.
Returns:
path string of the mount point
"""
path = os.path.abspath(
client_u... |
Writes a hunt object to the database. | def WriteHuntObject(self, hunt_obj, cursor=None):
"""Writes a hunt object to the database."""
query = """
INSERT INTO hunts (hunt_id, creator, description, duration_micros,
hunt_state,
client_rate, client_limit,
hunt)
VALUES (%(hunt_id... |
Updates the hunt object by applying the update function. | def UpdateHuntObject(self,
hunt_id,
duration=None,
client_rate=None,
client_limit=None,
hunt_state=None,
hunt_state_comment=None,
start_time=None,
... |
Deletes a given hunt object. | def DeleteHuntObject(self, hunt_id, cursor=None):
"""Deletes a given hunt object."""
query = "DELETE FROM hunts WHERE hunt_id = %s"
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
rows_deleted = cursor.execute(query, [hunt_id_int])
if rows_deleted == 0:
raise db.UnknownHuntError(hunt_id)
que... |
Generates a flow object from a database row. | def _HuntObjectFromRow(self, row):
"""Generates a flow object from a database row."""
(
create_time,
last_update_time,
creator,
duration_micros,
client_rate,
client_limit,
hunt_state,
hunt_state_comment,
init_start_time,
last_start_... |
Reads a hunt object from the database. | def ReadHuntObject(self, hunt_id, cursor=None):
"""Reads a hunt object from the database."""
query = ("SELECT {columns} "
"FROM hunts WHERE hunt_id = %s".format(
columns=_HUNT_COLUMNS_SELECT))
nr_results = cursor.execute(query, [db_utils.HuntIDToInt(hunt_id)])
if nr_result... |
Reads multiple hunt objects from the database. | def ReadHuntObjects(self,
offset,
count,
with_creator=None,
created_after=None,
with_description_match=None,
cursor=None):
"""Reads multiple hunt objects from the database."""
quer... |
Builds OutputPluginState object from a DB row. | def _HuntOutputPluginStateFromRow(self, row):
"""Builds OutputPluginState object from a DB row."""
plugin_name, plugin_args_bytes, plugin_state_bytes = row
plugin_descriptor = rdf_output_plugin.OutputPluginDescriptor(
plugin_name=plugin_name)
if plugin_args_bytes is not None:
plugin_args_... |
Reads all hunt output plugins states of a given hunt. | def ReadHuntOutputPluginsStates(self, hunt_id, cursor=None):
"""Reads all hunt output plugins states of a given hunt."""
columns = ", ".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS)
query = ("SELECT {columns} FROM hunt_output_plugins_states "
"WHERE hunt_id = %s".format(columns=columns))
rows... |
Writes hunt output plugin states for a given hunt. | def WriteHuntOutputPluginsStates(self, hunt_id, states, cursor=None):
"""Writes hunt output plugin states for a given hunt."""
columns = ", ".join(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS)
placeholders = mysql_utils.Placeholders(
2 + len(_HUNT_OUTPUT_PLUGINS_STATES_COLUMNS))
hunt_id_int = db_utils.H... |
Updates hunt output plugin state for a given output plugin. | def UpdateHuntOutputPluginState(self,
hunt_id,
state_index,
update_fn,
cursor=None):
"""Updates hunt output plugin state for a given output plugin."""
hunt_id_int = db_utils.H... |
Reads hunt log entries of a given hunt using given query options. | def ReadHuntLogEntries(self,
hunt_id,
offset,
count,
with_substring=None,
cursor=None):
"""Reads hunt log entries of a given hunt using given query options."""
hunt_id_int = db_utils.Hunt... |
Returns number of hunt log entries of a given hunt. | def CountHuntLogEntries(self, hunt_id, cursor=None):
"""Returns number of hunt log entries of a given hunt."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT COUNT(*) FROM flow_log_entries "
"FORCE INDEX(flow_log_entries_by_hunt) "
"WHERE hunt_id = %s AND flow_id = h... |
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,
with_timestamp=None,
cursor=None):
"""... |
Counts hunt results of a given hunt using given query options. | def CountHuntResults(self,
hunt_id,
with_tag=None,
with_type=None,
cursor=None):
"""Counts hunt results of a given hunt using given query options."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = "SELECT COUNT... |
Counts number of hunts results per type. | def CountHuntResultsByType(self, hunt_id, cursor=None):
"""Counts number of hunts results per type."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT type, COUNT(*) FROM flow_results "
"WHERE hunt_id = %s GROUP BY type")
cursor.execute(query, [hunt_id_int])
return dict(c... |
Builds an SQL condition matching db. HuntFlowsCondition. | def _HuntFlowCondition(self, condition):
"""Builds an SQL condition matching db.HuntFlowsCondition."""
if condition == db.HuntFlowsCondition.UNSET:
return "", []
elif condition == db.HuntFlowsCondition.FAILED_FLOWS_ONLY:
return ("AND flow_state = %s ",
[int(rdf_flow_objects.Flow.Fl... |
Reads hunt flows matching given conditins. | def ReadHuntFlows(self,
hunt_id,
offset,
count,
filter_condition=db.HuntFlowsCondition.UNSET,
cursor=None):
"""Reads hunt flows matching given conditins."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query ... |
Counts hunt flows matching given conditions. | def CountHuntFlows(self,
hunt_id,
filter_condition=db.HuntFlowsCondition.UNSET,
cursor=None):
"""Counts hunt flows matching given conditions."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT COUNT(*) FROM flows "
"FO... |
Reads hunt counters. | def ReadHuntCounters(self, hunt_id, cursor=None):
"""Reads hunt counters."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT flow_state, COUNT(*) "
"FROM flows "
"FORCE INDEX(flows_by_hunt) "
"WHERE parent_hunt_id = %s AND parent_flow_id IS NULL "
... |
Builds an SQL query part to fetch counts corresponding to given bins. | def _BinsToQuery(self, bins, column_name):
"""Builds an SQL query part to fetch counts corresponding to given bins."""
result = []
# With the current StatsHistogram implementation the last bin simply
# takes all the values that are greater than range_max_value of
# the one-before-the-last bin. range... |
Read/ calculate hunt client resources stats. | def ReadHuntClientResourcesStats(self, hunt_id, cursor=None):
"""Read/calculate hunt client resources stats."""
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = """
SELECT
COUNT(*),
SUM(user_cpu_time_used_micros),
SUM((user_cpu_time_used_micros) * (user_cpu_time_used_micros... |
Reads hunt flows states and timestamps. | def ReadHuntFlowsStatesAndTimestamps(self, hunt_id, cursor=None):
"""Reads hunt flows states and timestamps."""
query = """
SELECT
flow_state, UNIX_TIMESTAMP(timestamp), UNIX_TIMESTAMP(last_update)
FROM flows
FORCE INDEX(flows_by_hunt)
WHERE parent_hunt_id = %s AND parent_flow_i... |
Reads hunt output plugin log entries. | def ReadHuntOutputPluginLogEntries(self,
hunt_id,
output_plugin_id,
offset,
count,
with_type=None,
... |
Counts hunt output plugin log entries. | def CountHuntOutputPluginLogEntries(self,
hunt_id,
output_plugin_id,
with_type=None,
cursor=None):
"""Counts hunt output plugin log entries."""
query = ("SELECT... |
Will return True if hunt s task was assigned to this client before. | def _CheckIfHuntTaskWasAssigned(self, client_id, hunt_id):
"""Will return True if hunt's task was assigned to this client before."""
if data_store.RelationalDBEnabled():
flow_id = hunt_id
if hunt.IsLegacyHunt(hunt_id):
# Strip "H:" prefix.
flow_id = flow_id[2:]
try:
da... |
Run all the actions specified in the rule. | def _RunAction(self, rule, client_id):
"""Run all the actions specified in the rule.
Args:
rule: Rule which actions are to be executed.
client_id: Id of a client where rule's actions are to be executed.
Returns:
Number of actions started.
"""
actions_count = 0
try:
if ... |
Examines our rules and starts up flows based on the client. | def AssignTasksToClient(self, client_id):
"""Examines our rules and starts up flows based on the client.
Args:
client_id: Client id of the client for tasks to be assigned.
Returns:
Number of assigned tasks.
"""
rules = data_store.REL_DB.ReadAllForemanRules()
if not rules:
ret... |
Fetches metadata for the given binary from the datastore. | def _GetSignedBinaryMetadata(binary_type, relative_path):
"""Fetches metadata for the given binary from the datastore.
Args:
binary_type: ApiGrrBinary.Type of the binary.
relative_path: Relative path of the binary, relative to the canonical URN
roots for signed binaries (see _GetSignedBlobsRoots()).
... |
Build the data structure representing the config. | def Handle(self, unused_args, token=None):
"""Build the data structure representing the config."""
sections = {}
for descriptor in config.CONFIG.type_infos:
if descriptor.section in sections:
continue
section_data = {}
for parameter in self._ListParametersInSection(descriptor.sec... |
Renders specified config option. | def Handle(self, args, token=None):
"""Renders specified config option."""
if not args.name:
raise ValueError("Name not specified.")
return ApiConfigOption().InitFromConfigOption(args.name) |
A helper to create a proxy method in a class. | def Proxy(f):
"""A helper to create a proxy method in a class."""
def Wrapped(self, *args):
return getattr(self, f)(*args)
return Wrapped |
Synchronization decorator. | def Synchronized(f):
"""Synchronization decorator."""
@functools.wraps(f)
def NewFunction(self, *args, **kw):
with self.lock:
return f(self, *args, **kw)
return NewFunction |
Returns a unicode object. | def SmartUnicode(string):
"""Returns a unicode object.
This function will always return a unicode object. It should be used to
guarantee that something is always a unicode object.
Args:
string: The string to convert.
Returns:
a unicode object.
"""
if isinstance(string, Text):
return string
... |
Returns a bytes object where each byte has been xored with key. | def Xor(bytestr, key):
"""Returns a `bytes` object where each byte has been xored with key."""
# TODO(hanuszczak): Remove this import when string migration is done.
# pytype: disable=import-error
from builtins import bytes # pylint: disable=redefined-builtin, g-import-not-at-top
# pytype: enable=import-error... |
Takes an int and returns the number formatted as a hex string. | def FormatAsHexString(num, width=None, prefix="0x"):
"""Takes an int and returns the number formatted as a hex string."""
# Strip "0x".
hex_str = hex(num)[2:]
# Strip "L" for long values.
hex_str = hex_str.replace("L", "")
if width:
hex_str = hex_str.rjust(width, "0")
return "%s%s" % (prefix, hex_str) |
A sane implementation of os. path. normpath. | def NormalizePath(path, sep="/"):
"""A sane implementation of os.path.normpath.
The standard implementation treats leading / and // as different leading to
incorrect normal forms.
NOTE: Its ok to use a relative path here (without leading /) but any /../ will
still be removed anchoring the path at the top le... |
A sane version of os. path. join. | def JoinPath(stem="", *parts):
"""A sane version of os.path.join.
The intention here is to append the stem to the path. The standard module
removes the path if the stem begins with a /.
Args:
stem: The stem to join to.
*parts: parts of the path to join. The first arg is always the root and
di... |
Create a 20 char passphrase with easily typeable chars. | def GeneratePassphrase(length=20):
"""Create a 20 char passphrase with easily typeable chars."""
valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
valid_chars += "0123456789 ,-_&$#"
return "".join(random.choice(valid_chars) for i in range(length)) |
A utility function to read a passphrase from stdin. | def PassphraseCallback(verify=False,
prompt1="Enter passphrase:",
prompt2="Verify passphrase:"):
"""A utility function to read a passphrase from stdin."""
while 1:
try:
p1 = getpass.getpass(prompt1)
if verify:
p2 = getpass.getpass(prompt2)
... |
Resolves a hostname to an IP address. | def ResolveHostnameToIP(host, port):
"""Resolves a hostname to an IP address."""
ip_addrs = socket.getaddrinfo(host, port, socket.AF_UNSPEC, 0,
socket.IPPROTO_TCP)
# getaddrinfo returns tuples (family, socktype, proto, canonname, sockaddr).
# We are interested in sockaddr which i... |
Expires old cache entries. | def Expire(self):
"""Expires old cache entries."""
while len(self._age) > self._limit:
node = self._age.PopLeft()
self._hash.pop(node.key, None)
self.KillObject(node.data) |
Add the object to the cache. | def Put(self, key, obj):
"""Add the object to the cache."""
# Remove the old entry if it is there.
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
# Make a new node and insert it.
node = Node(key=key, data=obj)
self._hash[key] = node
self._age.AppendNode(node)
... |
Expire a specific object from cache. | def ExpireObject(self, key):
"""Expire a specific object from cache."""
node = self._hash.pop(key, None)
if node:
self._age.Unlink(node)
self.KillObject(node.data)
return node.data |
Expire all the objects with the key matching the regex. | def ExpireRegEx(self, regex):
"""Expire all the objects with the key matching the regex."""
reg = re.compile(regex)
for key in list(self._hash):
if reg.match(key):
self.ExpireObject(key) |
Expire all the objects with the key having a given prefix. | def ExpirePrefix(self, prefix):
"""Expire all the objects with the key having a given prefix."""
for key in list(self._hash):
if key.startswith(prefix):
self.ExpireObject(key) |
Remove the object from the cache completely. | def Pop(self, key):
"""Remove the object from the cache completely."""
node = self._hash.get(key)
if node:
del self._hash[key]
self._age.Unlink(node)
return node.data |
Fetch the object from cache. | def Get(self, key):
"""Fetch the object from cache.
Objects may be flushed from cache at any time. Callers must always
handle the possibility of KeyError raised here.
Args:
key: The key used to access the object.
Returns:
Cached object.
Raises:
KeyError: If the object is no... |
Flush all items from cache. | def Flush(self):
"""Flush all items from cache."""
while self._age:
node = self._age.PopLeft()
self.KillObject(node.data)
self._hash = dict() |
Calculate the size of the struct. | def GetSize(cls):
"""Calculate the size of the struct."""
format_str = "".join([x[0] for x in cls._fields])
return struct.calcsize(format_str) |
Gets stream buffer since the last GetValueAndReset () call. | def GetValueAndReset(self):
"""Gets stream buffer since the last GetValueAndReset() call."""
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to get a value from a closed stream.")
value = self._stream.getvalue()
self._stream.seek(0)
self._stream.truncate()
ret... |
Generate ZipInfo instance for the given name compression and stat. | def _GenerateZipInfo(self, arcname=None, compress_type=None, st=None):
"""Generate ZipInfo instance for the given name, compression and stat.
Args:
arcname: The name in the archive this should take.
compress_type: Compression type (zipfile.ZIP_DEFLATED, or ZIP_STORED)
st: An optional stat obj... |
Writes a symlink into the archive. | def WriteSymlink(self, src_arcname, dst_arcname):
"""Writes a symlink into the archive."""
# Inspired by:
# http://www.mail-archive.com/python-list@python.org/msg34223.html
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already close... |
Writes a file header. | def WriteFileHeader(self, arcname=None, compress_type=None, st=None):
"""Writes a file header."""
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
self.cur_zinfo = self._GenerateZipInfo(
arcname=arcname, compress... |
Writes file chunk. | def WriteFileChunk(self, chunk):
"""Writes file chunk."""
precondition.AssertType(chunk, bytes)
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
self.cur_file_size += len(chunk)
# TODO(user):pytype: crc32 is not ... |
Writes the file footer ( finished the file ). | def WriteFileFooter(self):
"""Writes the file footer (finished the file)."""
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
if self.cur_cmpr:
buf = self.cur_cmpr.flush()
self.cur_compress_size += len(buf)
... |
Write a zip member from a file like object. | def WriteFromFD(self, src_fd, arcname=None, compress_type=None, st=None):
"""Write a zip member from a file like object.
Args:
src_fd: A file like object, must support seek(), tell(), read().
arcname: The name in the archive this should take.
compress_type: Compression type (zipfile.ZIP_DEFLA... |
Writes a symlink into the archive. | def WriteSymlink(self, src_arcname, dst_arcname):
"""Writes a symlink into the archive."""
info = self._tar_fd.tarinfo()
info.tarfile = self._tar_fd
info.name = SmartStr(dst_arcname)
info.size = 0
info.mtime = time.time()
info.type = tarfile.SYMTYPE
info.linkname = SmartStr(src_arcname)... |
Writes file header. | def WriteFileHeader(self, arcname=None, st=None):
"""Writes file header."""
if st is None:
raise ValueError("Stat object can't be None.")
self.cur_file_size = 0
self.cur_info = self._tar_fd.tarinfo()
self.cur_info.tarfile = self._tar_fd
self.cur_info.type = tarfile.REGTYPE
self.cur_... |
Writes file chunk. | def WriteFileChunk(self, chunk):
"""Writes file chunk."""
self._tar_fd.fileobj.write(chunk)
self.cur_file_size += len(chunk)
return self._stream.GetValueAndReset() |
Writes file footer ( finishes the file ). | def WriteFileFooter(self):
"""Writes file footer (finishes the file)."""
if self.cur_file_size != self.cur_info.size:
raise IOError("Incorrect file size: st_size=%d, but written %d bytes." %
(self.cur_info.size, self.cur_file_size))
# TODO(user):pytype: BLOCKSIZE/NUL constants ar... |
Fetches user s data and returns it wrapped in a Grruser object. | def Get(self):
"""Fetches user's data and returns it wrapped in a Grruser object."""
args = user_management_pb2.ApiGetGrrUserArgs(username=self.username)
data = self._context.SendRequest("GetGrrUser", args)
return GrrUser(data=data, context=self._context) |
Deletes the user. | def Delete(self):
"""Deletes the user."""
args = user_management_pb2.ApiDeleteGrrUserArgs(username=self.username)
self._context.SendRequest("DeleteGrrUser", args) |
Modifies user s type and/ or password. | def Modify(self, user_type=None, password=None):
"""Modifies user's type and/or password."""
args = user_management_pb2.ApiModifyGrrUserArgs(
username=self.username, user_type=user_type)
if user_type is not None:
args.user_type = user_type
if password is not None:
args.password = ... |
Uploads data from a given stream and signs them with a given key. | def Upload(self, fd, sign_fn=None):
"""Uploads data from a given stream and signs them with a given key."""
if not sign_fn:
raise ValueError("sign_fn can't be empty. "
"See DefaultUploadSigner as a possible option.")
args = binary_management_pb2.ApiUploadGrrBinaryArgs(
... |
Creates a new GRR user of a given type with a given username/ password. | def CreateGrrUser(self, username=None, user_type=None, password=None):
"""Creates a new GRR user of a given type with a given username/password."""
if not username:
raise ValueError("Username can't be empty.")
args = user_management_pb2.ApiCreateGrrUserArgs(username=username)
if user_type is no... |
Lists all registered GRR users. | def ListGrrUsers(self):
"""Lists all registered GRR users."""
args = user_management_pb2.ApiListGrrUsersArgs()
items = self._context.SendIteratorRequest("ListGrrUsers", args)
return utils.MapItemsIterator(
lambda data: GrrUser(data=data, context=self._context), items) |
Return all audit log entries between now - offset and now. | def GetAuditLogEntries(offset, now, token):
"""Return all audit log entries between now-offset and now.
Args:
offset: rdfvalue.Duration how far back to look in time
now: rdfvalue.RDFDatetime for current time
token: GRR access token
Yields:
AuditEvents created during the time range
"""
start_t... |
Fetches client data from the relational db. | def _IterateAllClients(recency_window=None):
"""Fetches client data from the relational db.
Args:
recency_window: An rdfvalue.Duration specifying a window of last-ping
timestamps to consider. Clients that haven't communicated with GRR servers
longer than the given period will be skipped. If recency... |
Adds another instance of this category into the active_days counter. | def Add(self, category, label, age):
"""Adds another instance of this category into the active_days counter.
We automatically count the event towards all relevant active_days. For
example, if the category "Windows" was seen 8 days ago it will be counted
towards the 30 day active, 14 day active but not ... |
Generate a histogram object and store in the specified attribute. | def Save(self, token=None):
"""Generate a histogram object and store in the specified attribute."""
graph_series_by_label = {}
for active_time in self.active_days:
for label in self.categories[active_time]:
graphs_for_label = graph_series_by_label.setdefault(
label, rdf_stats.Clien... |
Retrieve all the clients for the AbstractClientStatsCollectors. | def Run(self):
"""Retrieve all the clients for the AbstractClientStatsCollectors."""
try:
self.stats = {}
self.BeginProcessing()
processed_count = 0
for client_info_batch in _IterateAllClients(
recency_window=self.recency_window):
for client_info in client_info_batc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.