INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
data: dictionary containing all the stats
metric: datadog metric
path: corresponding path in data, flattened, e.g. thread_pool.bulk.queue
xform: a lambda to apply to the numerical value | def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None):
"""
data: dictionary containing all the stats
metric: datadog metric
path: corresponding path in data, flattened, e.g. thread_pool.bulk.queue
xform: a lambda to apply to the numerical valu... |
Resets state and uid set. To be called asap to free memory | def reset(self):
"""
Resets state and uid set. To be called asap to free memory
"""
self.reached_limit = False
self.count = 0
self.seen.clear() |
is_reached is to be called for every object that counts towards the limit.
- When called with no uid, the Limiter assumes this is a new object and
unconditionally increments the counter (less CPU and memory usage).
- When a given object can be passed multiple times, a uid must be provided to
... | def is_reached(self, uid=None):
"""
is_reached is to be called for every object that counts towards the limit.
- When called with no uid, the Limiter assumes this is a new object and
unconditionally increments the counter (less CPU and memory usage).
- When a given object can be ... |
Fetch highwater offsets for each topic/partition from Kafka cluster.
Do this for all partitions in the cluster because even if it has no
consumers, we may want to measure whether producers are successfully
producing. No need to limit this for performance because fetching broker
offsets ... | def _get_broker_offsets(self, instance, topics):
"""
Fetch highwater offsets for each topic/partition from Kafka cluster.
Do this for all partitions in the cluster because even if it has no
consumers, we may want to measure whether producers are successfully
producing. No need t... |
Fetch child nodes for a given Zookeeper path. | def _get_zk_path_children(self, zk_conn, zk_path, name_for_error):
"""Fetch child nodes for a given Zookeeper path."""
children = []
try:
children = zk_conn.get_children(zk_path)
except NoNodeError:
self.log.info('No zookeeper node at %s', zk_path)
except ... |
Fetch Consumer Group offsets from Zookeeper.
Also fetch consumer_groups, topics, and partitions if not
already specified in consumer_groups.
:param dict consumer_groups: The consumer groups, topics, and partitions
that you want to fetch offsets for. If consumer_groups is None, will... | def _get_zk_consumer_offsets(self, zk_hosts_ports, consumer_groups=None, zk_prefix=''):
"""
Fetch Consumer Group offsets from Zookeeper.
Also fetch consumer_groups, topics, and partitions if not
already specified in consumer_groups.
:param dict consumer_groups: The consumer gro... |
retrieve consumer offsets via the new consumer api. Offsets in this version are stored directly
in kafka (__consumer_offsets topic) rather than in zookeeper | def _get_kafka_consumer_offsets(self, instance, consumer_groups):
"""
retrieve consumer offsets via the new consumer api. Offsets in this version are stored directly
in kafka (__consumer_offsets topic) rather than in zookeeper
"""
consumer_offsets = {}
topics = defaultdic... |
Validate any explicitly specified consumer groups.
While the check does not require specifying consumer groups,
if they are specified this method should be used to validate them.
val = {'consumer_group': {'topic': [0, 1]}} | def _validate_explicit_consumer_groups(cls, val):
"""Validate any explicitly specified consumer groups.
While the check does not require specifying consumer groups,
if they are specified this method should be used to validate them.
val = {'consumer_group': {'topic': [0, 1]}}
""... |
Emit an event to the Datadog Event Stream. | def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
"""Emit an event to the Datadog Event Stream."""
event_dict = {
'timestamp': int(time()),
'source_type_name': self.SOURCE_TYPE_NAME,
'msg_title': title,
'event_type': e... |
Print packages that've been added, removed or changed | def display_package_changes(pre_packages, post_packages, indent=''):
"""
Print packages that've been added, removed or changed
"""
# use package name to determine what's changed
pre_package_names = {p.name: p for p in pre_packages}
post_package_names = {p.name: p for p in post_packages}
add... |
Resolve transient dependencies for any number of checks.
If you want to do this en masse, put `all`. | def resolve(checks, lazy, quiet):
"""Resolve transient dependencies for any number of checks.
If you want to do this en masse, put `all`.
"""
root = get_root()
if 'all' in checks:
checks = os.listdir(root)
for check_name in sorted(checks):
pinned_reqs_file = os.path.join(root, c... |
Pin a dependency for all checks that require it. This can
also resolve transient dependencies.
Setting the version to `none` will remove the package. You can
specify an unlimited number of additional checks to apply the
pin for via arguments. | def pin(package, version, checks, marker, resolving, lazy, quiet):
"""Pin a dependency for all checks that require it. This can
also resolve transient dependencies.
Setting the version to `none` will remove the package. You can
specify an unlimited number of additional checks to apply the
pin for v... |
Combine all dependencies for the Agent's static environment. | def freeze():
"""Combine all dependencies for the Agent's static environment."""
echo_waiting('Verifying collected packages...')
catalog, errors = make_catalog()
if errors:
for error in errors:
echo_failure(error)
abort()
static_file = get_agent_requirements()
echo_... |
Restart an Agent to detect environment changes. | def reload_env(check, env):
"""Restart an Agent to detect environment changes."""
envs = get_configured_envs(check)
if not envs:
echo_failure('No active environments found for `{}`.'.format(check))
echo_info('See what is available to start via `ddev env ls {}`.'.format(check))
abort(... |
Set up the gitlab instance so it can be used in OpenMetricsBaseCheck | def _create_gitlab_prometheus_instance(self, instance, init_config):
"""
Set up the gitlab instance so it can be used in OpenMetricsBaseCheck
"""
# Mapping from Prometheus metrics names to Datadog ones
# For now it's a 1:1 mapping
allowed_metrics = init_config.get('allowe... |
Submit a metric as a gauge, additional tags provided will be added to
the ones from the label provided via the metrics object.
`custom_tags` is an array of 'tag:value' that will be added to the
metric when sending the gauge to Datadog. | def _submit_gauge(self, metric_name, val, metric, custom_tags=None, hostname=None):
"""
Submit a metric as a gauge, additional tags provided will be added to
the ones from the label provided via the metrics object.
`custom_tags` is an array of 'tag:value' that will be added to the
... |
Validate tag sets for a MongoReplicaSetClient. | def _validate_tag_sets(tag_sets):
"""Validate tag sets for a MongoReplicaSetClient.
"""
if tag_sets is None:
return tag_sets
if not isinstance(tag_sets, list):
raise TypeError((
"Tag sets %r invalid, must be a list") % (tag_sets,))
if len(tag_sets) == 0:
raise Va... |
Validate max_staleness. | def _validate_max_staleness(max_staleness):
"""Validate max_staleness."""
if max_staleness == -1:
return -1
if not isinstance(max_staleness, integer_types):
raise TypeError(_invalid_max_staleness_msg(max_staleness))
if max_staleness <= 0:
raise ValueError(_invalid_max_staleness... |
Read preference as a document. | def document(self):
"""Read preference as a document.
"""
doc = {'mode': self.__mongos_mode}
if self.__tag_sets not in (None, [{}]):
doc['tags'] = self.__tag_sets
if self.__max_staleness != -1:
doc['maxStalenessSeconds'] = self.__max_staleness
retu... |
Get stats from the queue manager | def queue_manager_stats(self, queue_manager, tags):
"""
Get stats from the queue manager
"""
for mname, pymqi_value in iteritems(metrics.queue_manager_metrics()):
try:
m = queue_manager.inquire(pymqi_value)
mname = '{}.queue_manager.{}'.format... |
Grab stats from queues | def queue_stats(self, queue, tags):
"""
Grab stats from queues
"""
for mname, pymqi_value in iteritems(metrics.queue_metrics()):
try:
mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname)
m = queue.inquire(pymqi_value)
self.ga... |
Get the version string for the given check. | def get_version_string(check_name):
"""
Get the version string for the given check.
"""
version = VERSION.search(read_version_file(check_name))
if version:
return version.group(1) |
Load the manifest file into a dictionary | def load_manifest(check_name):
"""
Load the manifest file into a dictionary
"""
manifest_path = os.path.join(get_root(), check_name, 'manifest.json')
if file_exists(manifest_path):
return json.loads(read_file(manifest_path))
return {} |
Returns a dictionary mapping {check-package-name --> pinned_version} from the
given file contents. We can assume lines are in the form:
datadog-active-directory==1.1.1; sys_platform == 'win32' | def parse_agent_req_file(contents):
"""
Returns a dictionary mapping {check-package-name --> pinned_version} from the
given file contents. We can assume lines are in the form:
datadog-active-directory==1.1.1; sys_platform == 'win32'
"""
catalog = OrderedDict()
for line in contents.spli... |
Query status and get a dictionary back.
Extract each field out of the dictionary
and stuff it in the corresponding metric.
query: show status...
field_metric_map: {"Seconds_behind_master": "mysqlSecondsBehindMaster"} | def _collect_dict(self, metric_type, field_metric_map, query, db, tags):
"""
Query status and get a dictionary back.
Extract each field out of the dictionary
and stuff it in the corresponding metric.
query: show status...
field_metric_map: {"Seconds_behind_master": "mysq... |
Get the `pid_file` variable | def _get_pid_file_variable(self, db):
"""
Get the `pid_file` variable
"""
pid_file = None
try:
with closing(db.cursor()) as cursor:
cursor.execute("SHOW VARIABLES LIKE 'pid_file'")
pid_file = cursor.fetchone()[1]
except Exceptio... |
Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking | def _get_slave_status(self, db, above_560, nonblocking):
"""
Retrieve the slaves' statuses using:
1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0
2. The `information_schema.processlist` table. Blocking
"""
try:
with closing(db... |
Return a dictionary for each job counter
{
counter_group_name: [
counter_name
]
}
} | def _parse_general_counters(self, init_config):
"""
Return a dictionary for each job counter
{
counter_group_name: [
counter_name
]
}
}
"""
job_counter = {}
if init_config.get('general_counters'):
# Parse... |
Return a dictionary for each job counter
{
job_name: {
counter_group_name: [
counter_name
]
}
}
} | def _parse_job_specific_counters(self, init_config):
"""
Return a dictionary for each job counter
{
job_name: {
counter_group_name: [
counter_name
]
}
}
}
"""
job_counter = {}
if init_confi... |
Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications | def _get_running_app_ids(self, rm_address, auth, ssl_verify):
"""
Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications
"""
metrics_json = self._rest_request_to_json(
rm_address,
auth,
ssl_verify,
... |
Get metrics for each MapReduce job.
Return a dictionary for each MapReduce job
{
job_id: {
'job_name': job_name,
'app_name': app_name,
'user_name': user_name,
'tracking_url': tracking_url
} | def _mapreduce_job_metrics(self, running_apps, auth, ssl_verify, addl_tags):
"""
Get metrics for each MapReduce job.
Return a dictionary for each MapReduce job
{
job_id: {
'job_name': job_name,
'app_name': app_name,
'user_name': user_name,
... |
Get custom metrics specified for each counter | def _mapreduce_job_counters_metrics(self, running_jobs, auth, ssl_verify, addl_tags):
"""
Get custom metrics specified for each counter
"""
for job_metrics in itervalues(running_jobs):
job_name = job_metrics['job_name']
# Check if the job_name exist in the custom... |
Get metrics for each MapReduce task
Return a dictionary of {task_id: 'tracking_url'} for each MapReduce task | def _mapreduce_task_metrics(self, running_jobs, auth, ssl_verify, addl_tags):
"""
Get metrics for each MapReduce task
Return a dictionary of {task_id: 'tracking_url'} for each MapReduce task
"""
for job_stats in itervalues(running_jobs):
metrics_json = self._rest_req... |
Parse the JSON response and set the metrics | def _set_metrics_from_json(self, metrics_json, metrics, tags):
"""
Parse the JSON response and set the metrics
"""
for status, (metric_name, metric_type) in iteritems(metrics):
metric_status = metrics_json.get(status)
if metric_status is not None:
... |
Set a metric | def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None):
"""
Set a metric
"""
if metric_type == self.HISTOGRAM:
self.histogram(metric_name, value, tags=tags, device_name=device_name)
elif metric_type == self.INCREMENT:
self.incr... |
Query the given URL and return the JSON response | def _rest_request_to_json(self, address, auth, ssl_verify, object_path, service_name, tags=None, *args, **kwargs):
"""
Query the given URL and return the JSON response
"""
response_json = None
tags = [] if tags is None else tags
service_check_tags = ['url:{}'.format(self... |
Reads `init_config` for `psutil` methods to call on the current process
Calls those methods and stores the raw output
:returns a dictionary of statistic_name: value | def _psutil_config_to_stats(self, instance):
"""
Reads `init_config` for `psutil` methods to call on the current process
Calls those methods and stores the raw output
:returns a dictionary of statistic_name: value
"""
process_metrics = instance.get('process_metrics', sel... |
Saves sample metrics from psutil
:param stats: a dictionary that looks like:
{
'memory_info': OrderedDict([('rss', 24395776), ('vms', 144666624)]),
'io_counters': OrderedDict([('read_count', 4536),
('write_count', 100),
... | def _register_psutil_metrics(self, stats, names_to_metric_types, tags=None):
"""
Saves sample metrics from psutil
:param stats: a dictionary that looks like:
{
'memory_info': OrderedDict([('rss', 24395776), ('vms', 144666624)]),
'io_counters': OrderedDict([('read_count... |
Get a Docker container's IP address from its id or name. | def get_container_ip(container_id_or_name):
"""Get a Docker container's IP address from its id or name."""
command = [
'docker',
'inspect',
'-f',
'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}',
container_id_or_name,
]
return run_command(command, captu... |
This utility provides a convenient way to safely set up and tear down Docker environments.
:param compose_file: A path to a Docker compose file. A custom tear
down is not required when using this.
:type compose_file: ``str``
:param build: Whether or not to build images for when ``c... | def docker_run(
compose_file=None,
build=False,
service_name=None,
up=None,
down=None,
sleep=None,
endpoints=None,
log_patterns=None,
conditions=None,
env_vars=None,
wrapper=None,
):
"""This utility provides a convenient way to safely set up and tear down Docker environme... |
Get the SON document representation of this DBRef.
Generally not needed by application developers | def as_doc(self):
"""Get the SON document representation of this DBRef.
Generally not needed by application developers
"""
doc = SON([("$ref", self.collection),
("$id", self.id)])
if self.database is not None:
doc["$db"] = self.database
doc... |
Reset the config object to its initial state | def clear(self):
"""
Reset the config object to its initial state
"""
with self._lock:
self._config = {
CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}},
CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}},
} |
Notice: this will return the defaultdict default value also for keys
that are not in the configuration, this is a tradeoff to keep the code simple. | def get_last(self, type_, key):
"""
Notice: this will return the defaultdict default value also for keys
that are not in the configuration, this is a tradeoff to keep the code simple.
"""
self._check_type(type_)
with self._lock:
return self._config[type_]['las... |
Get a list of possible paths containing certificates
Check is installed via pip to:
* Windows: embedded/lib/site-packages/datadog_checks/http_check
* Linux: embedded/lib/python2.7/site-packages/datadog_checks/http_check
Certificate is installed to:
* embedded/ssl/certs/cacert.pem
walk up t... | def _get_ca_certs_paths():
"""
Get a list of possible paths containing certificates
Check is installed via pip to:
* Windows: embedded/lib/site-packages/datadog_checks/http_check
* Linux: embedded/lib/python2.7/site-packages/datadog_checks/http_check
Certificate is installed to:
* embed... |
Validate logo files. Specifying no check will validate all logos | def logos(check):
"""Validate logo files. Specifying no check will validate all logos"""
valid_checks = get_valid_integrations()
if check:
if check in valid_checks:
checks = [check]
else:
echo_info('{} is not an integration.'.format(check))
return
el... |
The text option (-1) is not reliable enough when counters get large.
VBE.media_video_prd_services_01(10.93.67.16,,8080).happy18446744073709551615
2 types of data, "a" for counter ("c" in newer versions of varnish), "i" for gauge ("g")
https://github.com/varnish/Varnish-Cache/blob/master/include... | def _parse_varnishstat(self, output, varnishstat_format, tags=None):
"""
The text option (-1) is not reliable enough when counters get large.
VBE.media_video_prd_services_01(10.93.67.16,,8080).happy18446744073709551615
2 types of data, "a" for counter ("c" in newer versions of varnish),... |
Parse out service checks from varnishadm.
Example output:
Backend b0 is Sick
Current states good: 2 threshold: 3 window: 5
Average responsetime of good probes: 0.000000
Oldest Newest
============... | def _parse_varnishadm(self, output, tags):
""" Parse out service checks from varnishadm.
Example output:
Backend b0 is Sick
Current states good: 2 threshold: 3 window: 5
Average responsetime of good probes: 0.000000
Oldest ... |
Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0])
The text format uses iter_lines() generator.
The protobuf format directly parse the response.content property searching for Prometheus messages of type
MetricFamily [0] delimited by a varint... | def parse_metric_family(self, response):
"""
Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0])
The text format uses iter_lines() generator.
The protobuf format directly parse the response.content property searching for Prometheus me... |
Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: line generator
:output: generator of filtered lines | def _text_filter_input(self, input_gen):
"""
Filters out the text input line by line to avoid parsing and processing
metrics we know we don't want to process. This only works on `text/plain`
payloads, and is an INTERNAL FEATURE implemented for the kubelet check
:param input_get: ... |
:param messages: dictionary as metric_name: {labels: {}, value: 10}
:param _metric: dictionary as {labels: {le: '0.001', 'custom': 'value'}}
:param _m: str as metric name
:param metric_suffix: str must be in (count or sum)
:return: value of the metric_name matched by the labels | def get_metric_value_by_labels(messages, _metric, _m, metric_suffix):
"""
:param messages: dictionary as metric_name: {labels: {}, value: 10}
:param _metric: dictionary as {labels: {le: '0.001', 'custom': 'value'}}
:param _m: str as metric name
:param metric_suffix: str must be i... |
Extracts MetricFamily objects from the maps generated by parsing the
strings in _extract_metrics_from_string | def _extract_metric_from_map(self, _m, messages, obj_map, obj_help):
"""
Extracts MetricFamily objects from the maps generated by parsing the
strings in _extract_metrics_from_string
"""
_obj = metrics_pb2.MetricFamily()
_obj.name = _m
_obj.type = self.METRIC_TYPES... |
Poll the data from prometheus and return the metrics as a generator. | def scrape_metrics(self, endpoint):
"""
Poll the data from prometheus and return the metrics as a generator.
"""
response = self.poll(endpoint)
try:
# no dry run if no label joins
if not self.label_joins:
self._dry_run = False
e... |
Polls the data from prometheus and pushes them as gauges
`endpoint` is the metrics endpoint to use to poll metrics from Prometheus
Note that if the instance has a 'tags' attribute, it will be pushed
automatically as additional custom tags and added to the metrics | def process(self, endpoint, **kwargs):
"""
Polls the data from prometheus and pushes them as gauges
`endpoint` is the metrics endpoint to use to poll metrics from Prometheus
Note that if the instance has a 'tags' attribute, it will be pushed
automatically as additional custom ta... |
Handle a prometheus metric message according to the following flow:
- search self.metrics_mapper for a prometheus.metric <--> datadog.metric mapping
- call check method with the same name as the metric
- log some info if none of the above worked
`send_histograms_buckets` is ... | def process_metric(self, message, **kwargs):
"""
Handle a prometheus metric message according to the following flow:
- search self.metrics_mapper for a prometheus.metric <--> datadog.metric mapping
- call check method with the same name as the metric
- log some info i... |
Polls the metrics from the prometheus metrics endpoint provided.
Defaults to the protobuf format, but can use the formats specified by
the PrometheusFormat class.
Custom headers can be added to the default headers.
Returns a valid requests.Response, raise requests.HTTPError if the statu... | def poll(self, endpoint, pFormat=PrometheusFormat.PROTOBUF, headers=None):
"""
Polls the metrics from the prometheus metrics endpoint provided.
Defaults to the protobuf format, but can use the formats specified by
the PrometheusFormat class.
Custom headers can be added to the def... |
For each metric in the message, report it as a gauge with all labels as tags
except if a labels dict is passed, in which case keys are label names we'll extract
and corresponding values are tag names we'll use (eg: {'node': 'node'}).
Histograms generate a set of values instead of a unique metri... | def _submit(
self,
metric_name,
message,
send_histograms_buckets=True,
send_monotonic_counter=False,
custom_tags=None,
hostname=None,
):
"""
For each metric in the message, report it as a gauge with all labels as tags
except if a labels... |
If hostname is None, look at label_to_hostname setting | def _get_hostname(self, hostname, metric):
"""
If hostname is None, look at label_to_hostname setting
"""
if hostname is None and self.label_to_hostname is not None:
for label in metric.label:
if label.name == self.label_to_hostname:
return... |
Extracts metrics from a prometheus summary metric and sends them as gauges | def _submit_gauges_from_summary(self, name, metric, custom_tags=None, hostname=None):
"""
Extracts metrics from a prometheus summary metric and sends them as gauges
"""
if custom_tags is None:
custom_tags = []
# summaries do not have a value attribute
val = ge... |
Extracts metrics from a prometheus histogram and sends them as gauges | def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
"""
Extracts metrics from a prometheus histogram and sends them as gauges
"""
if custom_tags is None:
custom_tags = []
# histograms do n... |
See if a personal access token was passed | def get_auth_info(config=None):
"""
See if a personal access token was passed
"""
gh_config = (config or {}).get('github', {})
user = gh_config.get('user') or os.getenv('DD_GITHUB_USER')
token = gh_config.get('token') or os.getenv('DD_GITHUB_TOKEN')
if user and token:
return user, to... |
Fetch the labels from the PR and process the ones related to the changelog. | def get_changelog_types(pr_payload):
"""
Fetch the labels from the PR and process the ones related to the changelog.
"""
changelog_labels = []
for name in get_pr_labels(pr_payload):
if name.startswith(CHANGELOG_LABEL_PREFIX):
# only add the name, e.g. for `changelog/Added` it's j... |
Get the payload for the given PR number. Let exceptions bubble up. | def get_pr(pr_num, config=None, repo=DEFAULT_REPO, raw=False):
"""
Get the payload for the given PR number. Let exceptions bubble up.
"""
response = requests.get(PR_ENDPOINT.format(repo, pr_num), auth=get_auth_info(config))
if raw:
return response
else:
response.raise_for_status... |
Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number. | def parse_pr_numbers(git_log_lines):
"""
Parse PR numbers from commit messages. At GitHub those have the format:
`here is the message (#1234)`
being `1234` the PR number.
"""
prs = []
for line in git_log_lines:
pr_number = parse_pr_number(line)
if pr_number:
... |
Start. Multiple calls have no effect.
Not safe to call from multiple threads at once. | def open(self):
"""Start. Multiple calls have no effect.
Not safe to call from multiple threads at once.
"""
with self._lock:
if self._thread_will_exit:
# If the background thread has read self._stopped as True
# there is a chance that it has ... |
For more info, see: https://tox.readthedocs.io/en/latest/plugins.html
For an example, see: https://github.com/tox-dev/tox-travis | def tox_configure(config):
"""
For more info, see: https://tox.readthedocs.io/en/latest/plugins.html
For an example, see: https://github.com/tox-dev/tox-travis
"""
sections = config._cfg.sections
# Cache these
make_envconfig = None
reader = None
# Default to false so:
# 1. we d... |
Determine if collect_connection_state is set and can effectively run.
If self._collect_cx_state is True and a custom proc_location is provided, the system cannot
run `ss` or `netstat` over a custom proc_location
:param proc_location: str
:return: bool | def _is_collect_cx_state_runnable(self, proc_location):
"""
Determine if collect_connection_state is set and can effectively run.
If self._collect_cx_state is True and a custom proc_location is provided, the system cannot
run `ss` or `netstat` over a custom proc_location
:param ... |
_check_linux can be run inside a container and still collects the network metrics from the host
For that procfs_path can be set to something like "/host/proc"
When a custom procfs_path is set, the collect_connection_state option is ignored | def _check_linux(self, instance):
"""
_check_linux can be run inside a container and still collects the network metrics from the host
For that procfs_path can be set to something like "/host/proc"
When a custom procfs_path is set, the collect_connection_state option is ignored
""... |
Parse the output of conntrack -S
Add the parsed metrics | def _add_conntrack_stats_metrics(self, conntrack_path, tags):
"""
Parse the output of conntrack -S
Add the parsed metrics
"""
try:
output, _, _ = get_subprocess_output(["sudo", conntrack_path, "-S"], self.log)
# conntrack -S sample:
# cpu=0 fou... |
Parse the output of the command that retrieves the connection state (either `ss` or `netstat`)
Returns a dict metric_name -> value | def _parse_linux_cx_state(self, lines, tcp_states, state_col, protocol=None, ip_version=None):
"""
Parse the output of the command that retrieves the connection state (either `ss` or `netstat`)
Returns a dict metric_name -> value
"""
metrics = {}
for _, val in iteritems(s... |
Return a mapping of network metrics by interface. For example:
{ interface:
{'bytes_sent': 0,
'bytes_rcvd': 0,
'bytes_rcvd': 0,
...
}
} | def _parse_solaris_netstat(self, netstat_output):
"""
Return a mapping of network metrics by interface. For example:
{ interface:
{'bytes_sent': 0,
'bytes_rcvd': 0,
'bytes_rcvd': 0,
...
}
}
... |
Gather metrics about connections states and interfaces counters
using psutil facilities | def _check_psutil(self, instance):
"""
Gather metrics about connections states and interfaces counters
using psutil facilities
"""
custom_tags = instance.get('tags', [])
if self._collect_cx_state:
self._cx_state_psutil(tags=custom_tags)
self._cx_count... |
Collect metrics about connections state using psutil | def _cx_state_psutil(self, tags=None):
"""
Collect metrics about connections state using psutil
"""
metrics = defaultdict(int)
tags = [] if tags is None else tags
for conn in psutil.net_connections():
protocol = self._parse_protocol_psutil(conn)
st... |
Collect metrics about interfaces counters using psutil | def _cx_counters_psutil(self, tags=None):
"""
Collect metrics about interfaces counters using psutil
"""
tags = [] if tags is None else tags
for iface, counters in iteritems(psutil.net_io_counters(pernic=True)):
metrics = {
'bytes_rcvd': counters.bytes... |
Returns a string describing the protocol for the given connection
in the form `tcp4`, 'udp4` as in `self.cx_state_gauge` | def _parse_protocol_psutil(self, conn):
"""
Returns a string describing the protocol for the given connection
in the form `tcp4`, 'udp4` as in `self.cx_state_gauge`
"""
protocol = self.PSUTIL_TYPE_MAPPING.get(conn.type, '')
family = self.PSUTIL_FAMILY_MAPPING.get(conn.fam... |
Process the work unit, or wait for sentinel to exit | def run(self):
"""Process the work unit, or wait for sentinel to exit"""
while True:
self.running = True
workunit = self._workq.get()
if is_sentinel(workunit):
# Got sentinel
break
# Run the job / sequence
worku... |
Equivalent of the apply() builtin function. It blocks till
the result is ready. | def apply(self, func, args=(), kwds=dict()):
"""Equivalent of the apply() builtin function. It blocks till
the result is ready."""
return self.apply_async(func, args, kwds).get() |
A parallel equivalent of the map() builtin function. It
blocks till the result is ready.
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks. The
(approximate) size of these chunks can be specified by setting
chunksize to... | def map(self, func, iterable, chunksize=None):
"""A parallel equivalent of the map() builtin function. It
blocks till the result is ready.
This method chops the iterable into a number of chunks which
it submits to the process pool as separate tasks. The
(approximate) size of the... |
An equivalent of itertools.imap().
The chunksize argument is the same as the one used by the
map() method. For very long iterables using a large value for
chunksize can make make the job complete much faster than
using the default value of 1.
Also if chunksize is 1 then the nex... | def imap(self, func, iterable, chunksize=1):
"""
An equivalent of itertools.imap().
The chunksize argument is the same as the one used by the
map() method. For very long iterables using a large value for
chunksize can make make the job complete much faster than
using the... |
The same as imap() except that the ordering of the results
from the returned iterator should be considered
arbitrary. (Only when there is only one worker process is the
order guaranteed to be "correct".) | def imap_unordered(self, func, iterable, chunksize=1):
"""The same as imap() except that the ordering of the results
from the returned iterator should be considered
arbitrary. (Only when there is only one worker process is the
order guaranteed to be "correct".)"""
collector = Uno... |
A variant of the apply() method which returns an
ApplyResult object.
If callback is specified then it should be a callable which
accepts a single argument. When the result becomes ready,
callback is applied to it (unless the call failed). callback
should complete immediately sin... | def apply_async(self, func, args=(), kwds=dict(), callback=None):
"""A variant of the apply() method which returns an
ApplyResult object.
If callback is specified then it should be a callable which
accepts a single argument. When the result becomes ready,
callback is applied to ... |
A variant of the map() method which returns a ApplyResult
object.
If callback is specified then it should be a callable which
accepts a single argument. When the result becomes ready
callback is applied to it (unless the call failed). callback
should complete immediately since o... | def map_async(self, func, iterable, chunksize=None, callback=None):
"""A variant of the map() method which returns a ApplyResult
object.
If callback is specified then it should be a callable which
accepts a single argument. When the result becomes ready
callback is applied to it... |
A variant of the imap() method which returns an ApplyResult
object that provides an iterator (next method(timeout)
available).
If callback is specified then it should be a callable which
accepts a single argument. When the resulting iterator becomes
ready, callback is applied to... | def imap_async(self, func, iterable, chunksize=None, callback=None):
"""A variant of the imap() method which returns an ApplyResult
object that provides an iterator (next method(timeout)
available).
If callback is specified then it should be a callable which
accepts a single arg... |
A variant of the imap_unordered() method which returns an
ApplyResult object that provides an iterator (next
method(timeout) available).
If callback is specified then it should be a callable which
accepts a single argument. When the resulting iterator becomes
ready, callback is ... | def imap_unordered_async(self, func, iterable, chunksize=None, callback=None):
"""A variant of the imap_unordered() method which returns an
ApplyResult object that provides an iterator (next
method(timeout) available).
If callback is specified then it should be a callable which
... |
Stops the worker processes immediately without completing
outstanding work. When the pool object is garbage collected
terminate() will be called immediately. | def terminate(self):
"""Stops the worker processes immediately without completing
outstanding work. When the pool object is garbage collected
terminate() will be called immediately."""
self.close()
# Clearing the job queue
try:
while 1:
self._... |
Create the WorkUnit objects to process and pushes them on the
work queue. Each work unit is meant to process a slice of
iterable of size chunksize. If collector is specified, then
the ApplyResult objects associated with the jobs will notify
collector when their result becomes ready.
... | def _create_sequences(self, func, iterable, chunksize, collector=None):
"""
Create the WorkUnit objects to process and pushes them on the
work queue. Each work unit is meant to process a slice of
iterable of size chunksize. If collector is specified, then
the ApplyResult objects ... |
Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function | def process(self):
"""
Call the function with the args/kwds and tell the ApplyResult
that its result is ready. Correctly handles the exceptions
happening during the execution of the function
"""
try:
result = self._func(*self._args, **self._kwds)
excep... |
Returns the result when it arrives. If timeout is not None and
the result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised an exception
then that exception will be reraised by get(). | def get(self, timeout=None):
"""
Returns the result when it arrives. If timeout is not None and
the result does not arrive within timeout seconds then
TimeoutError is raised. If the remote call raised an exception
then that exception will be reraised by get().
"""
... |
Waits until the result is available or until timeout
seconds pass. | def wait(self, timeout=None):
"""Waits until the result is available or until timeout
seconds pass."""
self._event.wait(timeout)
return self._event.isSet() |
Called by a Job object to tell the result is ready, and
provides the value of this result. The object will become
ready and successful. The collector's notify_ready() method
will be called, and the callback method too | def _set_value(self, value):
"""Called by a Job object to tell the result is ready, and
provides the value of this result. The object will become
ready and successful. The collector's notify_ready() method
will be called, and the callback method too"""
assert not self.ready()
... |
Called by a Job object to tell that an exception occured
during the processing of the function. The object will become
ready but not successful. The collector's notify_ready()
method will be called, but NOT the callback method | def _set_exception(self):
"""Called by a Job object to tell that an exception occured
during the processing of the function. The object will become
ready but not successful. The collector's notify_ready()
method will be called, but NOT the callback method"""
assert not self.ready... |
Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job | def next(self, timeout=None):
"""Return the next result value in the sequence. Raise
StopIteration at the end. Can raise the exception raised by
the Job"""
try:
apply_result = self._collector._get_result(self._idx, timeout)
except IndexError:
# Reset for n... |
Called by the CollectorIterator object to retrieve the
result's values one after another, in the order the results have
become available.
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to wait (in seconds)
for the result ... | def _get_result(self, idx, timeout=None):
"""Called by the CollectorIterator object to retrieve the
result's values one after another, in the order the results have
become available.
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling ... |
Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been processed | def notify_ready(self, apply_result):
"""Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been p... |
Called by the CollectorIterator object to retrieve the
result's values one after another (order defined by the
implementation)
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to wait (in seconds)
for the result at index id... | def _get_result(self, idx, timeout=None):
"""Called by the CollectorIterator object to retrieve the
result's values one after another (order defined by the
implementation)
\param idx The index of the result we want, wrt collector's order
\param timeout integer telling how long to... |
Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been processed | def notify_ready(self, apply_result):
"""Called by the ApplyResult object (already registered via
register_result()) that it is now ready (ie. the Job's result
is available or an exception has been raised).
\param apply_result ApplyResult object telling us that the job
has been p... |
Execute a command over the socket, or raise socket.error.
:Parameters:
- `sock`: a raw socket instance
- `dbname`: name of the database on which to run the command
- `spec`: a command document as a dict, SON, or mapping object
- `slave_ok`: whether to set the SlaveOkay wire protocol bit
... | def command(sock, dbname, spec, slave_ok, is_mongos,
read_preference, codec_options, check=True,
allowable_errors=None, address=None,
check_keys=False, listeners=None, max_bson_size=None,
read_concern=DEFAULT_READ_CONCERN,
parse_write_concern_error=False,
... |
Receive a raw BSON message or raise socket.error. | def receive_message(
sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE):
"""Receive a raw BSON message or raise socket.error."""
header = _receive_data_on_socket(sock, 16)
length = _UNPACK_INT(header[:4])[0]
actual_op = _UNPACK_INT(header[12:])[0]
if operation != actual_op:
... |
See: https://github.com/python/cpython/blob/40ee9a3640d702bce127e9877c82a99ce817f0d1/Lib/socket.py#L691 | def create_connection(self):
"""See: https://github.com/python/cpython/blob/40ee9a3640d702bce127e9877c82a99ce817f0d1/Lib/socket.py#L691"""
err = None
try:
for res in socket.getaddrinfo(self._server, self._port, 0, self._sock_type):
af, socktype, proto, canonname, sa =... |
Helper function that wraps :func:`json.dumps`.
Recursive function that handles all BSON types including
:class:`~bson.binary.Binary` and :class:`~bson.code.Code`.
:Parameters:
- `json_options`: A :class:`JSONOptions` instance used to modify the
encoding of MongoDB Extended JSON types. Defaul... | def dumps(obj, *args, **kwargs):
"""Helper function that wraps :func:`json.dumps`.
Recursive function that handles all BSON types including
:class:`~bson.binary.Binary` and :class:`~bson.code.Code`.
:Parameters:
- `json_options`: A :class:`JSONOptions` instance used to modify the
encodin... |
Helper function that wraps :func:`json.loads`.
Automatically passes the object_hook for BSON type conversion.
Raises ``TypeError``, ``ValueError``, ``KeyError``, or
:exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.
:Parameters:
- `json_options`: A :class:`JSONOptions` instance use... | def loads(s, *args, **kwargs):
"""Helper function that wraps :func:`json.loads`.
Automatically passes the object_hook for BSON type conversion.
Raises ``TypeError``, ``ValueError``, ``KeyError``, or
:exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON.
:Parameters:
- `json_options... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.