text stringlengths 81 112k |
|---|
Unload a kext by forking into kextunload.
def LegacyKextunload(self, cf_bundle_identifier):
"""Unload a kext by forking into kextunload."""
error_code = OS_SUCCESS
bundle_identifier = self.CFStringToPystring(cf_bundle_identifier)
try:
subprocess.check_call(['/sbin/kextunload', '-b', bundle_identi... |
Retrieves a path info record for a given path.
def ReadPathInfo(self,
client_id,
path_type,
components,
timestamp=None,
cursor=None):
"""Retrieves a path info record for a given path."""
if timestamp is None:
p... |
Retrieves path info records for given paths.
def ReadPathInfos(self, client_id, path_type, components_list, cursor=None):
"""Retrieves path info records for given paths."""
if not components_list:
return {}
path_ids = list(map(rdf_objects.PathID.FromComponents, components_list))
path_infos = {... |
Writes a collection of path_info records for a client.
def WritePathInfos(self, client_id, path_infos):
"""Writes a collection of path_info records for a client."""
try:
self._MultiWritePathInfos({client_id: path_infos})
except MySQLdb.IntegrityError as error:
raise db.UnknownClientError(client... |
Writes a collection of path info records for specified clients.
def MultiWritePathInfos(self, path_infos):
"""Writes a collection of path info records for specified clients."""
try:
self._MultiWritePathInfos(path_infos)
except MySQLdb.IntegrityError as error:
client_ids = list(iterkeys(path_inf... |
Writes a collection of path info records for specified clients.
def _MultiWritePathInfos(self, path_infos, connection=None):
"""Writes a collection of path info records for specified clients."""
query = ""
path_info_count = 0
path_info_values = []
parent_path_info_count = 0
parent_path_info_v... |
Lists path info records that correspond to descendants of given path.
def ListDescendentPathInfos(self,
client_id,
path_type,
components,
timestamp=None,
max_depth=None,... |
Reads a collection of hash and stat entries for given paths.
def ReadPathInfosHistories(self,
client_id,
path_type,
components_list,
cursor=None):
"""Reads a collection of hash and stat entries for g... |
Enumerate all interfaces and collect their MAC addresses.
def EnumerateInterfacesFromClient(args):
"""Enumerate all interfaces and collect their MAC addresses."""
del args # Unused
libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c"))
ifa = Ifaddrs()
p_ifa = ctypes.pointer(ifa)
libc.getifaddrs(ct... |
Enumerates all the users on this system.
def EnumerateUsersFromClient(args):
"""Enumerates all the users on this system."""
del args # Unused
users = _ParseWtmp()
for user, last_login in iteritems(users):
# Lose the null termination
username, _ = user.split(b"\x00", 1)
username = username.decod... |
Parses the currently mounted devices.
def CheckMounts(filename):
"""Parses the currently mounted devices."""
with io.open(filename, "r") as fd:
for line in fd:
try:
device, mnt_point, fs_type, _ = line.split(" ", 3)
except ValueError:
continue
if fs_type in ACCEPTABLE_FILESYST... |
List all the filesystems mounted on the system.
def EnumerateFilesystemsFromClient(args):
"""List all the filesystems mounted on the system."""
del args # Unused.
filenames = ["/proc/mounts", "/etc/mtab"]
for filename in filenames:
for device, fs_type, mnt_point in CheckMounts(filename):
yield rdf... |
Parse wtmp and utmp and extract the last logon time.
def _ParseWtmp():
"""Parse wtmp and utmp and extract the last logon time."""
users = {}
wtmp_struct_size = UtmpStruct.GetSize()
filenames = glob.glob("/var/log/wtmp*") + ["/var/run/utmp"]
for filename in filenames:
try:
wtmp = open(filename, "r... |
Client update for rpm based distros.
Upgrading rpms is a bit more tricky than upgrading deb packages since there
is a preinstall script that kills the running GRR daemon and, thus, also
the installer process. We need to make sure we detach the child process
properly and therefore cannot use client_util... |
Returns a default root path for storing temporary files.
def _TempRootPath():
"""Returns a default root path for storing temporary files."""
# `FLAGS.test_tmpdir` is defined only in test environment, so we can't expect
# for it to be always defined.
test_tmpdir = (
compatibility.Environ("TEST_TMPDIR", de... |
Creates a temporary directory based on the environment configuration.
The directory will be placed in folder as specified by the `TEST_TMPDIR`
environment variable if available or fallback to `Test.tmpdir` of the current
configuration if not.
Args:
suffix: A suffix to end the directory name with.
pref... |
Creates a temporary file based on the environment configuration.
If no directory is specified the file will be placed in folder as specified by
the `TEST_TMPDIR` environment variable if available or fallback to
`Test.tmpdir` of the current configuration if not.
If directory is specified it must be part of the... |
Return the best available name for this volume.
def Name(self):
"""Return the best available name for this volume."""
return (self.name or self.device_path or self.windowsvolume.drive_letter or
self.unixvolume.mount_point or None) |
Ensure the pathspec is valid.
def Validate(self):
"""Ensure the pathspec is valid."""
self.pathspec.Validate()
if (self.HasField("start_time") and self.HasField("end_time") and
self.start_time > self.end_time):
raise ValueError("Start time must be before end time.")
if not self.path_reg... |
Turn Exported* protos with embedded metadata into a nested dict.
def _GetNestedDict(self, value):
"""Turn Exported* protos with embedded metadata into a nested dict."""
row = {}
for type_info in value.__class__.type_infos:
# We only expect the metadata proto to be included as ProtoEmbedded.
if ... |
Creates a new gzipped output tempfile for the output type.
We write to JSON data to gzip_filehandle to get compressed data. We hold a
reference to the original filehandle (gzip_filehandle_parent) so we can pass
the gzip data to bigquery.
Args:
output_type: string of export type to be used in fil... |
Returns the tracker for a given value type.
def _GetTempOutputFileHandles(self, value_type):
"""Returns the tracker for a given value type."""
try:
return self.temp_output_trackers[value_type], False
except KeyError:
return self._CreateOutputFileHandles(value_type), True |
Finish writing JSON files, upload to cloudstorage and bigquery.
def Flush(self, state):
"""Finish writing JSON files, upload to cloudstorage and bigquery."""
self.bigquery = bigquery.GetBigQueryClient()
# BigQuery job ids must be alphanum plus dash and underscore.
urn_str = self.source_urn.RelativeName... |
Convert Exported* rdfvalue into a BigQuery schema.
def RDFValueToBigQuerySchema(self, value):
"""Convert Exported* rdfvalue into a BigQuery schema."""
fields_array = []
for type_info in value.__class__.type_infos:
# Nested structures are indicated by setting type "RECORD"
if type_info.__class__... |
Write newline separated JSON dicts for each value.
We write each dict separately so we don't have to hold all of the output
streams in memory. We open and close the JSON array manually with [].
Args:
state: rdf_protodict.AttributedDict with the plugin's state.
values: RDF values to export.
de... |
Assign kwargs to the protobuf, and remove them from the kwargs dict.
def FilterArgsFromSemanticProtobuf(protobuf, kwargs):
"""Assign kwargs to the protobuf, and remove them from the kwargs dict."""
for descriptor in protobuf.type_infos:
value = kwargs.pop(descriptor.name, None)
if value is not None:
... |
Initializes state for a list of output plugins.
def GetOutputPluginStates(output_plugins, source=None, token=None):
"""Initializes state for a list of output plugins."""
output_plugins_states = []
for plugin_descriptor in output_plugins:
plugin_class = plugin_descriptor.GetPluginClass()
try:
_, plu... |
The main factory function for creating and executing a new flow.
Args:
args: An arg protocol buffer which is an instance of the required flow's
args_type class attribute.
runner_args: an instance of FlowRunnerArgs() protocol buffer which is used
to initialize the runner for this flow.
parent_... |
The main factory function for creating and executing a new flow.
Args:
client_id: ID of the client this flow should run on.
cpu_limit: CPU limit in seconds for this flow.
creator: Username that requested this flow.
flow_args: An arg protocol buffer which is an instance of the required
flow's ar... |
Flushes the flow/hunt and all its requests to the data_store.
def Flush(self):
"""Flushes the flow/hunt and all its requests to the data_store."""
self._CheckLeaseAndFlush()
self.Load()
super(FlowBase, self).Flush()
# Writing the messages queued in the queue_manager of the runner always has
# t... |
Flushes the flow and all its requests to the data_store.
def Close(self):
"""Flushes the flow and all its requests to the data_store."""
self._CheckLeaseAndFlush()
super(FlowBase, self).Close()
# Writing the messages queued in the queue_manager of the runner always has
# to be the last thing that h... |
The initialization method.
def Initialize(self):
"""The initialization method."""
super(GRRFlow, self).Initialize()
self._client_version = None
self._client_os = None
self._client_knowledge_base = None
if "r" in self.mode:
state = self.Get(self.Schema.FLOW_STATE_DICT)
self.context ... |
Make a new runner.
def CreateRunner(self, **kw):
"""Make a new runner."""
self.runner = flow_runner.FlowRunner(self, token=self.token, **kw)
return self.runner |
Send out a final notification about the end of this flow.
def NotifyAboutEnd(self):
"""Send out a final notification about the end of this flow."""
flow_ref = None
if self.runner_args.client_id:
flow_ref = rdf_objects.FlowReference(
client_id=self.client_id, flow_id=self.urn.Basename())
... |
Mark the flow for termination as soon as any of its states are called.
def MarkForTermination(cls, flow_urn, reason=None, mutation_pool=None):
"""Mark the flow for termination as soon as any of its states are called."""
# Doing a blind write here using low-level data store API. Accessing
# the flow via AFF... |
Terminate a flow.
Args:
flow_id: The flow session_id to terminate.
reason: A reason to log.
status: Status code used in the generated status message.
token: The access token to be used for this request.
Raises:
FlowError: If the flow can not be found.
def TerminateAFF4Flow(cls, ... |
Returns the ResultCollection for the flow with a given flow_id.
Args:
flow_id: The id of the flow, a RDFURN of the form aff4:/flows/F:123456.
Returns:
The collection containing the results for the flow identified by the id.
def ResultCollectionForFID(cls, flow_id):
"""Returns the ResultCollec... |
Get instances of all well known flows.
def GetAllWellKnownFlows(cls, token=None):
"""Get instances of all well known flows."""
well_known_flows = {}
for cls in itervalues(registry.AFF4FlowRegistry.FLOW_REGISTRY):
if issubclass(cls, WellKnownFlow) and cls.well_known_session_id:
well_known_flow... |
Removes WellKnownFlow messages from the queue and returns them.
def FetchAndRemoveRequestsAndResponses(self, session_id):
"""Removes WellKnownFlow messages from the queue and returns them."""
messages = []
with queue_manager.WellKnownQueueManager(token=self.token) as manager:
for response in manager.... |
For WellKnownFlows we receive these messages directly.
def ProcessResponses(self, responses, thread_pool):
"""For WellKnownFlows we receive these messages directly."""
for response in responses:
thread_pool.AddTask(
target=self._SafeProcessMessage,
args=(response,),
name=sel... |
Returns the IP as an `IPAddress` object (if packed bytes are defined).
def AsIPAddr(self):
"""Returns the IP as an `IPAddress` object (if packed bytes are defined)."""
if self.packed_bytes is None:
return None
packed_bytes = self.packed_bytes.AsBytes()
if self.address_type == NetworkAddress.Fam... |
Return a list of IP addresses.
def GetIPAddresses(self):
"""Return a list of IP addresses."""
results = []
for address in self.addresses:
human_readable_address = address.human_readable_address
if human_readable_address is not None:
results.append(human_readable_address)
return res... |
Checks all `content_conditions` until one yields no matches.
def _CheckConditionsShortCircuit(content_conditions, pathspec):
"""Checks all `content_conditions` until one yields no matches."""
matches = []
for cond in content_conditions:
with vfs.VFSOpen(pathspec) as vfs_file:
cur_matches = list(cond.Se... |
Yields all possible expansions from given path patterns.
def _GetExpandedPaths(args):
"""Yields all possible expansions from given path patterns."""
opts = globbing.PathOpts(
follow_links=args.follow_links, pathtype=args.pathtype)
for path in args.paths:
for expanded_path in globbing.ExpandPath(str(pa... |
This function expands paths from the args and returns registry keys.
Args:
args: An `rdf_file_finder.FileFinderArgs` object.
Yields:
`rdf_client_fs.StatEntry` instances.
def RegistryKeyFromClient(args):
"""This function expands paths from the args and returns registry keys.
Args:
args: An `rdf_f... |
Returns last known GRR version that the client used.
def GetClientVersion(client_id, token=None):
"""Returns last known GRR version that the client used."""
if data_store.RelationalDBEnabled():
sinfo = data_store.REL_DB.ReadClientStartupInfo(client_id=client_id)
if sinfo is not None:
return sinfo.cli... |
Returns last known operating system name that the client used.
def GetClientOs(client_id, token=None):
"""Returns last known operating system name that the client used."""
if data_store.RelationalDBEnabled():
kb = data_store.REL_DB.ReadClientSnapshot(client_id).knowledge_base
else:
with aff4.FACTORY.Open... |
Returns an `rdf_crypto.Hash` instance for given AFF4 file descriptor.
def GetFileHashEntry(fd):
"""Returns an `rdf_crypto.Hash` instance for given AFF4 file descriptor."""
# Hash file store is not migrated to RELDB just yet, hence the first check.
if (not fd.urn.Path().startswith("/files/hash/generic") and
... |
Returns an `rdf_crypto.Hash` instance for given URN of an AFF4 file.
def GetUrnHashEntry(urn, token=None):
"""Returns an `rdf_crypto.Hash` instance for given URN of an AFF4 file."""
if data_store.RelationalDBEnabled():
client_id, vfs_path = urn.Split(2)
path_type, components = rdf_objects.ParseCategorizedP... |
Enumerate all modules which match the patterns MODULE_PATTERNS.
PyInstaller often fails to locate all dlls which are required at
runtime. We import all the client modules here, we simply introspect
all the modules we have loaded in our current running process, and
all the ones matching the patterns are copied ... |
Read a file from a ZipFile and write it to a new ZipFile.
def CopyFileInZip(from_zip, from_name, to_zip, to_name=None):
"""Read a file from a ZipFile and write it to a new ZipFile."""
data = from_zip.read(from_name)
if to_name is None:
to_name = from_name
to_zip.writestr(to_name, data) |
Use VS2010 to build the windows Nanny service.
def BuildNanny(self):
"""Use VS2010 to build the windows Nanny service."""
# When running under cygwin, the following environment variables are not set
# (since they contain invalid chars). Visual Studio requires these or it
# will fail.
os.environ["Pr... |
Windows templates also include the nanny.
def MakeExecutableTemplate(self, output_file=None):
"""Windows templates also include the nanny."""
super(WindowsClientBuilder,
self).MakeExecutableTemplate(output_file=output_file)
self.MakeBuildDirectory()
self.BuildWithPyInstaller()
# Get any... |
Check password with legacy crypt based method.
def _CheckLegacyPassword(self, password):
"""Check password with legacy crypt based method."""
# This import will fail on Windows.
import crypt # pylint: disable=g-import-not-at-top
salt = self._value[:2]
return crypt.crypt(password, salt) == self._va... |
Send an AFF4-based notification to the user in the UI.
Args:
message_type: One of aff4_grr.Notification.notification_types e.g.
"ViewObject", "HostInformation", "GrantAccess" or
the same with an added ":[new-style notification type] suffix, e.g.
"ViewObject:TYPE_CLIENT_INTERROGATED".
... |
Deletes the pending notification with the given timestamp.
Args:
timestamp: The timestamp of the notification. Assumed to be unique.
Raises:
UniqueKeyError: Raised if multiple notifications have the timestamp.
def DeletePendingNotification(self, timestamp):
"""Deletes the pending notification... |
A generator of current notifications.
def ShowNotifications(self, reset=True):
"""A generator of current notifications."""
shown_notifications = self.Schema.SHOWN_NOTIFICATIONS()
# Pending notifications first
pending = self.Get(self.Schema.PENDING_NOTIFICATIONS, [])
for notification in pending:
... |
Return a description of this user.
def Describe(self):
"""Return a description of this user."""
result = ["\nUsername: %s" % self.urn.Basename()]
labels = [l.name for l in self.GetLabels()]
result.append("Labels: %s" % ",".join(labels))
if self.Get(self.Schema.PASSWORD) is None:
result.appen... |
Gets the metric value corresponding to the given field values.
def Get(self, fields=None):
"""Gets the metric value corresponding to the given field values."""
if not self._field_defs and fields:
raise ValueError("Metric was registered without fields, "
"but following fields were p... |
Increments counter value by a given delta.
def Increment(self, delta, fields=None):
"""Increments counter value by a given delta."""
if delta < 0:
raise ValueError(
"Counter increment should not be < 0 (received: %d)" % delta)
self._metric_values[_FieldsToKey(fields)] = self.Get(fields=fie... |
Records the given observation in a distribution.
def Record(self, value, fields=None):
"""Records the given observation in a distribution."""
key = _FieldsToKey(fields)
metric_value = self._metric_values.get(key)
if metric_value is None:
metric_value = self._DefaultValue()
self._metric_valu... |
Sets the metric's current value.
def Set(self, value, fields=None):
"""Sets the metric's current value."""
self._metric_values[_FieldsToKey(fields)] = self._value_type(value) |
Returns current metric's value (executing a callback if needed).
def Get(self, fields=None):
"""Returns current metric's value (executing a callback if needed)."""
result = super(_GaugeMetric, self).Get(fields=fields)
if callable(result):
return result()
else:
return result |
See base class.
def _InitializeMetric(self, metadata):
"""See base class."""
field_defs = stats_utils.FieldDefinitionTuplesFromProtos(
metadata.fields_defs)
if metadata.metric_type == rdf_stats.MetricMetadata.MetricType.COUNTER:
self._counter_metrics[metadata.varname] = _CounterMetric(field_d... |
See base class.
def IncrementCounter(self, metric_name, delta=1, fields=None):
"""See base class."""
if delta < 0:
raise ValueError("Invalid increment for counter: %d." % delta)
self._counter_metrics[metric_name].Increment(delta, fields) |
See base class.
def RecordEvent(self, metric_name, value, fields=None):
"""See base class."""
self._event_metrics[metric_name].Record(value, fields) |
See base class.
def SetGaugeValue(self, metric_name, value, fields=None):
"""See base class."""
self._gauge_metrics[metric_name].Set(value, fields) |
See base class.
def SetGaugeCallback(self, metric_name, callback, fields=None):
"""See base class."""
self._gauge_metrics[metric_name].SetCallback(callback, fields) |
Fetches the metric object corresponding to the given name.
def _GetMetric(self, metric_name):
"""Fetches the metric object corresponding to the given name."""
if metric_name in self._counter_metrics:
return self._counter_metrics[metric_name]
elif metric_name in self._event_metrics:
return self.... |
Parse the yum output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the yum output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
packages = []
for line in stdout.decode("utf-8").splitlines()[1... |
Parse the yum repolist output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the yum repolist output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
output = iter(stdout.decode("utf-8").splitlines()... |
Parse the rpm -qa output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the rpm -qa output."""
_ = time_taken, args, knowledge_base # Unused.
rpm_re = re.compile(r"^(\w[-\w\+]+?)-(\d.*)$")
self.CheckReturn(cmd, return_val)
packages = []
... |
Parse the dpkg output.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the dpkg output."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(cmd, return_val)
column_lengths = []
i = 0
for i, line in enumerate(stdout... |
Parse the dmidecode output. All data is parsed into a dictionary.
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
knowledge_base):
"""Parse the dmidecode output. All data is parsed into a dictionary."""
_ = stderr, time_taken, args, knowledge_base # Unused.
self.CheckReturn(... |
Parse the ps output.
Note that cmdline consumes every field up to the end of line
and as it is string, we can't perfectly see what the arguments
on the command line really were. We just assume a space is the arg
seperator. It's imperfect, but it's better than nothing.
Obviously, if cmd/cmdline is s... |
Validates an IAP JWT for your (Compute|Container) Engine service.
Args:
iap_jwt: The contents of the X-Goog-IAP-JWT-Assertion header.
cloud_project_number: The project *number* for your Google Cloud project.
This is returned by 'gcloud projects describe $PROJECT_ID', or in the
Project Info card i... |
Validates an IAP JWT.
def ValidateIapJwt(iap_jwt, expected_audience):
"""Validates an IAP JWT."""
try:
key_id = jwt.get_unverified_header(iap_jwt).get("kid")
if not key_id:
raise IAPValidationFailedError("No key ID")
key = GetIapKey(key_id)
decoded_jwt = jwt.decode(
iap_jwt, key, alg... |
Retrieves a public key from the list published by Identity-Aware Proxy.
The key file is re-fetched if necessary.
Args:
key_id: Key id.
Returns:
String with a key.
Raises:
KeyNotFoundError: if the key is not found in the key file.
KeysCanNotBeFetchedError: if the key file can't be fetched.
d... |
Inits an GRR API object with a HTTP connector.
def InitHttp(api_endpoint=None,
page_size=None,
auth=None,
proxies=None,
verify=None,
cert=None,
trust_env=True):
"""Inits an GRR API object with a HTTP connector."""
connector = http_conne... |
Changes interface to a staticly set IP.
Sets IP configs to local if no paramaters passed.
Args:
interface: Name of the interface.
ip: IP address.
subnet: Subnet mask.
gw: IP address of the default gateway.
Returns:
A tuple of stdout, stderr, exit_status.
def NetshStaticIp(interface,
... |
Tries to disable an interface. Only works on Vista and 7.
Args:
interface: Name of the interface to disable.
Returns:
res which is a tuple of (stdout, stderr, exit_status, time_taken).
def DisableInterfaces(interface):
"""Tries to disable an interface. Only works on Vista and 7.
Args:
interfac... |
Gives a list of enabled interfaces. Should work on all windows versions.
Returns:
interfaces: Names of interfaces found enabled.
def GetEnabledInterfaces():
"""Gives a list of enabled interfaces. Should work on all windows versions.
Returns:
interfaces: Names of interfaces found enabled.
"""
interf... |
Sends a message to a user.
Args:
msg: Message to be displaied to user.
Returns:
res which is a tuple of (stdout, stderr, exit_status, time_taken).
def MsgUser(msg):
"""Sends a message to a user.
Args:
msg: Message to be displaied to user.
Returns:
res which is a tuple of (stdout, stderr, ... |
Apply build.yaml settings from the template.
def GetConfigFromTemplate(self, template_path):
"""Apply build.yaml settings from the template."""
with zipfile.ZipFile(template_path) as template_zip:
build_yaml = None
for name in template_zip.namelist():
if name.endswith("build.yaml"):
... |
Get the appropriate client deployer based on the selected flags.
def GetRepacker(self, context, signer=None):
"""Get the appropriate client deployer based on the selected flags."""
if "Target:Darwin" in context:
deployer_class = build.DarwinClientRepacker
elif "Target:Windows" in context:
deplo... |
Repack binaries based on the configuration.
We repack all templates in the templates directory. We expect to find only
functioning templates, all other files should be removed. Each template
contains a build.yaml that specifies how it was built and how it should be
repacked.
Args:
template_p... |
Repack all the templates in ClientBuilder.template_dir.
def RepackAllTemplates(self, upload=False, token=None):
"""Repack all the templates in ClientBuilder.template_dir."""
for template in os.listdir(config.CONFIG["ClientBuilder.template_dir"]):
template_path = os.path.join(config.CONFIG["ClientBuilder.... |
Build metadata requests list from collection maps.
def _MakeArgs(amazon_collection_map, google_collection_map):
"""Build metadata requests list from collection maps."""
request_list = []
for url, label in iteritems(amazon_collection_map):
request_list.append(
CloudMetadataRequest(
bios_ve... |
Make the google unique ID of zone/project/id.
def MakeGoogleUniqueID(cloud_instance):
"""Make the google unique ID of zone/project/id."""
if not (cloud_instance.zone and cloud_instance.project_id and
cloud_instance.instance_id):
raise ValueError("Bad zone/project_id/id: '%s/%s/%s'" %
... |
Build the standard set of cloud metadata to collect during interrogate.
def BuildCloudMetadataRequests():
"""Build the standard set of cloud metadata to collect during interrogate."""
amazon_collection_map = {
"/".join((AMAZON_URL_BASE, "instance-id")): "instance_id",
"/".join((AMAZON_URL_BASE, "ami-id... |
Convert CloudMetadataResponses to CloudInstance proto.
Ideally we'd just get the client to fill out a CloudInstance proto, but we
need to keep the flexibility of collecting new metadata and creating new
fields without a client push. So instead we bring back essentially a dict of
results and fill the proto on t... |
Records given value.
def Record(self, value):
"""Records given value."""
self.sum += value
self.count += 1
pos = bisect.bisect(self.bins, value) - 1
if pos < 0:
pos = 0
elif pos == len(self.bins):
pos = len(self.bins) - 1
self.heights[pos] += 1 |
Puts a given value into an appropriate bin.
def RegisterValue(self, value):
"""Puts a given value into an appropriate bin."""
if self.bins:
for b in self.bins:
if b.range_max_value > value:
b.num += 1
return
self.bins[-1].num += 1 |
Update stats with info about resources consumed by a single client.
def RegisterResources(self, client_resources):
"""Update stats with info about resources consumed by a single client."""
self.user_cpu_stats.RegisterValue(client_resources.cpu_usage.user_cpu_time)
self.system_cpu_stats.RegisterValue(
... |
Extracts and returns the serialized object.
def payload(self):
"""Extracts and returns the serialized object."""
try:
rdf_cls = self.classes.get(self.name)
if rdf_cls:
value = rdf_cls.FromSerializedString(self.data)
value.age = self.embedded_age
return value
except Type... |
Receives a value and fills it into a DataBlob.
Args:
value: value to set
raise_on_error: if True, raise if we can't serialize. If False, set the
key to an error string.
Returns:
self
Raises:
TypeError: if the value can't be serialized and raise_on_error is True
def SetVal... |
Extracts and returns a single value from a DataBlob.
def GetValue(self, ignore_error=True):
"""Extracts and returns a single value from a DataBlob."""
if self.HasField("none"):
return None
field_names = [
"integer", "string", "data", "boolean", "list", "dict", "rdf_value",
"float", "... |
Add another member to the array.
Args:
value: The new data to append to the array.
**kwarg: Create a new element from these keywords.
Returns:
The value which was added. This can be modified further by the caller and
changes will be propagated here.
Raises:
ValueError: If t... |
Constructs a single sample that best represents a list of samples.
Args:
samples: An iterable collection of `CpuSample` instances.
Returns:
A `CpuSample` instance representing `samples`.
Raises:
ValueError: If `samples` is empty.
def FromMany(cls, samples):
"""Constructs a single s... |
Constructs a single sample that best represents a list of samples.
Args:
samples: An iterable collection of `IOSample` instances.
Returns:
An `IOSample` instance representing `samples`.
Raises:
ValueError: If `samples` is empty.
def FromMany(cls, samples):
"""Constructs a single sa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.