INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Print exceptions raised by subscribers to stderr. | def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print... |
Set up the kubernetes_state instance so it can be used in OpenMetricsBaseCheck | def _create_kubernetes_state_prometheus_instance(self, instance):
"""
Set up the kubernetes_state instance so it can be used in OpenMetricsBaseCheck
"""
ksm_instance = deepcopy(instance)
endpoint = instance.get('kube_state_url')
if endpoint is None:
raise Chec... |
Some metrics contains conditions, labels that have "condition" as name and "true", "false", or "unknown"
as value. The metric value is expected to be a gauge equal to 0 or 1 in this case.
For example:
metric {
label { name: "condition", value: "true"
}
# other labe... | def _condition_to_service_check(self, sample, sc_name, mapping, tags=None):
"""
Some metrics contains conditions, labels that have "condition" as name and "true", "false", or "unknown"
as value. The metric value is expected to be a gauge equal to 0 or 1 in this case.
For example:
... |
Metrics from kube-state-metrics have changed
For example:
kube_node_status_condition{condition="Ready",node="ip-172-33-39-189.eu-west-1.compute",status="true"} 1
kube_node_status_condition{condition="OutOfDisk",node="ip-172-33-57-130.eu-west-1.compute",status="false"} 1
metric {
... | def _condition_to_tag_check(self, sample, base_sc_name, mapping, scraper_config, tags=None):
"""
Metrics from kube-state-metrics have changed
For example:
kube_node_status_condition{condition="Ready",node="ip-172-33-39-189.eu-west-1.compute",status="true"} 1
kube_node_status_cond... |
Lookups the labels_mapper table to see if replacing the tag name is
necessary, then returns a "name:value" tag string | def _format_tag(self, name, value, scraper_config):
"""
Lookups the labels_mapper table to see if replacing the tag name is
necessary, then returns a "name:value" tag string
"""
return '%s:%s' % (scraper_config['labels_mapper'].get(name, name), value) |
Search for `name` in labels name and returns corresponding tag string.
Tag name is label name if not specified.
Returns None if name was not found. | def _label_to_tag(self, name, labels, scraper_config, tag_name=None):
"""
Search for `name` in labels name and returns corresponding tag string.
Tag name is label name if not specified.
Returns None if name was not found.
"""
value = labels.get(name)
if value:
... |
Phase a pod is in. | def kube_pod_status_phase(self, metric, scraper_config):
""" Phase a pod is in. """
metric_name = scraper_config['namespace'] + '.pod.status_phase'
status_phase_counter = Counter()
for sample in metric.samples:
# Counts aggregated cluster-wide to avoid no-data issues on pod ... |
Time until the next schedule | def kube_cronjob_next_schedule_time(self, metric, scraper_config):
""" Time until the next schedule """
# Used as a service check so that one can be alerted if the cronjob's next schedule is in the past
check_basename = scraper_config['namespace'] + '.cronjob.on_schedule_check'
curr_time... |
The ready status of a cluster node. v1.0+ | def kube_node_status_condition(self, metric, scraper_config):
""" The ready status of a cluster node. v1.0+"""
base_check_name = scraper_config['namespace'] + '.node'
metric_name = scraper_config['namespace'] + '.nodes.by_condition'
by_condition_counter = Counter()
for sample in... |
The ready status of a cluster node (legacy) | def kube_node_status_ready(self, metric, scraper_config):
""" The ready status of a cluster node (legacy)"""
service_check_name = scraper_config['namespace'] + '.node.ready'
for sample in metric.samples:
node_tag = self._label_to_tag("node", sample[self.SAMPLE_LABELS], scraper_config... |
Whether the node is in a network unavailable state (legacy) | def kube_node_status_network_unavailable(self, metric, scraper_config):
""" Whether the node is in a network unavailable state (legacy)"""
service_check_name = scraper_config['namespace'] + '.node.network_unavailable'
for sample in metric.samples:
node_tag = self._label_to_tag("node"... |
Whether a node can schedule new pods. | def kube_node_spec_unschedulable(self, metric, scraper_config):
""" Whether a node can schedule new pods. """
metric_name = scraper_config['namespace'] + '.node.status'
statuses = ('schedulable', 'unschedulable')
if metric.type in METRIC_TYPES:
for sample in metric.samples:
... |
Quota and current usage by resource type. | def kube_resourcequota(self, metric, scraper_config):
""" Quota and current usage by resource type. """
metric_base_name = scraper_config['namespace'] + '.resourcequota.{}.{}'
suffixes = {'used': 'used', 'hard': 'limit'}
if metric.type in METRIC_TYPES:
for sample in metric.sa... |
Resource limits by consumer type. | def kube_limitrange(self, metric, scraper_config):
""" Resource limits by consumer type. """
# type's cardinality's low: https://github.com/kubernetes/kubernetes/blob/v1.6.1/pkg/api/v1/types.go#L3872-L3879
# idem for resource: https://github.com/kubernetes/kubernetes/blob/v1.6.1/pkg/api/v1/types... |
Count objects by whitelisted tags and submit counts as gauges. | def count_objects_by_tags(self, metric, scraper_config):
""" Count objects by whitelisted tags and submit counts as gauges. """
config = self.object_count_params[metric.name]
metric_name = "{}.{}".format(scraper_config['namespace'], config['metric_name'])
object_counter = Counter()
... |
Searches for a pod uid in the podlist and returns the pod if found
:param uid: pod uid
:param podlist: podlist dict object
:return: pod dict object if found, None if not found | def get_pod_by_uid(uid, podlist):
"""
Searches for a pod uid in the podlist and returns the pod if found
:param uid: pod uid
:param podlist: podlist dict object
:return: pod dict object if found, None if not found
"""
for pod in podlist.get("items", []):
try:
if pod["meta... |
Return if the pod is a static pending pod
See https://github.com/kubernetes/kubernetes/pull/57106
:param pod: dict
:return: bool | def is_static_pending_pod(pod):
"""
Return if the pod is a static pending pod
See https://github.com/kubernetes/kubernetes/pull/57106
:param pod: dict
:return: bool
"""
try:
if pod["metadata"]["annotations"]["kubernetes.io/config.source"] == "api":
return False
p... |
Queries the agent6 container filter interface. It retrieves container
name + image from the podlist, so static pod filtering is not supported.
Result is cached between calls to avoid the python-go switching cost for
prometheus metrics (will be called once per metric)
:param cid: contain... | def is_excluded(self, cid, pod_uid=None):
"""
Queries the agent6 container filter interface. It retrieves container
name + image from the podlist, so static pod filtering is not supported.
Result is cached between calls to avoid the python-go switching cost for
prometheus metric... |
Returns the client certificates
:return: tuple (crt,key) or None | def cert_pair(self):
"""
Returns the client certificates
:return: tuple (crt,key) or None
"""
if self._ssl_cert and self._ssl_private_key:
return (self._ssl_cert, self._ssl_private_key)
else:
return None |
Returns the https headers with credentials, if token is used and url is https
:param url: url to be queried, including scheme
:return: dict or None | def headers(self, url):
"""
Returns the https headers with credentials, if token is used and url is https
:param url: url to be queried, including scheme
:return: dict or None
"""
if self._token and url.lower().startswith('https'):
return {'Authorization': 'Be... |
Configures a PrometheusScaper object with query credentials
:param scraper: valid PrometheusScaper object
:param endpoint: url that will be scraped | def configure_scraper(self, scraper_config):
"""
Configures a PrometheusScaper object with query credentials
:param scraper: valid PrometheusScaper object
:param endpoint: url that will be scraped
"""
endpoint = scraper_config['prometheus_url']
scraper_config.upda... |
Return the list of file changed in the current branch compared to `master` | def files_changed():
"""
Return the list of file changed in the current branch compared to `master`
"""
with chdir(get_root()):
result = run_command('git diff --name-only master...', capture='out')
changed_files = result.stdout.splitlines()
# Remove empty lines
return [f for f in ch... |
Get the list of commits from `target_tag` to `HEAD` for the given check | def get_commits_since(check_name, target_tag=None):
"""
Get the list of commits from `target_tag` to `HEAD` for the given check
"""
root = get_root()
target_path = os.path.join(root, check_name)
command = 'git log --pretty=%s {}{}'.format('' if target_tag is None else '{}... '.format(target_tag)... |
Return the contents of a file at a given tag | def git_show_file(path, ref):
"""
Return the contents of a file at a given tag
"""
root = get_root()
command = 'git show {}:{}'.format(ref, path)
with chdir(root):
return run_command(command, capture=True).stdout |
Commit the changes for the given targets. | def git_commit(targets, message, force=False, sign=False):
"""
Commit the changes for the given targets.
"""
root = get_root()
target_paths = []
for t in targets:
target_paths.append(os.path.join(root, t))
with chdir(root):
result = run_command('git add{} {}'.format(' -f' if... |
Tag the repo using an annotated tag. | def git_tag(tag_name, push=False):
"""
Tag the repo using an annotated tag.
"""
with chdir(get_root()):
result = run_command('git tag -a {} -m "{}"'.format(tag_name, tag_name), capture=True)
if push:
if result.code != 0:
return result
return run_c... |
Return a list of all the tags in the git repo matching a regex passed in
`pattern`. If `pattern` is None, return all the tags. | def git_tag_list(pattern=None):
"""
Return a list of all the tags in the git repo matching a regex passed in
`pattern`. If `pattern` is None, return all the tags.
"""
with chdir(get_root()):
result = run_command('git tag', capture=True).stdout
result = result.splitlines()
if not... |
Return a boolean value for whether the given file is tracked by git. | def git_ls_files(filename):
"""
Return a boolean value for whether the given file is tracked by git.
"""
with chdir(get_root()):
# https://stackoverflow.com/a/2406813
result = run_command('git ls-files --error-unmatch {}'.format(filename), capture=True)
return result.code == 0 |
When handling non english versions, the counters don't work quite as documented.
This is because strings like "Bytes Sent/sec" might appear multiple times in the
english master, and might not have mappings for each index.
Search each index, and make sure the requested counter name actually appe... | def _make_counter_path(self, machine_name, counter_name, instance_name, counters):
"""
When handling non english versions, the counters don't work quite as documented.
This is because strings like "Bytes Sent/sec" might appear multiple times in the
english master, and might not have mapp... |
Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps | def gauge(self, *args, **kwargs):
"""
Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps
"""
orig_gauge = super(Nagios, self).gauge
# remove 'timestamp' arg if the base class' gauge function does not accept a 'timestamp' arg
if 'times... |
Parse until the end of each tailer associated with this instance.
We match instance and tailers based on the path to the Nagios configuration file
Special case: Compatibility with the old conf when no conf file is specified
but the path to the event_log is given | def check(self, instance):
"""
Parse until the end of each tailer associated with this instance.
We match instance and tailers based on the path to the Nagios configuration file
Special case: Compatibility with the old conf when no conf file is specified
but the path to the even... |
Actual nagios parsing
Return True if we found an event, False otherwise | def _parse_line(self, line):
"""
Actual nagios parsing
Return True if we found an event, False otherwise
"""
# first isolate the timestamp and the event type
try:
self._line_parsed = self._line_parsed + 1
m = RE_LINE_REG.match(line)
if... |
Factory method called by the parsers | def create_event(self, timestamp, event_type, hostname, fields, tags=None):
"""Factory method called by the parsers
"""
# Agent6 expects a specific set of fields, so we need to place all
# extra fields in the msg_title and let the Datadog backend separate them
# Any remaining fie... |
Create a command generator to perform all the snmp query.
If mibs_path is not None, load the mibs present in the custom mibs
folder. (Need to be in pysnmp format) | def create_snmp_engine(self, mibs_path):
'''
Create a command generator to perform all the snmp query.
If mibs_path is not None, load the mibs present in the custom mibs
folder. (Need to be in pysnmp format)
'''
snmp_engine = hlapi.SnmpEngine()
mib_builder = snmp_... |
Generate a Security Parameters object based on the instance's
configuration.
See http://pysnmp.sourceforge.net/docs/current/security-configuration.html | def get_auth_data(cls, instance):
'''
Generate a Security Parameters object based on the instance's
configuration.
See http://pysnmp.sourceforge.net/docs/current/security-configuration.html
'''
if "community_string" in instance:
# SNMP v1 - SNMP v2
... |
Generate a Context Parameters object based on the instance's
configuration.
We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen
accepts Context Engine Id (always None for now) and Context Name parameters. | def get_context_data(cls, instance):
'''
Generate a Context Parameters object based on the instance's
configuration.
We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen
accepts Context Engine Id (always None for now) and Context Name parameters.
'''
... |
Generate a Transport target object based on the instance's configuration | def get_transport_target(cls, instance, timeout, retries):
'''
Generate a Transport target object based on the instance's configuration
'''
if "ip_address" not in instance:
raise Exception("An IP address needs to be specified")
ip_address = instance["ip_address"]
... |
Perform a snmpwalk on the domain specified by the oids, on the device
configured in instance.
lookup_names is a boolean to specify whether or not to use the mibs to
resolve the name and values.
Returns a dictionary:
dict[oid/metric_name][row index] = value
In case of sca... | def check_table(
self,
instance,
snmp_engine,
mib_view_controller,
oids,
lookup_names,
timeout,
retries,
enforce_constraints=False,
mibs_to_load=None,
):
'''
Perform a snmpwalk on the domain specified by the oids, on the... |
Perform two series of SNMP requests, one for all that have MIB asociated
and should be looked up and one for those specified by oids | def _check(self, instance):
'''
Perform two series of SNMP requests, one for all that have MIB asociated
and should be looked up and one for those specified by oids
'''
(
snmp_engine,
mib_view_controller,
ip_address,
tags,
... |
For all the metrics that are specified as oid,
the conf oid is going to exactly match or be a prefix of the oid sent back by the device
Use the instance configuration to find the name to give to the metric
Submit the results to the aggregator. | def report_raw_metrics(self, metrics, results, tags):
'''
For all the metrics that are specified as oid,
the conf oid is going to exactly match or be a prefix of the oid sent back by the device
Use the instance configuration to find the name to give to the metric
Submit the resu... |
For each of the metrics specified as needing to be resolved with mib,
gather the tags requested in the instance conf for each row.
Submit the results to the aggregator. | def report_table_metrics(self, metrics, results, tags):
'''
For each of the metrics specified as needing to be resolved with mib,
gather the tags requested in the instance conf for each row.
Submit the results to the aggregator.
'''
for metric in metrics:
fo... |
Gather the tags for this row of the table (index) based on the
results (all the results from the query).
index_tags and column_tags are the tags to gather.
- Those specified in index_tags contain the tag_group name and the
index of the value we want to extract from the index tuple.
... | def get_index_tags(self, index, results, index_tags, column_tags):
'''
Gather the tags for this row of the table (index) based on the
results (all the results from the query).
index_tags and column_tags are the tags to gather.
- Those specified in index_tags contain the tag_grou... |
Convert the values reported as pysnmp-Managed Objects to values and
report them to the aggregator | def submit_metric(self, name, snmp_value, forced_type, tags=None):
'''
Convert the values reported as pysnmp-Managed Objects to values and
report them to the aggregator
'''
tags = [] if tags is None else tags
if reply_invalid(snmp_value):
# Metrics not present... |
See https://github.com/python/cpython/blob/b02774f42108aaf18eb19865472c8d5cd95b5f11/Lib/bdb.py#L319-L332 | def set_trace(self, frame=None):
"""See https://github.com/python/cpython/blob/b02774f42108aaf18eb19865472c8d5cd95b5f11/Lib/bdb.py#L319-L332"""
self.reset()
if frame is None:
frame = sys._getframe().f_back
while frame:
frame.f_trace = self.trace_dispatch
... |
The current average latency or None. | def round_trip_time(self):
"""The current average latency or None."""
# This override is for unittesting only!
if self._address in self._host_to_round_trip_time:
return self._host_to_round_trip_time[self._address]
return self._round_trip_time |
Collect stats for all reachable networks | def collect_networks_metrics(self, tags, network_ids, exclude_network_id_rules):
"""
Collect stats for all reachable networks
"""
networks = self.get_networks()
filtered_networks = []
if not network_ids:
# Filter out excluded networks
filtered_netw... |
Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' | def _parse_uptime_string(self, uptime):
""" Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """
uptime = uptime.strip()
load_averages = uptime[uptime.find('load average:') :].split(':')[1].strip().split(',')
load_averages = [float(load_avg) for load_avg in... |
Submits stats for all hypervisors registered to this control plane
Raises specific exceptions based on response code | def collect_hypervisors_metrics(
self,
servers,
custom_tags=None,
use_shortname=False,
collect_hypervisor_metrics=True,
collect_hypervisor_load=False,
):
"""
Submits stats for all hypervisors registered to this control plane
Raises specific exc... |
Guarantees a valid auth scope for this instance, and returns it
Communicates with the identity server and initializes a new scope when one is absent, or has been forcibly
removed due to token expiry | def init_api(self, instance_config, custom_tags):
"""
Guarantees a valid auth scope for this instance, and returns it
Communicates with the identity server and initializes a new scope when one is absent, or has been forcibly
removed due to token expiry
"""
custom_tags = ... |
Tries to connect to the cadvisor endpoint, with given params
:return: url if OK, raises exception if NOK | def detect_cadvisor(kubelet_url, cadvisor_port):
"""
Tries to connect to the cadvisor endpoint, with given params
:return: url if OK, raises exception if NOK
"""
if cadvisor_port == 0:
raise ValueError("cAdvisor port set to 0 in configuration")
kubelet_hostnam... |
Scrape and submit metrics from cadvisor
:param: instance: check instance object
:param: cadvisor_url: valid cadvisor url, as returned by detect_cadvisor()
:param: pod_list: fresh podlist object from the kubelet
:param: pod_list_utils: already initialised PodListUtils object | def process_cadvisor(self, instance, cadvisor_url, pod_list, pod_list_utils):
"""
Scrape and submit metrics from cadvisor
:param: instance: check instance object
:param: cadvisor_url: valid cadvisor url, as returned by detect_cadvisor()
:param: pod_list: fresh podlist object from... |
Recusively parses and submit metrics for a given entity, until
reaching self.max_depth.
Nested metric names are flattened: memory/usage -> memory.usage
:param: metric: parent's metric name (check namespace for root stat objects)
:param: dat: metric dictionnary to parse
:param: ta... | def _publish_raw_metrics(self, metric, dat, tags, is_pod, depth=0):
"""
Recusively parses and submit metrics for a given entity, until
reaching self.max_depth.
Nested metric names are flattened: memory/usage -> memory.usage
:param: metric: parent's metric name (check namespace fo... |
Get the proper set of stats metrics for the specified ES version | def stats_for_version(version):
"""
Get the proper set of stats metrics for the specified ES version
"""
metrics = dict(STATS_METRICS)
# JVM additional metrics
if version >= [0, 90, 10]:
metrics.update(JVM_METRICS_POST_0_90_10)
else:
metrics.update(JVM_METRICS_PRE_0_90_10)
... |
Get the proper set of pshard metrics for the specified ES version | def pshard_stats_for_version(version):
"""
Get the proper set of pshard metrics for the specified ES version
"""
pshard_stats_metrics = dict(PRIMARY_SHARD_METRICS)
if version >= [1, 0, 0]:
pshard_stats_metrics.update(PRIMARY_SHARD_METRICS_POST_1_0)
return pshard_stats_metrics |
Get the proper set of health metrics for the specified ES version | def health_stats_for_version(version):
"""
Get the proper set of health metrics for the specified ES version
"""
cluster_health_metrics = dict(CLUSTER_HEALTH_METRICS)
if version >= [2, 4, 0]:
cluster_health_metrics.update(CLUSTER_HEALTH_METRICS_POST_2_4)
return cluster_health_metrics |
Show all the checks that can be released. | def ready(ctx, quiet):
"""Show all the checks that can be released."""
user_config = ctx.obj
cached_prs = {}
for target in sorted(get_valid_checks()):
# get the name of the current release tag
cur_version = get_version_string(target)
target_tag = get_release_tag_string(target, c... |
Show all the pending PRs for a given check. | def changes(ctx, check, dry_run):
"""Show all the pending PRs for a given check."""
if not dry_run and check not in get_valid_checks():
abort('Check `{}` is not an Agent-based Integration'.format(check))
# get the name of the current release tag
cur_version = get_version_string(check)
targe... |
Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
a maintenance task that should be run under ve... | def tag(check, version, push, dry_run):
"""Tag the HEAD of the git repo with the current release number for a
specific check. The tag is pushed to origin by default.
You can tag everything at once by setting the check to `all`.
Notice: specifying a different version than the one in __about__.py is
... |
Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit the above changes
You can release everything at once by setting the che... | def make(ctx, check, version, initial_release, skip_sign, sign_only):
"""Perform a set of operations needed to release a single check:
\b
* update the version in __about__.py
* update the changelog
* update the requirements-agent-release.txt file
* update in-toto metadata
* commit... |
Perform the operations needed to update the changelog.
This method is supposed to be used by other tasks and not directly. | def changelog(ctx, check, version, old_version, initial, quiet, dry_run):
"""Perform the operations needed to update the changelog.
This method is supposed to be used by other tasks and not directly.
"""
if check not in get_valid_checks():
abort('Check `{}` is not an Agent-based Integration'.fo... |
Build a wheel for a check as it is on the repo HEAD | def build(check, sdist):
"""Build a wheel for a check as it is on the repo HEAD"""
if check in get_valid_checks():
check_dir = os.path.join(get_root(), check)
else:
check_dir = resolve_path(check)
if not dir_exists(check_dir):
abort('`{}` is not an Agent-based Integration... |
Release a specific check to PyPI as it is on the repo HEAD. | def upload(ctx, check, sdist, dry_run):
"""Release a specific check to PyPI as it is on the repo HEAD."""
if check in get_valid_checks():
check_dir = os.path.join(get_root(), check)
else:
check_dir = resolve_path(check)
if not dir_exists(check_dir):
abort('`{}` is not an ... |
Return the metrics received under the given name | def metrics(self, name):
"""
Return the metrics received under the given name
"""
return [
MetricStub(
ensure_unicode(stub.name),
stub.type,
stub.value,
normalize_tags(stub.tags),
ensure_unicode(s... |
Return the service checks received under the given name | def service_checks(self, name):
"""
Return the service checks received under the given name
"""
return [
ServiceCheckStub(
ensure_unicode(stub.check_id),
ensure_unicode(stub.name),
stub.status,
normalize_tags(stu... |
Return all events | def events(self):
"""
Return all events
"""
all_events = [{ensure_unicode(key): value for key, value in iteritems(ev)} for ev in self._events]
for ev in all_events:
to_decode = []
for key, value in iteritems(ev):
if isinstance(value, binar... |
Assert a metric is tagged with tag | def assert_metric_has_tag(self, metric_name, tag, count=None, at_least=1):
"""
Assert a metric is tagged with tag
"""
self._asserted.add(metric_name)
candidates = []
for metric in self.metrics(metric_name):
if tag in metric.tags:
candidates.ap... |
Assert a metric was processed by this stub | def assert_metric(self, name, value=None, tags=None, count=None, at_least=1, hostname=None, metric_type=None):
"""
Assert a metric was processed by this stub
"""
self._asserted.add(name)
tags = normalize_tags(tags, sort=True)
candidates = []
for metric in self.me... |
Assert a service check was processed by this stub | def assert_service_check(self, name, status=None, tags=None, count=None, at_least=1, hostname=None, message=None):
"""
Assert a service check was processed by this stub
"""
tags = normalize_tags(tags, sort=True)
candidates = []
for sc in self.service_checks(name):
... |
Return the metrics assertion coverage | def metrics_asserted_pct(self):
"""
Return the metrics assertion coverage
"""
num_metrics = len(self._metrics)
num_asserted = len(self._asserted)
if num_metrics == 0:
if num_asserted == 0:
return 100
else:
return 0
... |
Examine the response and raise an error is something is off | def _process_response(cls, response):
"""
Examine the response and raise an error is something is off
"""
if len(response) != 1:
raise BadResponseError("Malformed response: {}".format(response))
stats = list(itervalues(response))[0]
if not len(stats):
... |
Optional metric handler for 'items' stats
key: "items:<slab_id>:<metric_name>" format
value: return untouched
Like all optional metric handlers returns metric, tags, value | def get_items_stats(key, value):
"""
Optional metric handler for 'items' stats
key: "items:<slab_id>:<metric_name>" format
value: return untouched
Like all optional metric handlers returns metric, tags, value
"""
itemized_key = key.split(':')
slab_id = i... |
Optional metric handler for 'items' stats
key: "items:<slab_id>:<metric_name>" format
value: return untouched
Like all optional metric handlers returns metric, tags, value | def get_slabs_stats(key, value):
"""
Optional metric handler for 'items' stats
key: "items:<slab_id>:<metric_name>" format
value: return untouched
Like all optional metric handlers returns metric, tags, value
"""
slabbed_key = key.split(':')
tags = []
... |
instance: the check instance
base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api)
object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE
max_detailed: the limit of objects to collect for this type
filters: explicit or regexes filters of specified queue... | def get_stats(
self,
instance,
base_url,
object_type,
max_detailed,
filters,
limit_vhosts,
custom_tags,
auth=None,
ssl_verify=True,
):
"""
instance: the check instance
base_url: the url of the rabbitmq management... |
Collect metrics on currently open connection per vhost. | def get_connections_stat(
self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth=None, ssl_verify=True
):
"""
Collect metrics on currently open connection per vhost.
"""
instance_proxy = self.get_instance_proxy(instance, base_url)
grab_all_dat... |
Check the aliveness API against all or a subset of vhosts. The API
will return {"status": "ok"} and a 200 response code in the case
that the check passes. | def _check_aliveness(self, instance, base_url, vhosts, custom_tags, auth=None, ssl_verify=True):
"""
Check the aliveness API against all or a subset of vhosts. The API
will return {"status": "ok"} and a 200 response code in the case
that the check passes.
"""
for vhost i... |
Create a GridIn property. | def _grid_in_property(field_name, docstring, read_only=False,
closed_only=False):
"""Create a GridIn property."""
def getter(self):
if closed_only and not self._closed:
raise AttributeError("can only get %r on a closed file" %
field_name... |
Create a GridOut property. | def _grid_out_property(field_name, docstring):
"""Create a GridOut property."""
def getter(self):
self._ensure_file()
# Protect against PHP-237
if field_name == 'length':
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
docstring += "... |
Flush `data` to a chunk. | def __flush_data(self, data):
"""Flush `data` to a chunk.
"""
# Ensure the index, even if there's nothing to write, so
# the filemd5 command always succeeds.
self.__ensure_indexes()
self._file['md5'].update(data)
if not data:
return
assert(len... |
Flush the buffer contents out to a chunk. | def __flush_buffer(self):
"""Flush the buffer contents out to a chunk.
"""
self.__flush_data(self._buffer.getvalue())
self._buffer.close()
self._buffer = StringIO() |
Flush the file to the database. | def __flush(self):
"""Flush the file to the database.
"""
try:
self.__flush_buffer()
self._file['md5'] = self._file["md5"].hexdigest()
self._file["length"] = self._position
self._file["uploadDate"] = datetime.datetime.utcnow()
return ... |
Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed. | def close(self):
"""Flush the file and close it.
A closed file cannot be written any more. Calling
:meth:`close` more than once is allowed.
"""
if not self._closed:
self.__flush()
object.__setattr__(self, "_closed", True) |
Write data to the file. There is no return value.
`data` can be either a string of bytes or a file-like object
(implementing :meth:`read`). If the file has an
:attr:`encoding` attribute, `data` can also be a
:class:`unicode` (:class:`str` in python 3) instance, which
will be enc... | def write(self, data):
"""Write data to the file. There is no return value.
`data` can be either a string of bytes or a file-like object
(implementing :meth:`read`). If the file has an
:attr:`encoding` attribute, `data` can also be a
:class:`unicode` (:class:`str` in python 3) i... |
Reads a chunk at a time. If the current position is within a
chunk the remainder of the chunk is returned. | def readchunk(self):
"""Reads a chunk at a time. If the current position is within a
chunk the remainder of the chunk is returned.
"""
received = len(self.__buffer)
chunk_data = EMPTY
chunk_size = int(self.chunk_size)
if received > 0:
chunk_data = sel... |
Read at most `size` bytes from the file (less if there
isn't enough data).
The bytes are returned as an instance of :class:`str` (:class:`bytes`
in python 3). If `size` is negative or omitted all data is read.
:Parameters:
- `size` (optional): the number of bytes to read | def read(self, size=-1):
"""Read at most `size` bytes from the file (less if there
isn't enough data).
The bytes are returned as an instance of :class:`str` (:class:`bytes`
in python 3). If `size` is negative or omitted all data is read.
:Parameters:
- `size` (optiona... |
Set the current position of this file.
:Parameters:
- `pos`: the position (or offset if using relative
positioning) to seek to
- `whence` (optional): where to seek
from. :attr:`os.SEEK_SET` (``0``) for absolute file
positioning, :attr:`os.SEEK_CUR` (``1``) to ... | def seek(self, pos, whence=_SEEK_SET):
"""Set the current position of this file.
:Parameters:
- `pos`: the position (or offset if using relative
positioning) to seek to
- `whence` (optional): where to seek
from. :attr:`os.SEEK_SET` (``0``) for absolute file
... |
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT` | def provider(self, value):
"""
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`
"""
result = None
# `None` defaults to `ProviderArchitecture.DEFAULT`
defaulted_value = value or ProviderArchitecture.DEFAULT
try:
parsed_value ... |
A property to retrieve the sampler connection information. | def connection(self):
"""
A property to retrieve the sampler connection information.
"""
return {'host': self.host, 'namespace': self.namespace, 'username': self.username, 'password': self.password} |
Return an index key used to cache the sampler connection. | def connection_key(self):
"""
Return an index key used to cache the sampler connection.
"""
return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username) |
Cache and return filters as a comprehensive WQL clause. | def formatted_filters(self):
"""
Cache and return filters as a comprehensive WQL clause.
"""
if not self._formatted_filters:
filters = deepcopy(self.filters)
self._formatted_filters = self._format_filter(filters, self._and_props)
return self._formatted_fil... |
Compute new samples. | def sample(self):
"""
Compute new samples.
"""
self._sampling = True
try:
if self.is_raw_perf_class and not self._previous_sample:
self._current_sample = self._query()
self._previous_sample = self._current_sample
self._current... |
Return the calculator for the given `counter_type`.
Fallback with `get_raw`. | def _get_property_calculator(self, counter_type):
"""
Return the calculator for the given `counter_type`.
Fallback with `get_raw`.
"""
calculator = get_raw
try:
calculator = get_calculator(counter_type)
except UndefinedCalculator:
self.logg... |
Format WMI Object's RAW data based on the previous sample.
Do not override the original WMI Object ! | def _format_property_values(self, previous, current):
"""
Format WMI Object's RAW data based on the previous sample.
Do not override the original WMI Object !
"""
formatted_wmi_object = CaseInsensitiveDict()
for property_name, property_raw_value in iteritems(current):
... |
Create a new WMI connection | def get_connection(self):
"""
Create a new WMI connection
"""
self.logger.debug(
u"Connecting to WMI server "
u"(host={host}, namespace={namespace}, provider={provider}, username={username}).".format(
host=self.host, namespace=self.namespace, provi... |
Transform filters to a comprehensive WQL `WHERE` clause.
Builds filter from a filter list.
- filters: expects a list of dicts, typically:
- [{'Property': value},...] or
- [{'Property': (comparison_op, value)},...]
NOTE: If we just provide a value we defa... | def _format_filter(filters, and_props=[]):
"""
Transform filters to a comprehensive WQL `WHERE` clause.
Builds filter from a filter list.
- filters: expects a list of dicts, typically:
- [{'Property': value},...] or
- [{'Property': (comparison_op, value)}... |
Query WMI using WMI Query Language (WQL) & parse the results.
Returns: List of WMI objects or `TimeoutException`. | def _query(self): # pylint: disable=E0202
"""
Query WMI using WMI Query Language (WQL) & parse the results.
Returns: List of WMI objects or `TimeoutException`.
"""
formated_property_names = ",".join(self.property_names)
wql = "Select {property_names} from {class_name}{f... |
Parse WMI query results in a more comprehensive form.
Returns: List of WMI objects
```
[
{
'freemegabytes': 19742.0,
'name': 'C:',
'avgdiskbytesperwrite': 1536.0
}, {
'freemegabytes': 19742.0,
... | def _parse_results(self, raw_results, includes_qualifiers):
"""
Parse WMI query results in a more comprehensive form.
Returns: List of WMI objects
```
[
{
'freemegabytes': 19742.0,
'name': 'C:',
'avgdiskbytesperwrite': ... |
Return (IsMaster, round_trip_time).
Can raise ConnectionFailure or OperationFailure. | def _check_with_socket(self, sock_info, metadata=None):
"""Return (IsMaster, round_trip_time).
Can raise ConnectionFailure or OperationFailure.
"""
cmd = SON([('ismaster', 1)])
if metadata is not None:
cmd['client'] = metadata
start = _time()
request_... |
Verify that the checks versions are in sync with the requirements-agent-release.txt file | def agent_reqs():
"""Verify that the checks versions are in sync with the requirements-agent-release.txt file"""
echo_info("Validating requirements-agent-release.txt...")
agent_reqs_content = parse_agent_req_file(read_file(get_agent_release_requirements()))
ok_checks = 0
unreleased_checks = 0
f... |
Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` | def _log_deprecation(self, deprecation_key):
"""
Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key`
"""
if not self._deprecations[deprecation_key][0]:
self.log.warning(self._deprecations[deprecation_key][1])
self.... |
Convert from CamelCase to camel_case
And substitute illegal metric characters | def convert_to_underscore_separated(self, name):
"""
Convert from CamelCase to camel_case
And substitute illegal metric characters
"""
metric_name = self.FIRST_CAP_RE.sub(br'\1_\2', ensure_bytes(name))
metric_name = self.ALL_CAP_RE.sub(br'\1_\2', metric_name).lower()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.