INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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_list)) |
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 around it using temporary
files.
Args:
in_buffer: data to sign
Returns:
signed data
"""
precondition.AssertType(in_buffer, bytes)
with tempfile.NamedTemporary... |
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... | def SignFile(self, in_filename, out_filename=None):
"""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:
... |
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 = [
"--define=%%_g... |
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(token=token)
client_list = index.LookupClients([query_str])
result_set ... |
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... | def DownloadDir(aff4_path, output_dir, bufsize=8192, preserve_path=True):
"""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: ... |
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=None):
"""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 w... |
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_NOTIFICATIONS)) |
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:
_, client_id, user, reason = rdfvalue.RDFURN(r... |
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=user)
print("Found token %s" % str(approved_t... |
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... | def ApprovalCreateRaw(aff4_path,
reason="",
expire_in=60 * 60 * 24 * 7,
token=None,
approval_type="ClientApproval"):
"""Creates an approval with raw access.
This method requires raw datastore access to manipulate approvals dire... |
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 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.
"""
try:
urn = r... |
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 reported by this client.
hw_infos = {}
logging.info("%d clients to proce... |
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... | def FindClonedClients(token=None):
"""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 w... |
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... | def CleanClientVersions(clients=None, dry_run=True, token=None):
"""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 t... |
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... | def CleanVacuousVersions(clients=None, dry_run=True):
"""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, ... |
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... | def ExportClientsByKeywords(keywords, filename, token=None):
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:
ke... |
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... | def WakeStuckFlow(session_id):
"""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 clien... |
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.PortInUseError(self.port)
... |
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.
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.
"""
# Figure out which port ... |
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.installed_re.match(pkg["S... |
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)):
raise process_error.ProcessError("... |
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.pid)
if self.Is64bit():
... |
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, address, buf, num_bytes,
ctype... |
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(migrations_root):
if (current_migration_number is None or
_Migra... |
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... | def ProcessMigrations(open_conn_fn,
migrations_root):
"""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 connection... |
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 TABLE `{}`".format(table))
ro... |
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 needs to be greater than or equal to zero")
count = 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")
if count < 0:
raise ValueError("Count needs to be greater than or e... |
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, "../../version.ini")
if not os.path.exists... |
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"),
os.path.join(self.package_dir,... |
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:
input_dir: the name of the input directory.
output_file: the name of the output ZIP archive without extension.
"""
logging.info("Generating zip template file at %s", output_file)
... |
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:
rpm_spec_filename = "grr.spec.in"... |
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 WEBAUTH_MANAGER.SecurityCheck(func, request, *ar... |
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.ValidateIapJwtFromCompute... |
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_type == "Basic":
... |
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 ValueError("JWT token is missing.")
token = auth_head... |
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, **kwargs) |
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
logging.info("Using webauth ma... |
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
... | def GetQueryParamsNames(self):
"""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 annota... |
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(cls)):
for name in compatibility.ListAttrs(i... |
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... | def PublishEvent(cls, event_name, msg, token=None):
"""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: A... |
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 PublishMultipleEvents(cls, events, token=None):
"""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
... |
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, "
"Parent: %s" % (type(child), type(pare... |
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... | def FanOut(self, obj, parent=None):
"""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:
... |
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... | def Format(self, format_string, rdf):
"""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 objec... |
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... | def Update(self, attribute=None):
"""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 l... |
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 read
# access pattern is contiguous reading so since we hav... |
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)
chunk.dirty = True
return chunk
exc... |
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
# we can't read anymore. We return the empty string... |
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._HASH_SIZE))
# If we're adding a new blob, ... |
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_numbers}
for metadata in aff4.FA... |
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_delete=self.to_delete)
self.to... |
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 "
"enabled=VALUES(enabled)")
... |
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.CronJob.FromSerializedString(job)
job.current_run_id... |
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_id, state, "
"UNIX_TIMESTA... |
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.unchanged,
forced_run_requested=... |
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 = utils.ProcessIdString()
qu... |
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_until:
unleased_jobs.append(job)
con... |
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 DUPLICATE KEY UPDATE "
"run=VALUES(... |
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._CronJobRunFromRow(row) for row in cursor.fetchall... |
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, [job_id, db_utils.CronJobRunIDToInt(run_id)]... |
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,
[mysql_utils.RDFDatetimeToTimestamp(cutoff_timestamp)]) |
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 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.
"""
precondition.AssertIterableType(v... |
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(chunk_begins):
chunks.append({
"blob_id": bl... |
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_SIZE or
len(partitions[-1]) >= CHUNKS_PER_INSERT):
par... |
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 ASC").format(
... |
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) "
"WHERE blob_id IN {}".format(
... |
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).SerializeToString()
values.append({
"hash_id": ... |
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)))
cursor.execute(query, [hash_id.AsBytes() for hash_id... |
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):
"""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 argumen... |
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.Split()
if not split or len(split) < 2:
return None
# Normalize to lowercase.
split = [s.lower() for s in split]
str_clien... |
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 = (
QueueManager.notification_shar... |
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 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.
"""
result = QueueManager(store=self.data_store, tok... |
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... | def FreezeTimestamp(self):
"""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 deletin... |
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_timestamps.pop() |
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, status in self.data_store.ReadCompletedRequests(
session_id... |
Fetch only completed requests and responses up to a limit. | def FetchCompletedResponses(self, session_id, timestamp=None, limit=10000):
"""Fetch only completed requests and responses up to a limit."""
if timestamp is None:
timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now())
completed_requests = collections.deque(
self.FetchCompletedRe... |
Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the requests/responses for.
timestamp: Tuple (start, end) with a time range. Fetched requests and
... | def FetchRequestsAndResponses(self, session_id, timestamp=None):
"""Fetches all outstanding requests and responses for this flow.
We first cache all requests and responses for this flow in memory to
prevent round trips.
Args:
session_id: The session_id to get the requests/responses for.
ti... |
Deletes the request and all its responses from the flow state queue. | def DeleteRequest(self, request):
"""Deletes the request and all its responses from the flow state queue."""
self.requests_to_delete.append(request)
if request and request.HasField("request"):
self.DeQueueClientRequest(request.request)
data_store.DB.DeleteRequest(request) |
Deletes all states in multiple flows and dequeues all client messages. | def MultiDestroyFlowStates(self, session_ids):
"""Deletes all states in multiple flows and dequeues all client messages."""
deleted_requests = self.data_store.MultiDestroyFlowStates(
session_ids, request_limit=self.request_limit)
for request in deleted_requests:
if request.HasField("request")... |
Writes the changes in this object to the datastore. | def Flush(self):
"""Writes the changes in this object to the datastore."""
self.data_store.StoreRequestsAndResponses(
new_requests=self.request_queue,
new_responses=self.response_queue,
requests_to_delete=self.requests_to_delete)
# We need to make sure that notifications are writte... |
Queues the message on the flow's state. | def QueueResponse(self, response, timestamp=None):
"""Queues the message on the flow's state."""
if timestamp is None:
timestamp = self.frozen_timestamp
self.response_queue.append((response, timestamp)) |
Queues a notification for a flow. | def QueueNotification(self, notification=None, timestamp=None, **kw):
"""Queues a notification for a flow."""
if notification is None:
notification = rdf_flows.GrrNotification(**kw)
session_id = notification.session_id
if session_id:
if timestamp is None:
timestamp = self.frozen_t... |
Removes the tasks from the queue.
Note that tasks can already have been removed. It is not an error
to re-delete an already deleted task.
Args:
queue: A queue to clear.
tasks: A list of tasks to remove. Tasks may be Task() instances or integers
representing the task_id.
mutation_pool... | def Delete(self, queue, tasks, mutation_pool=None):
"""Removes the tasks from the queue.
Note that tasks can already have been removed. It is not an error
to re-delete an already deleted task.
Args:
queue: A queue to clear.
tasks: A list of tasks to remove. Tasks may be Task() instances or i... |
Schedule a set of Task() instances. | def Schedule(self, tasks, mutation_pool, timestamp=None):
"""Schedule a set of Task() instances."""
non_fleetspeak_tasks = []
for queue, queued_tasks in iteritems(
collection.Group(tasks, lambda x: x.queue)):
if not queue:
continue
client_id = _GetClientIdFromQueue(queue)
... |
Returns all queue notifications. | def GetNotifications(self, queue):
"""Returns all queue notifications."""
queue_shard = self.GetNotificationShard(queue)
return self._GetUnsortedNotifications(queue_shard).values() |
Returns notifications for all shards of a queue at once.
Used by worker_test_lib.MockWorker to cover all shards with a single worker.
Args:
queue: usually rdfvalue.RDFURN("aff4:/W")
Returns:
List of rdf_flows.GrrNotification objects | def GetNotificationsForAllShards(self, queue):
"""Returns notifications for all shards of a queue at once.
Used by worker_test_lib.MockWorker to cover all shards with a single worker.
Args:
queue: usually rdfvalue.RDFURN("aff4:/W")
Returns:
List of rdf_flows.GrrNotification objects
""... |
Returns all the available notifications for a queue_shard.
Args:
queue_shard: urn of queue shard
notifications_by_session_id: store notifications in this dict rather than
creating a new one
Returns:
dict of notifications. keys are session ids. | def _GetUnsortedNotifications(self,
queue_shard,
notifications_by_session_id=None):
"""Returns all the available notifications for a queue_shard.
Args:
queue_shard: urn of queue shard
notifications_by_session_id: store notifications in... |
This signals that there are new messages available in a queue. | def NotifyQueue(self, notification, **kwargs):
"""This signals that there are new messages available in a queue."""
self._MultiNotifyQueue(notification.session_id.Queue(), [notification],
**kwargs) |
This is the same as NotifyQueue but for several session_ids at once.
Args:
notifications: A list of notifications.
mutation_pool: A MutationPool object to schedule Notifications on.
Raises:
RuntimeError: An invalid session_id was passed. | def MultiNotifyQueue(self, notifications, mutation_pool=None):
"""This is the same as NotifyQueue but for several session_ids at once.
Args:
notifications: A list of notifications.
mutation_pool: A MutationPool object to schedule Notifications on.
Raises:
RuntimeError: An invalid session... |
Does the actual queuing. | def _MultiNotifyQueue(self, queue, notifications, mutation_pool=None):
"""Does the actual queuing."""
notification_list = []
now = rdfvalue.RDFDatetime.Now()
for notification in notifications:
if not notification.first_queued:
notification.first_queued = (
self.frozen_timestamp... |
This deletes the notification when all messages have been processed. | def DeleteNotifications(self, session_ids, start=None, end=None):
"""This deletes the notification when all messages have been processed."""
if not session_ids:
return
for session_id in session_ids:
if not isinstance(session_id, rdfvalue.SessionID):
raise RuntimeError(
"Can ... |
Retrieves tasks from a queue without leasing them.
This is good for a read only snapshot of the tasks.
Args:
queue: The task queue that this task belongs to, usually client.Queue()
where client is the ClientURN object you want to schedule msgs on.
limit: Number of values to fetch.
... | def Query(self, queue, limit=1):
"""Retrieves tasks from a queue without leasing them.
This is good for a read only snapshot of the tasks.
Args:
queue: The task queue that this task belongs to, usually client.Queue()
where client is the ClientURN object you want to schedule msgs on.
... |
Returns a list of Tasks leased for a certain time.
Args:
queue: The queue to query from.
lease_seconds: The tasks will be leased for this long.
limit: Number of values to fetch.
Returns:
A list of GrrMessage() objects leased. | def QueryAndOwn(self, queue, lease_seconds=10, limit=1):
"""Returns a list of Tasks leased for a certain time.
Args:
queue: The queue to query from.
lease_seconds: The tasks will be leased for this long.
limit: Number of values to fetch.
Returns:
A list of GrrMessage() objects le... |
Retrieves responses for a well known flow.
Args:
session_id: The session_id to get the requests/responses for.
Yields:
The retrieved responses. | def FetchResponses(self, session_id):
"""Retrieves responses for a well known flow.
Args:
session_id: The session_id to get the requests/responses for.
Yields:
The retrieved responses.
"""
timestamp = (0, self.frozen_timestamp or rdfvalue.RDFDatetime.Now())
for response in self.da... |
Migrate one Artifact from AFF4 to REL_DB. | def _MigrateArtifact(artifact):
"""Migrate one Artifact from AFF4 to REL_DB."""
name = Text(artifact.name)
try:
logging.info("Migating %s", name)
data_store.REL_DB.WriteArtifact(artifact)
logging.info(" Wrote %s", name)
except db.DuplicatedArtifactError:
logging.info(" Skipped %s, because art... |
Migrates Artifacts from AFF4 to REL_DB. | def MigrateArtifacts():
"""Migrates Artifacts from AFF4 to REL_DB."""
# First, delete all existing artifacts in REL_DB.
artifacts = data_store.REL_DB.ReadAllArtifacts()
if artifacts:
logging.info("Deleting %d artifacts from REL_DB.", len(artifacts))
for artifact in data_store.REL_DB.ReadAllArtifacts():... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.