partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
SearchClients
Search indexes for clients. Returns list (client, hostname, os version).
grr/server/grr_response_server/console_utils.py
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 ...
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 ...
[ "Search", "indexes", "for", "clients", ".", "Returns", "list", "(", "client", "hostname", "os", "version", ")", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L48-L63
[ "def", "SearchClients", "(", "query_str", ",", "token", "=", "None", ",", "limit", "=", "1000", ")", ":", "client_schema", "=", "aff4", ".", "AFF4Object", ".", "classes", "[", "\"VFSGRRClient\"", "]", ".", "SchemaCls", "index", "=", "client_index", ".", "C...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
DownloadDir
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...
grr/server/grr_response_server/console_utils.py
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: ...
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: ...
[ "Take", "an", "aff4", "path", "and", "download", "all", "files", "in", "it", "to", "output_dir", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L66-L99
[ "def", "DownloadDir", "(", "aff4_path", ",", "output_dir", ",", "bufsize", "=", "8192", ",", "preserve_path", "=", "True", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "output_dir", ")", ":", "os", ".", "makedirs", "(", "output_dir", ")...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
OpenClient
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.
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Opens", "the", "client", "getting", "potential", "approval", "tokens", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L107-L133
[ "def", "OpenClient", "(", "client_id", "=", "None", ",", "token", "=", "None", ")", ":", "if", "not", "token", ":", "try", ":", "token", "=", "ApprovalFind", "(", "client_id", ",", "token", "=", "token", ")", "except", "access_control", ".", "Unauthorize...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
GetNotifications
Show pending notifications for a user.
grr/server/grr_response_server/console_utils.py
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))
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))
[ "Show", "pending", "notifications", "for", "a", "user", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L136-L142
[ "def", "GetNotifications", "(", "user", "=", "None", ",", "token", "=", "None", ")", ":", "if", "not", "user", ":", "user", "=", "getpass", ".", "getuser", "(", ")", "user_obj", "=", "aff4", ".", "FACTORY", ".", "Open", "(", "aff4", ".", "ROOT_URN", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ApprovalGrant
Iterate through requested access approving or not.
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Iterate", "through", "requested", "access", "approving", "or", "not", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L177-L194
[ "def", "ApprovalGrant", "(", "token", "=", "None", ")", ":", "user", "=", "getpass", ".", "getuser", "(", ")", "notifications", "=", "GetNotifications", "(", "user", "=", "user", ",", "token", "=", "token", ")", "requests", "=", "[", "n", "for", "n", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ApprovalFind
Find approvals issued for a specific client.
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Find", "approvals", "issued", "for", "a", "specific", "client", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L197-L207
[ "def", "ApprovalFind", "(", "object_id", ",", "token", "=", "None", ")", ":", "user", "=", "getpass", ".", "getuser", "(", ")", "object_id", "=", "rdfvalue", ".", "RDFURN", "(", "object_id", ")", "try", ":", "approved_token", "=", "security", ".", "Appro...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ApprovalCreateRaw
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...
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Creates", "an", "approval", "with", "raw", "access", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L210-L267
[ "def", "ApprovalCreateRaw", "(", "aff4_path", ",", "reason", "=", "\"\"", ",", "expire_in", "=", "60", "*", "60", "*", "24", "*", "7", ",", "token", "=", "None", ",", "approval_type", "=", "\"ClientApproval\"", ")", ":", "if", "approval_type", "in", "[",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ApprovalRevokeRaw
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.
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Revokes", "an", "approval", "for", "a", "given", "token", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L270-L293
[ "def", "ApprovalRevokeRaw", "(", "aff4_path", ",", "token", ")", ":", "try", ":", "urn", "=", "rdf_client", ".", "ClientURN", "(", "aff4_path", ")", "except", "type_info", ".", "TypeValueError", ":", "urn", "=", "rdfvalue", ".", "RDFURN", "(", "aff4_path", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_GetHWInfos
Opens the given clients in batches and returns hardware information.
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Opens", "the", "given", "clients", "in", "batches", "and", "returns", "hardware", "information", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L296-L318
[ "def", "_GetHWInfos", "(", "client_list", ",", "batch_size", "=", "10000", ",", "token", "=", "None", ")", ":", "# This function returns a dict mapping each client_id to a set of reported", "# hardware serial numbers reported by this client.", "hw_infos", "=", "{", "}", "logg...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
FindClonedClients
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...
grr/server/grr_response_server/console_utils.py
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...
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", "find", "multiple", "machines", "reporting", "the", "same", "client_id", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L321-L392
[ "def", "FindClonedClients", "(", "token", "=", "None", ")", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", "token", "=", "token", ")", "clients", "=", "index", ".", "LookupClients", "(", "[", "\".\"", "]", ")", "hw_infos", "=", "_GetHWIn...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
CleanClientVersions
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...
grr/server/grr_response_server/console_utils.py
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...
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", "excessive", "client", "versions", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L395-L438
[ "def", "CleanClientVersions", "(", "clients", "=", "None", ",", "dry_run", "=", "True", ",", "token", "=", "None", ")", ":", "if", "not", "clients", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", "token", "=", "token", ")", "clients", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
CleanVacuousVersions
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...
grr/server/grr_response_server/console_utils.py
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, ...
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, ...
[ "A", "script", "to", "remove", "no", "-", "op", "client", "versions", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L441-L488
[ "def", "CleanVacuousVersions", "(", "clients", "=", "None", ",", "dry_run", "=", "True", ")", ":", "if", "not", "clients", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", ")", "clients", "=", "index", ".", "LookupClients", "(", "[", "\".\...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ExportClientsByKeywords
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...
grr/server/grr_response_server/console_utils.py
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...
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...
[ "r", "A", "script", "to", "export", "clients", "summaries", "selected", "by", "a", "keyword", "search", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L491-L538
[ "def", "ExportClientsByKeywords", "(", "keywords", ",", "filename", ",", "token", "=", "None", ")", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", "token", "=", "token", ")", "client_list", "=", "index", ".", "LookupClients", "(", "keywords"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
StartFlowAndWorker
Launches the flow and worker and waits for it to finish. Args: client_id: The client common name we issue the request. flow_name: The name of the flow to launch. **kwargs: passthrough to flow. Returns: A flow session id. Note: you need raw access to run this flow as it requires running a wo...
grr/server/grr_response_server/console_utils.py
def StartFlowAndWorker(client_id, flow_name, **kwargs): """Launches the flow and worker and waits for it to finish. Args: client_id: The client common name we issue the request. flow_name: The name of the flow to launch. **kwargs: passthrough to flow. Returns: A flow session id. Note: you...
def StartFlowAndWorker(client_id, flow_name, **kwargs): """Launches the flow and worker and waits for it to finish. Args: client_id: The client common name we issue the request. flow_name: The name of the flow to launch. **kwargs: passthrough to flow. Returns: A flow session id. Note: you...
[ "Launches", "the", "flow", "and", "worker", "and", "waits", "for", "it", "to", "finish", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L541-L585
[ "def", "StartFlowAndWorker", "(", "client_id", ",", "flow_name", ",", "*", "*", "kwargs", ")", ":", "# Empty token, only works with raw access.", "queue", "=", "rdfvalue", ".", "RDFURN", "(", "\"DEBUG-%s-\"", "%", "getpass", ".", "getuser", "(", ")", ")", "if", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
WakeStuckFlow
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...
grr/server/grr_response_server/console_utils.py
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...
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...
[ "Wake", "up", "stuck", "flows", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/console_utils.py#L588-L627
[ "def", "WakeStuckFlow", "(", "session_id", ")", ":", "session_id", "=", "rdfvalue", ".", "SessionID", "(", "session_id", ")", "woken", "=", "0", "checked_pending", "=", "False", "with", "queue_manager", ".", "QueueManager", "(", ")", "as", "manager", ":", "f...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
StatsServer.Start
Start HTTPServer.
grr/server/grr_response_server/stats_server.py
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) ...
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) ...
[ "Start", "HTTPServer", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/stats_server.py#L38-L52
[ "def", "Start", "(", "self", ")", ":", "try", ":", "self", ".", "_http_server", "=", "http_server", ".", "HTTPServer", "(", "(", "\"\"", ",", "self", ".", "port", ")", ",", "StatsServerHandler", ")", "except", "socket", ".", "error", "as", "e", ":", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
StatsServerInit.RunOnce
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.
grr/server/grr_response_server/stats_server.py
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 ...
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 ...
[ "Main", "method", "of", "this", "registry", "hook", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/stats_server.py#L63-L107
[ "def", "RunOnce", "(", "self", ")", ":", "# Figure out which port to use.", "port", "=", "config", ".", "CONFIG", "[", "\"Monitoring.http_port\"", "]", "if", "not", "port", ":", "logging", ".", "info", "(", "\"Monitoring server disabled.\"", ")", "return", "# TODO...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
DebianPackagesStatusParser.Parse
Parse the status file.
grr/core/grr_response_core/lib/parsers/linux_software_parser.py
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...
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...
[ "Parse", "the", "status", "file", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/core/grr_response_core/lib/parsers/linux_software_parser.py#L31-L53
[ "def", "Parse", "(", "self", ",", "stat", ",", "file_object", ",", "knowledge_base", ")", ":", "_", ",", "_", "=", "stat", ",", "knowledge_base", "packages", "=", "[", "]", "sw_data", "=", "utils", ".", "ReadFileBytesAsUnicode", "(", "file_object", ")", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Process.Is64bit
Returns true if this is a 64 bit process.
grr/client/grr_response_client/windows/process.py
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("...
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("...
[ "Returns", "true", "if", "this", "is", "a", "64", "bit", "process", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/windows/process.py#L118-L127
[ "def", "Is64bit", "(", "self", ")", ":", "if", "\"64\"", "not", "in", "platform", ".", "machine", "(", ")", ":", "return", "False", "iswow64", "=", "ctypes", ".", "c_bool", "(", "False", ")", "if", "IsWow64Process", "is", "None", ":", "return", "False"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Process.Open
Opens the process for reading.
grr/client/grr_response_client/windows/process.py
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(): ...
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(): ...
[ "Opens", "the", "process", "for", "reading", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/windows/process.py#L129-L145
[ "def", "Open", "(", "self", ")", ":", "self", ".", "h_process", "=", "kernel32", ".", "OpenProcess", "(", "PROCESS_VM_READ", "|", "PROCESS_QUERY_INFORMATION", ",", "0", ",", "self", ".", "pid", ")", "if", "not", "self", ".", "h_process", ":", "raise", "p...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Process.ReadBytes
Reads at most num_bytes starting from offset <address>.
grr/client/grr_response_client/windows/process.py
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...
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...
[ "Reads", "at", "most", "num_bytes", "starting", "from", "offset", "<address", ">", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/windows/process.py#L195-L209
[ "def", "ReadBytes", "(", "self", ",", "address", ",", "num_bytes", ")", ":", "address", "=", "int", "(", "address", ")", "buf", "=", "ctypes", ".", "create_string_buffer", "(", "num_bytes", ")", "bytesread", "=", "ctypes", ".", "c_size_t", "(", "0", ")",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_MigrationFilenameToInt
Converts migration filename to a migration number.
grr/server/grr_response_server/databases/mysql_migration.py
def _MigrationFilenameToInt(fname): """Converts migration filename to a migration number.""" base, _ = os.path.splitext(fname) return int(base)
def _MigrationFilenameToInt(fname): """Converts migration filename to a migration number.""" base, _ = os.path.splitext(fname) return int(base)
[ "Converts", "migration", "filename", "to", "a", "migration", "number", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_migration.py#L28-L31
[ "def", "_MigrationFilenameToInt", "(", "fname", ")", ":", "base", ",", "_", "=", "os", ".", "path", ".", "splitext", "(", "fname", ")", "return", "int", "(", "base", ")" ]
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ListMigrationsToProcess
Lists filenames of migrations with numbers bigger than a given one.
grr/server/grr_response_server/databases/mysql_migration.py
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...
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...
[ "Lists", "filenames", "of", "migrations", "with", "numbers", "bigger", "than", "a", "given", "one", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_migration.py#L34-L44
[ "def", "ListMigrationsToProcess", "(", "migrations_root", ",", "current_migration_number", ")", ":", "migrations", "=", "[", "]", "for", "m", "in", "os", ".", "listdir", "(", "migrations_root", ")", ":", "if", "(", "current_migration_number", "is", "None", "or",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ProcessMigrations
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...
grr/server/grr_response_server/databases/mysql_migration.py
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...
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...
[ "Processes", "migrations", "from", "a", "given", "folder", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_migration.py#L47-L104
[ "def", "ProcessMigrations", "(", "open_conn_fn", ",", "migrations_root", ")", ":", "with", "contextlib", ".", "closing", "(", "open_conn_fn", "(", ")", ")", "as", "conn", ":", "conn", ".", "autocommit", "(", "True", ")", "with", "contextlib", ".", "closing",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
DumpCurrentSchema
Dumps current database schema.
grr/server/grr_response_server/databases/mysql_migration.py
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...
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...
[ "Dumps", "current", "database", "schema", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_migration.py#L107-L117
[ "def", "DumpCurrentSchema", "(", "cursor", ")", ":", "cursor", ".", "execute", "(", "\"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES \"", "\"WHERE table_schema = (SELECT DATABASE())\"", ")", "defs", "=", "[", "]", "for", "table", ",", "in", "sorted", "(", "cursor", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
FilterList
Filters a list, getting count elements, starting at offset.
grr/server/grr_response_server/gui/api_call_handler_utils.py
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 ...
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", "a", "list", "getting", "count", "elements", "starting", "at", "offset", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_handler_utils.py#L74-L99
[ "def", "FilterList", "(", "l", ",", "offset", ",", "count", "=", "0", ",", "filter_value", "=", "None", ")", ":", "if", "offset", "<", "0", ":", "raise", "ValueError", "(", "\"Offset needs to be greater than or equal to zero\"", ")", "if", "count", "<", "0",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
FilterCollection
Filters an aff4 collection, getting count elements, starting at offset.
grr/server/grr_response_server/gui/api_call_handler_utils.py
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...
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...
[ "Filters", "an", "aff4", "collection", "getting", "count", "elements", "starting", "at", "offset", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_handler_utils.py#L102-L127
[ "def", "FilterCollection", "(", "aff4_collection", ",", "offset", ",", "count", "=", "0", ",", "filter_value", "=", "None", ")", ":", "if", "offset", "<", "0", ":", "raise", "ValueError", "(", "\"Offset needs to be greater than or equal to zero\"", ")", "if", "c...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
get_config
Get INI parser with version.ini data.
api_client/python/setup.py
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...
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...
[ "Get", "INI", "parser", "with", "version", ".", "ini", "data", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/api_client/python/setup.py#L31-L42
[ "def", "get_config", "(", ")", ":", "# 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", "(", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
LinuxClientBuilder.CopyFiles
This sets up the template directory.
grr/client_builder/grr_response_client_builder/builders/linux.py
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,...
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,...
[ "This", "sets", "up", "the", "template", "directory", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/builders/linux.py#L70-L110
[ "def", "CopyFiles", "(", "self", ")", ":", "if", "self", ".", "fleetspeak_enabled", ":", "# Copy files needed for dpkg-buildpackage.", "shutil", ".", "copytree", "(", "config_lib", ".", "Resource", "(", ")", ".", "Filter", "(", "\"install_data/debian/dpkg_client/fleet...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
LinuxClientBuilder.MakeZip
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.
grr/client_builder/grr_response_client_builder/builders/linux.py
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) ...
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) ...
[ "Creates", "a", "ZIP", "archive", "of", "the", "files", "in", "the", "input", "directory", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/builders/linux.py#L112-L129
[ "def", "MakeZip", "(", "self", ",", "input_dir", ",", "output_file", ")", ":", "logging", ".", "info", "(", "\"Generating zip template file at %s\"", ",", "output_file", ")", "zf", "=", "zipfile", ".", "ZipFile", "(", "output_file", ",", "\"w\"", ")", "oldwd",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
CentosClientBuilder.CopyFiles
This sets up the template directory.
grr/client_builder/grr_response_client_builder/builders/linux.py
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"...
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"...
[ "This", "sets", "up", "the", "template", "directory", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client_builder/grr_response_client_builder/builders/linux.py#L135-L164
[ "def", "CopyFiles", "(", "self", ")", ":", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "self", ".", "package_dir", ",", "\"debian\"", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "package_dir", ",", "\"rpmbuild\"",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
SecurityCheck
A decorator applied to protected web handlers.
grr/server/grr_response_server/gui/webauth.py
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...
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...
[ "A", "decorator", "applied", "to", "protected", "web", "handlers", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L262-L271
[ "def", "SecurityCheck", "(", "func", ")", ":", "def", "Wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wrapping function.\"\"\"", "if", "WEBAUTH_MANAGER", "is", "None", ":", "raise", "RuntimeError", "(", "\"Attempt to init...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
IAPWebAuthManager.SecurityCheck
Wrapping function.
grr/server/grr_response_server/gui/webauth.py
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...
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", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L80-L94
[ "def", "SecurityCheck", "(", "self", ",", "func", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "IAP_HEADER", "not", "in", "request", ".", "headers", ":", "return", "werkzeug_wrappers", ".", "Response", "(", "\...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
BasicWebAuthManager.SecurityCheck
Wrapping function.
grr/server/grr_response_server/gui/webauth.py
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": ...
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": ...
[ "Wrapping", "function", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L100-L152
[ "def", "SecurityCheck", "(", "self", ",", "func", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", ".", "user", "=", "u\"\"", "authorized", "=", "False", "try", ":", "auth_type", ",", "authorization", "=", "request", ".",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
FirebaseWebAuthManager.SecurityCheck
Check if access should be allowed for the request.
grr/server/grr_response_server/gui/webauth.py
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...
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...
[ "Check", "if", "access", "should", "be", "allowed", "for", "the", "request", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L209-L237
[ "def", "SecurityCheck", "(", "self", ",", "func", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "auth_header", "=", "request", ".", "headers", ".", "get", "(", "\"Authorization\"", ",", "\"\"", ")", "if", "not", "au...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
NullWebAuthManager.SecurityCheck
A decorator applied to protected web handlers.
grr/server/grr_response_server/gui/webauth.py
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)
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)
[ "A", "decorator", "applied", "to", "protected", "web", "handlers", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L250-L255
[ "def", "SecurityCheck", "(", "self", ",", "func", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "request", ".", "user", "=", "self", ".", "username", "request", ".", "token", "=", "access_control", ".", "ACLToken", "(", "username...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
WebAuthInit.RunOnce
Run this once on init.
grr/server/grr_response_server/gui/webauth.py
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...
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...
[ "Run", "this", "once", "on", "init", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/webauth.py#L276-L285
[ "def", "RunOnce", "(", "self", ")", ":", "global", "WEBAUTH_MANAGER", "# pylint: disable=global-statement", "# pylint: disable=g-bad-name", "WEBAUTH_MANAGER", "=", "BaseWebAuthManager", ".", "GetPlugin", "(", "config", ".", "CONFIG", "[", "\"AdminUI.webauth_manager\"", "]",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
RouterMethodMetadata.GetQueryParamsNames
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 ...
grr/server/grr_response_server/gui/api_call_router.py
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...
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...
[ "This", "extracts", "all", "parameters", "from", "URL", "paths", "for", "logging", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_router.py#L127-L148
[ "def", "GetQueryParamsNames", "(", "self", ")", ":", "result", "=", "[", "]", "for", "unused_method", ",", "path", ",", "unused_params", "in", "self", ".", "http_methods", "or", "[", "]", ":", "for", "arg", "in", "re", ".", "findall", "(", "self", ".",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
ApiCallRouter.GetAnnotatedMethods
Returns a dictionary of annotated router methods.
grr/server/grr_response_server/gui/api_call_router.py
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...
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...
[ "Returns", "a", "dictionary", "of", "annotated", "router", "methods", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/gui/api_call_router.py#L174-L201
[ "def", "GetAnnotatedMethods", "(", "cls", ")", ":", "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", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Events.PublishEvent
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...
grr/server/grr_response_server/events.py
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...
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...
[ "Publish", "the", "message", "into", "all", "listeners", "of", "the", "event", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/events.py#L35-L51
[ "def", "PublishEvent", "(", "cls", ",", "event_name", ",", "msg", ",", "token", "=", "None", ")", ":", "cls", ".", "PublishMultipleEvents", "(", "{", "event_name", ":", "[", "msg", "]", "}", ",", "token", "=", "token", ")" ]
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Events.PublishMultipleEvents
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.
grr/server/grr_response_server/events.py
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 ...
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 ...
[ "Publishes", "multiple", "messages", "at", "once", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/events.py#L54-L76
[ "def", "PublishMultipleEvents", "(", "cls", ",", "events", ",", "token", "=", "None", ")", ":", "event_name_map", "=", "registry", ".", "EventRegistry", ".", "EVENT_NAME_MAP", "for", "event_name", ",", "messages", "in", "iteritems", "(", "events", ")", ":", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
Overlay
Adds hint attributes to a child hint if they are not defined.
grr/server/grr_response_server/check_lib/hints.py
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...
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...
[ "Adds", "hint", "attributes", "to", "a", "child", "hint", "if", "they", "are", "not", "defined", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/hints.py#L28-L37
[ "def", "Overlay", "(", "child", ",", "parent", ")", ":", "for", "arg", "in", "child", ",", "parent", ":", "if", "not", "isinstance", "(", "arg", ",", "collections", ".", "Mapping", ")", ":", "raise", "DefinitionError", "(", "\"Trying to merge badly defined h...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
RdfFormatter.FanOut
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...
grr/server/grr_response_server/check_lib/hints.py
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: ...
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: ...
[ "Expand", "values", "from", "various", "attribute", "types", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/hints.py#L45-L80
[ "def", "FanOut", "(", "self", ",", "obj", ",", "parent", "=", "None", ")", ":", "# Catch cases where RDFs are iterable but return themselves.", "if", "parent", "and", "obj", "==", "parent", ":", "results", "=", "[", "utils", ".", "SmartUnicode", "(", "obj", ")...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
RdfFormatter.Format
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...
grr/server/grr_response_server/check_lib/hints.py
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...
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...
[ "Apply", "string", "formatting", "templates", "to", "rdf", "data", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/check_lib/hints.py#L82-L111
[ "def", "Format", "(", "self", ",", "format_string", ",", "rdf", ")", ":", "result", "=", "[", "]", "for", "literal_text", ",", "field_name", ",", "_", ",", "_", "in", "self", ".", "parse", "(", "format_string", ")", ":", "# output the literal text", "if"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
VFSDirectory.Update
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...
grr/server/grr_response_server/aff4_objects/standard.py
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...
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...
[ "Refresh", "an", "old", "attribute", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L29-L62
[ "def", "Update", "(", "self", ",", "attribute", "=", "None", ")", ":", "# client id is the first path element", "client_id", "=", "self", ".", "urn", ".", "Split", "(", ")", "[", "0", "]", "if", "attribute", "==", "\"CONTAINS\"", ":", "# Get the pathspec for t...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
AFF4SparseImage._GetChunkForReading
Returns the relevant chunk from the datastore and reads ahead.
grr/server/grr_response_server/aff4_objects/standard.py
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...
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", "and", "reads", "ahead", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L154-L175
[ "def", "_GetChunkForReading", "(", "self", ",", "chunk", ")", ":", "try", ":", "return", "self", ".", "chunk_cache", ".", "Get", "(", "chunk", ")", "except", "KeyError", ":", "pass", "# We don't have this chunk already cached. The most common read", "# access pattern ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
AFF4SparseImage._GetChunkForWriting
Returns the relevant chunk from the datastore.
grr/server/grr_response_server/aff4_objects/standard.py
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...
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...
[ "Returns", "the", "relevant", "chunk", "from", "the", "datastore", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L177-L203
[ "def", "_GetChunkForWriting", "(", "self", ",", "chunk", ")", ":", "try", ":", "chunk", "=", "self", ".", "chunk_cache", ".", "Get", "(", "chunk", ")", "chunk", ".", "dirty", "=", "True", "return", "chunk", "except", "KeyError", ":", "pass", "try", ":"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
AFF4SparseImage._ReadPartial
Read as much as possible, but not more than length.
grr/server/grr_response_server/aff4_objects/standard.py
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...
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...
[ "Read", "as", "much", "as", "possible", "but", "not", "more", "than", "length", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L205-L225
[ "def", "_ReadPartial", "(", "self", ",", "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...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
AFF4SparseImage.AddBlob
Add another blob to this image using its hash.
grr/server/grr_response_server/aff4_objects/standard.py
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, ...
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, ...
[ "Add", "another", "blob", "to", "this", "image", "using", "its", "hash", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L266-L293
[ "def", "AddBlob", "(", "self", ",", "blob_hash", ",", "length", ",", "chunk_number", ")", ":", "if", "len", "(", "blob_hash", ".", "AsBytes", "(", ")", ")", "!=", "self", ".", "_HASH_SIZE", ":", "raise", "ValueError", "(", "\"Hash '%s' doesn't have correct l...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
AFF4SparseImage.ChunksExist
Do we have this chunk in the index?
grr/server/grr_response_server/aff4_objects/standard.py
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...
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...
[ "Do", "we", "have", "this", "chunk", "in", "the", "index?" ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L298-L310
[ "def", "ChunksExist", "(", "self", ",", "chunk_numbers", ")", ":", "index_urns", "=", "{", "self", ".", "urn", ".", "Add", "(", "self", ".", "CHUNK_ID_TEMPLATE", "%", "chunk_number", ")", ":", "chunk_number", "for", "chunk_number", "in", "chunk_numbers", "}"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
LabelSet.Flush
Flush the data to the index.
grr/server/grr_response_server/aff4_objects/standard.py
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...
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...
[ "Flush", "the", "data", "to", "the", "index", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/standard.py#L350-L360
[ "def", "Flush", "(", "self", ")", ":", "super", "(", "LabelSet", ",", "self", ")", ".", "Flush", "(", ")", "self", ".", "to_delete", "=", "self", ".", "to_delete", ".", "difference", "(", "self", ".", "to_set", ")", "with", "data_store", ".", "DB", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.WriteCronJob
Writes a cronjob to the database.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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)") ...
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)") ...
[ "Writes", "a", "cronjob", "to", "the", "database", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L22-L35
[ "def", "WriteCronJob", "(", "self", ",", "cronjob", ",", "cursor", "=", "None", ")", ":", "query", "=", "(", "\"INSERT INTO cron_jobs \"", "\"(job_id, job, create_time, enabled) \"", "\"VALUES (%s, %s, FROM_UNIXTIME(%s), %s) \"", "\"ON DUPLICATE KEY UPDATE \"", "\"enabled=VALUE...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin._CronJobFromRow
Creates a cronjob object from a database result row.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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...
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...
[ "Creates", "a", "cronjob", "object", "from", "a", "database", "result", "row", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L37-L53
[ "def", "_CronJobFromRow", "(", "self", ",", "row", ")", ":", "(", "job", ",", "create_time", ",", "enabled", ",", "forced_run_requested", ",", "last_run_status", ",", "last_run_time", ",", "current_run_id", ",", "state", ",", "leased_until", ",", "leased_by", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.ReadCronJobs
Reads all cronjobs from the database.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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...
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...
[ "Reads", "all", "cronjobs", "from", "the", "database", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L56-L77
[ "def", "ReadCronJobs", "(", "self", ",", "cronjob_ids", "=", "None", ",", "cursor", "=", "None", ")", ":", "query", "=", "(", "\"SELECT job, UNIX_TIMESTAMP(create_time), enabled, \"", "\"forced_run_requested, last_run_status, \"", "\"UNIX_TIMESTAMP(last_run_time), current_run_i...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.UpdateCronJob
Updates run information for an existing cron job.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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=...
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=...
[ "Updates", "run", "information", "for", "an", "existing", "cron", "job", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L101-L136
[ "def", "UpdateCronJob", "(", "self", ",", "cronjob_id", ",", "last_run_status", "=", "db", ".", "Database", ".", "unchanged", ",", "last_run_time", "=", "db", ".", "Database", ".", "unchanged", ",", "current_run_id", "=", "db", ".", "Database", ".", "unchang...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.LeaseCronJobs
Leases all available cron jobs.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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...
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...
[ "Leases", "all", "available", "cron", "jobs", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L139-L168
[ "def", "LeaseCronJobs", "(", "self", ",", "cronjob_ids", "=", "None", ",", "lease_time", "=", "None", ",", "cursor", "=", "None", ")", ":", "now", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "now_str", "=", "mysql_utils", ".", "RDFDatetime...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.ReturnLeasedCronJobs
Makes leased cron jobs available for leasing again.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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...
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...
[ "Makes", "leased", "cron", "jobs", "available", "for", "leasing", "again", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L171-L203
[ "def", "ReturnLeasedCronJobs", "(", "self", ",", "jobs", ",", "cursor", "=", "None", ")", ":", "if", "not", "jobs", ":", "return", "unleased_jobs", "=", "[", "]", "conditions", "=", "[", "]", "args", "=", "[", "]", "for", "job", "in", "jobs", ":", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.WriteCronJobRun
Stores a cron job run object in the database.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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(...
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(...
[ "Stores", "a", "cron", "job", "run", "object", "in", "the", "database", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L206-L225
[ "def", "WriteCronJobRun", "(", "self", ",", "run_object", ",", "cursor", "=", "None", ")", ":", "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=V...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.ReadCronJobRuns
Reads all cron job runs for a given job id.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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...
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", "all", "cron", "job", "runs", "for", "a", "given", "job", "id", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L234-L243
[ "def", "ReadCronJobRuns", "(", "self", ",", "job_id", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"\n SELECT run, UNIX_TIMESTAMP(write_time)\n FROM cron_job_runs\n WHERE job_id = %s\n \"\"\"", "cursor", ".", "execute", "(", "query", ",", "[", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.ReadCronJobRun
Reads a single cron job run from the db.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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)]...
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)]...
[ "Reads", "a", "single", "cron", "job", "run", "from", "the", "db", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L246-L256
[ "def", "ReadCronJobRun", "(", "self", ",", "job_id", ",", "run_id", ",", "cursor", "=", "None", ")", ":", "query", "=", "(", "\"SELECT run, UNIX_TIMESTAMP(write_time) FROM cron_job_runs \"", "\"WHERE job_id = %s AND run_id = %s\"", ")", "num_runs", "=", "cursor", ".", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBCronJobMixin.DeleteOldCronJobRuns
Deletes cron job runs that are older then the given timestamp.
grr/server/grr_response_server/databases/mysql_cronjobs.py
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)])
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)])
[ "Deletes", "cron", "job", "runs", "that", "are", "older", "then", "the", "given", "timestamp", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_cronjobs.py#L259-L263
[ "def", "DeleteOldCronJobRuns", "(", "self", ",", "cutoff_timestamp", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"DELETE FROM cron_job_runs WHERE write_time < FROM_UNIXTIME(%s)\"", "cursor", ".", "execute", "(", "query", ",", "[", "mysql_utils", ".", "RDFDat...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_Insert
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.
grr/server/grr_response_server/databases/mysql_blobs.py
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...
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...
[ "Inserts", "one", "or", "multiple", "rows", "into", "the", "given", "table", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L21-L50
[ "def", "_Insert", "(", "cursor", ",", "table", ",", "values", ")", ":", "precondition", ".", "AssertIterableType", "(", "values", ",", "dict", ")", "if", "not", "values", ":", "# Nothing can be INSERTed with empty `values` list.", "return", "column_names", "=", "l...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_BlobToChunks
Splits a Blob into chunks of size BLOB_CHUNK_SIZE.
grr/server/grr_response_server/databases/mysql_blobs.py
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...
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...
[ "Splits", "a", "Blob", "into", "chunks", "of", "size", "BLOB_CHUNK_SIZE", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L53-L64
[ "def", "_BlobToChunks", "(", "blob_id", ",", "blob", ")", ":", "# In case of empty blob (with empty range), use [0].", "chunk_begins", "=", "list", "(", "range", "(", "0", ",", "len", "(", "blob", ")", ",", "BLOB_CHUNK_SIZE", ")", ")", "or", "[", "0", "]", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_PartitionChunks
Groups chunks into partitions of size safe for a single INSERT.
grr/server/grr_response_server/databases/mysql_blobs.py
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...
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...
[ "Groups", "chunks", "into", "partitions", "of", "size", "safe", "for", "a", "single", "INSERT", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L67-L81
[ "def", "_PartitionChunks", "(", "chunks", ")", ":", "partitions", "=", "[", "[", "]", "]", "partition_size", "=", "0", "for", "chunk", "in", "chunks", ":", "cursize", "=", "len", "(", "chunk", "[", "\"blob_chunk\"", "]", ")", "if", "(", "cursize", "+",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBBlobsMixin.WriteBlobs
Writes given blobs.
grr/server/grr_response_server/databases/mysql_blobs.py
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)
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)
[ "Writes", "given", "blobs", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L88-L94
[ "def", "WriteBlobs", "(", "self", ",", "blob_id_data_map", ",", "cursor", "=", "None", ")", ":", "chunks", "=", "[", "]", "for", "blob_id", ",", "blob", "in", "iteritems", "(", "blob_id_data_map", ")", ":", "chunks", ".", "extend", "(", "_BlobToChunks", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBBlobsMixin.ReadBlobs
Reads given blobs.
grr/server/grr_response_server/databases/mysql_blobs.py
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( ...
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( ...
[ "Reads", "given", "blobs", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L97-L116
[ "def", "ReadBlobs", "(", "self", ",", "blob_ids", ",", "cursor", "=", "None", ")", ":", "if", "not", "blob_ids", ":", "return", "{", "}", "query", "=", "(", "\"SELECT blob_id, blob_chunk \"", "\"FROM blobs \"", "\"FORCE INDEX (PRIMARY) \"", "\"WHERE blob_id IN {} \"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBBlobsMixin.CheckBlobsExist
Checks if given blobs exist.
grr/server/grr_response_server/databases/mysql_blobs.py
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( ...
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( ...
[ "Checks", "if", "given", "blobs", "exist", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L119-L133
[ "def", "CheckBlobsExist", "(", "self", ",", "blob_ids", ",", "cursor", "=", "None", ")", ":", "if", "not", "blob_ids", ":", "return", "{", "}", "exists", "=", "{", "blob_id", ":", "False", "for", "blob_id", "in", "blob_ids", "}", "query", "=", "(", "...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBBlobsMixin.WriteHashBlobReferences
Writes blob references for a given set of hashes.
grr/server/grr_response_server/databases/mysql_blobs.py
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": ...
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": ...
[ "Writes", "blob", "references", "for", "a", "given", "set", "of", "hashes", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L136-L145
[ "def", "WriteHashBlobReferences", "(", "self", ",", "references_by_hash", ",", "cursor", ")", ":", "values", "=", "[", "]", "for", "hash_id", ",", "blob_refs", "in", "iteritems", "(", "references_by_hash", ")", ":", "refs", "=", "rdf_objects", ".", "BlobRefere...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MySQLDBBlobsMixin.ReadHashBlobReferences
Reads blob references of a given set of hashes.
grr/server/grr_response_server/databases/mysql_blobs.py
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...
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...
[ "Reads", "blob", "references", "of", "a", "given", "set", "of", "hashes", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mysql_blobs.py#L148-L158
[ "def", "ReadHashBlobReferences", "(", "self", ",", "hashes", ",", "cursor", ")", ":", "query", "=", "(", "\"SELECT hash_id, blob_references FROM hash_blob_references WHERE \"", "\"hash_id IN {}\"", ")", ".", "format", "(", "mysql_utils", ".", "Placeholders", "(", "len",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
BlobStore.WriteBlobsWithUnknownHashes
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.
grr/server/grr_response_server/blob_store.py
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...
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...
[ "Calculates", "hash", "ids", "and", "writes", "contents", "of", "given", "data", "blobs", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/blob_store.py#L26-L39
[ "def", "WriteBlobsWithUnknownHashes", "(", "self", ",", "blobs_data", ")", ":", "blobs_ids", "=", "[", "rdf_objects", ".", "BlobID", ".", "FromBlobData", "(", "d", ")", "for", "d", "in", "blobs_data", "]", "self", ".", "WriteBlobs", "(", "dict", "(", "zip"...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_GetClientIdFromQueue
Returns q's client id, if q is a client task queue, otherwise None. Args: q: rdfvalue.RDFURN Returns: string or None
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Returns", "q", "s", "client", "id", "if", "q", "is", "a", "client", "task", "queue", "otherwise", "None", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L45-L69
[ "def", "_GetClientIdFromQueue", "(", "q", ")", ":", "split", "=", "q", ".", "Split", "(", ")", "if", "not", "split", "or", "len", "(", "split", ")", "<", "2", ":", "return", "None", "# Normalize to lowercase.", "split", "=", "[", "s", ".", "lower", "...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.GetNotificationShard
Gets a single shard for a given queue.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Gets", "a", "single", "shard", "for", "a", "given", "queue", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L133-L144
[ "def", "GetNotificationShard", "(", "self", ",", "queue", ")", ":", "queue_name", "=", "str", "(", "queue", ")", "QueueManager", ".", "notification_shard_counters", ".", "setdefault", "(", "queue_name", ",", "0", ")", "QueueManager", ".", "notification_shard_count...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.Copy
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.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Return", "a", "copy", "of", "the", "queue", "manager", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L152-L163
[ "def", "Copy", "(", "self", ")", ":", "result", "=", "QueueManager", "(", "store", "=", "self", ".", "data_store", ",", "token", "=", "self", ".", "token", ")", "result", ".", "prev_frozen_timestamps", "=", "self", ".", "prev_frozen_timestamps", "result", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.FreezeTimestamp
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...
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Freezes", "the", "timestamp", "used", "for", "resolve", "/", "delete", "database", "queries", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L165-L175
[ "def", "FreezeTimestamp", "(", "self", ")", ":", "self", ".", "prev_frozen_timestamps", ".", "append", "(", "self", ".", "frozen_timestamp", ")", "self", ".", "frozen_timestamp", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")" ]
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.UnfreezeTimestamp
Unfreezes the timestamp used for resolve/delete database queries.
grr/server/grr_response_server/queue_manager.py
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()
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()
[ "Unfreezes", "the", "timestamp", "used", "for", "resolve", "/", "delete", "database", "queries", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L177-L181
[ "def", "UnfreezeTimestamp", "(", "self", ")", ":", "if", "not", "self", ".", "prev_frozen_timestamps", ":", "raise", "RuntimeError", "(", "\"Unbalanced UnfreezeTimestamp call.\"", ")", "self", ".", "frozen_timestamp", "=", "self", ".", "prev_frozen_timestamps", ".", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.FetchCompletedRequests
Fetch all the requests with a status message queued for them.
grr/server/grr_response_server/queue_manager.py
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...
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", "all", "the", "requests", "with", "a", "status", "message", "queued", "for", "them", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L202-L209
[ "def", "FetchCompletedRequests", "(", "self", ",", "session_id", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "(", "0", ",", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "No...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.FetchCompletedResponses
Fetch only completed requests and responses up to a limit.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Fetch", "only", "completed", "requests", "and", "responses", "up", "to", "a", "limit", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L211-L245
[ "def", "FetchCompletedResponses", "(", "self", ",", "session_id", ",", "timestamp", "=", "None", ",", "limit", "=", "10000", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "(", "0", ",", "self", ".", "frozen_timestamp", "or", "rdfvalue",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.FetchRequestsAndResponses
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 ...
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Fetches", "all", "outstanding", "requests", "and", "responses", "for", "this", "flow", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L247-L279
[ "def", "FetchRequestsAndResponses", "(", "self", ",", "session_id", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "(", "0", ",", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.DeleteRequest
Deletes the request and all its responses from the flow state queue.
grr/server/grr_response_server/queue_manager.py
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)
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", "the", "request", "and", "all", "its", "responses", "from", "the", "flow", "state", "queue", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L281-L288
[ "def", "DeleteRequest", "(", "self", ",", "request", ")", ":", "self", ".", "requests_to_delete", ".", "append", "(", "request", ")", "if", "request", "and", "request", ".", "HasField", "(", "\"request\"", ")", ":", "self", ".", "DeQueueClientRequest", "(", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.MultiDestroyFlowStates
Deletes all states in multiple flows and dequeues all client messages.
grr/server/grr_response_server/queue_manager.py
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")...
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")...
[ "Deletes", "all", "states", "in", "multiple", "flows", "and", "dequeues", "all", "client", "messages", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L294-L302
[ "def", "MultiDestroyFlowStates", "(", "self", ",", "session_ids", ")", ":", "deleted_requests", "=", "self", ".", "data_store", ".", "MultiDestroyFlowStates", "(", "session_ids", ",", "request_limit", "=", "self", ".", "request_limit", ")", "for", "request", "in",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.Flush
Writes the changes in this object to the datastore.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Writes", "the", "changes", "in", "this", "object", "to", "the", "datastore", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L304-L343
[ "def", "Flush", "(", "self", ")", ":", "self", ".", "data_store", ".", "StoreRequestsAndResponses", "(", "new_requests", "=", "self", ".", "request_queue", ",", "new_responses", "=", "self", ".", "response_queue", ",", "requests_to_delete", "=", "self", ".", "...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.QueueResponse
Queues the message on the flow's state.
grr/server/grr_response_server/queue_manager.py
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))
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", "the", "message", "on", "the", "flow", "s", "state", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L345-L349
[ "def", "QueueResponse", "(", "self", ",", "response", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "self", ".", "frozen_timestamp", "self", ".", "response_queue", ".", "append", "(", "(", "response", ",",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.QueueNotification
Queues a notification for a flow.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Queues", "a", "notification", "for", "a", "flow", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L363-L392
[ "def", "QueueNotification", "(", "self", ",", "notification", "=", "None", ",", "timestamp", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "notification", "is", "None", ":", "notification", "=", "rdf_flows", ".", "GrrNotification", "(", "*", "*", "kw...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.Delete
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...
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Removes", "the", "tasks", "from", "the", "queue", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L394-L413
[ "def", "Delete", "(", "self", ",", "queue", ",", "tasks", ",", "mutation_pool", "=", "None", ")", ":", "if", "queue", "is", "None", ":", "return", "if", "mutation_pool", "is", "None", ":", "raise", "ValueError", "(", "\"Mutation pool can't be none.\"", ")", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.Schedule
Schedule a set of Task() instances.
grr/server/grr_response_server/queue_manager.py
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) ...
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) ...
[ "Schedule", "a", "set", "of", "Task", "()", "instances", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L415-L432
[ "def", "Schedule", "(", "self", ",", "tasks", ",", "mutation_pool", ",", "timestamp", "=", "None", ")", ":", "non_fleetspeak_tasks", "=", "[", "]", "for", "queue", ",", "queued_tasks", "in", "iteritems", "(", "collection", ".", "Group", "(", "tasks", ",", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.GetNotifications
Returns all queue notifications.
grr/server/grr_response_server/queue_manager.py
def GetNotifications(self, queue): """Returns all queue notifications.""" queue_shard = self.GetNotificationShard(queue) return self._GetUnsortedNotifications(queue_shard).values()
def GetNotifications(self, queue): """Returns all queue notifications.""" queue_shard = self.GetNotificationShard(queue) return self._GetUnsortedNotifications(queue_shard).values()
[ "Returns", "all", "queue", "notifications", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L434-L437
[ "def", "GetNotifications", "(", "self", ",", "queue", ")", ":", "queue_shard", "=", "self", ".", "GetNotificationShard", "(", "queue", ")", "return", "self", ".", "_GetUnsortedNotifications", "(", "queue_shard", ")", ".", "values", "(", ")" ]
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.GetNotificationsForAllShards
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
grr/server/grr_response_server/queue_manager.py
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 ""...
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", "notifications", "for", "all", "shards", "of", "a", "queue", "at", "once", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L439-L455
[ "def", "GetNotificationsForAllShards", "(", "self", ",", "queue", ")", ":", "notifications_by_session_id", "=", "{", "}", "for", "queue_shard", "in", "self", ".", "GetAllNotificationShards", "(", "queue", ")", ":", "self", ".", "_GetUnsortedNotifications", "(", "q...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager._GetUnsortedNotifications
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.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Returns", "all", "the", "available", "notifications", "for", "a", "queue_shard", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L457-L492
[ "def", "_GetUnsortedNotifications", "(", "self", ",", "queue_shard", ",", "notifications_by_session_id", "=", "None", ")", ":", "if", "notifications_by_session_id", "is", "None", ":", "notifications_by_session_id", "=", "{", "}", "end_time", "=", "self", ".", "froze...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.NotifyQueue
This signals that there are new messages available in a queue.
grr/server/grr_response_server/queue_manager.py
def NotifyQueue(self, notification, **kwargs): """This signals that there are new messages available in a queue.""" self._MultiNotifyQueue(notification.session_id.Queue(), [notification], **kwargs)
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", "signals", "that", "there", "are", "new", "messages", "available", "in", "a", "queue", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L494-L497
[ "def", "NotifyQueue", "(", "self", ",", "notification", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_MultiNotifyQueue", "(", "notification", ".", "session_id", ".", "Queue", "(", ")", ",", "[", "notification", "]", ",", "*", "*", "kwargs", ")" ]
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.MultiNotifyQueue
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.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "This", "is", "the", "same", "as", "NotifyQueue", "but", "for", "several", "session_ids", "at", "once", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L499-L512
[ "def", "MultiNotifyQueue", "(", "self", ",", "notifications", ",", "mutation_pool", "=", "None", ")", ":", "extract_queue", "=", "lambda", "notification", ":", "notification", ".", "session_id", ".", "Queue", "(", ")", "for", "queue", ",", "notifications", "in...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager._MultiNotifyQueue
Does the actual queuing.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Does", "the", "actual", "queuing", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L514-L532
[ "def", "_MultiNotifyQueue", "(", "self", ",", "queue", ",", "notifications", ",", "mutation_pool", "=", "None", ")", ":", "notification_list", "=", "[", "]", "now", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "notification", "in", "no...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.DeleteNotifications
This deletes the notification when all messages have been processed.
grr/server/grr_response_server/queue_manager.py
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 ...
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 ...
[ "This", "deletes", "the", "notification", "when", "all", "messages", "have", "been", "processed", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L537-L558
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.Query
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. ...
grr/server/grr_response_server/queue_manager.py
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. ...
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. ...
[ "Retrieves", "tasks", "from", "a", "queue", "without", "leasing", "them", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L560-L578
[ "def", "Query", "(", "self", ",", "queue", ",", "limit", "=", "1", ")", ":", "# This function is usually used for manual testing so we also accept client", "# ids and get the queue from it.", "if", "isinstance", "(", "queue", ",", "rdf_client", ".", "ClientURN", ")", ":...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
QueueManager.QueryAndOwn
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.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Returns", "a", "list", "of", "Tasks", "leased", "for", "a", "certain", "time", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L580-L593
[ "def", "QueryAndOwn", "(", "self", ",", "queue", ",", "lease_seconds", "=", "10", ",", "limit", "=", "1", ")", ":", "with", "self", ".", "data_store", ".", "GetMutationPool", "(", ")", "as", "mutation_pool", ":", "return", "mutation_pool", ".", "QueueQuery...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
WellKnownQueueManager.FetchResponses
Retrieves responses for a well known flow. Args: session_id: The session_id to get the requests/responses for. Yields: The retrieved responses.
grr/server/grr_response_server/queue_manager.py
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...
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...
[ "Retrieves", "responses", "for", "a", "well", "known", "flow", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/queue_manager.py#L608-L621
[ "def", "FetchResponses", "(", "self", ",", "session_id", ")", ":", "timestamp", "=", "(", "0", ",", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", ")", "for", "response", "in", "self", ".", "data_store", ".",...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
_MigrateArtifact
Migrate one Artifact from AFF4 to REL_DB.
grr/server/grr_response_server/databases/migration.py
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...
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...
[ "Migrate", "one", "Artifact", "from", "AFF4", "to", "REL_DB", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/migration.py#L18-L27
[ "def", "_MigrateArtifact", "(", "artifact", ")", ":", "name", "=", "Text", "(", "artifact", ".", "name", ")", "try", ":", "logging", ".", "info", "(", "\"Migating %s\"", ",", "name", ")", "data_store", ".", "REL_DB", ".", "WriteArtifact", "(", "artifact", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
MigrateArtifacts
Migrates Artifacts from AFF4 to REL_DB.
grr/server/grr_response_server/databases/migration.py
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():...
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():...
[ "Migrates", "Artifacts", "from", "AFF4", "to", "REL_DB", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/migration.py#L34-L57
[ "def", "MigrateArtifacts", "(", ")", ":", "# First, delete all existing artifacts in REL_DB.", "artifacts", "=", "data_store", ".", "REL_DB", ".", "ReadAllArtifacts", "(", ")", "if", "artifacts", ":", "logging", ".", "info", "(", "\"Deleting %d artifacts from REL_DB.\"", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
HTTPManager._GetBaseURLs
Gathers a list of base URLs we will try.
grr/client/grr_response_client/comms.py
def _GetBaseURLs(self): """Gathers a list of base URLs we will try.""" result = config.CONFIG["Client.server_urls"] if not result: # Backwards compatibility - deduce server_urls from Client.control_urls. for control_url in config.CONFIG["Client.control_urls"]: result.append(posixpath.dir...
def _GetBaseURLs(self): """Gathers a list of base URLs we will try.""" result = config.CONFIG["Client.server_urls"] if not result: # Backwards compatibility - deduce server_urls from Client.control_urls. for control_url in config.CONFIG["Client.control_urls"]: result.append(posixpath.dir...
[ "Gathers", "a", "list", "of", "base", "URLs", "we", "will", "try", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L158-L171
[ "def", "_GetBaseURLs", "(", "self", ")", ":", "result", "=", "config", ".", "CONFIG", "[", "\"Client.server_urls\"", "]", "if", "not", "result", ":", "# Backwards compatibility - deduce server_urls from Client.control_urls.", "for", "control_url", "in", "config", ".", ...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
HTTPManager._GetProxies
Gather a list of proxies to use.
grr/client/grr_response_client/comms.py
def _GetProxies(self): """Gather a list of proxies to use.""" # Detect proxies from the OS environment. result = client_utils.FindProxies() # Also try to connect directly if all proxies fail. result.append("") # Also try all proxies configured in the config system. result.extend(config.CON...
def _GetProxies(self): """Gather a list of proxies to use.""" # Detect proxies from the OS environment. result = client_utils.FindProxies() # Also try to connect directly if all proxies fail. result.append("") # Also try all proxies configured in the config system. result.extend(config.CON...
[ "Gather", "a", "list", "of", "proxies", "to", "use", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L173-L184
[ "def", "_GetProxies", "(", "self", ")", ":", "# Detect proxies from the OS environment.", "result", "=", "client_utils", ".", "FindProxies", "(", ")", "# Also try to connect directly if all proxies fail.", "result", ".", "append", "(", "\"\"", ")", "# Also try all proxies c...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74
train
HTTPManager.OpenServerEndpoint
Search through all the base URLs to connect to one that works. This is a thin wrapper around requests.request() so most parameters are documented there. Args: path: The URL path to access in this endpoint. verify_cb: A callback which should return True if the response is reasonable. Th...
grr/client/grr_response_client/comms.py
def OpenServerEndpoint(self, path, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): """Search thr...
def OpenServerEndpoint(self, path, verify_cb=lambda x: True, data=None, params=None, headers=None, method="GET", timeout=None): """Search thr...
[ "Search", "through", "all", "the", "base", "URLs", "to", "connect", "to", "one", "that", "works", "." ]
google/grr
python
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/comms.py#L195-L255
[ "def", "OpenServerEndpoint", "(", "self", ",", "path", ",", "verify_cb", "=", "lambda", "x", ":", "True", ",", "data", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "method", "=", "\"GET\"", ",", "timeout", "=", "None", "...
5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74