INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Run the Docker check for one instance. | def check(self, instance):
"""Run the Docker check for one instance."""
if not self.init_success:
# Initialization can fail if cgroups are not ready or docker daemon is down. So we retry if needed
# https://github.com/DataDog/dd-agent/issues/1896
self.init()
... |
List all the containers from the API filter and count them. | def _get_and_count_containers(self, custom_cgroups=False, healthchecks=False):
"""List all the containers from the API, filter and count them."""
# Querying the size of containers is slow, we don't do it at each run
must_query_size = self.collect_container_size and self._latest_size_query == 0
... |
Generate the tags for a given entity ( container or image ) according to a list of tag names. | def _get_tags(self, entity=None, tag_type=None):
"""Generate the tags for a given entity (container or image) according to a list of tag names."""
# Start with custom tags
tags = list(self.custom_tags)
# Collect pod names as tags on kubernetes
if Platform.is_k8s() and KubeUtil.P... |
Extra tag information from the API result ( containers or images ). Cache extracted tags inside the entity object. | def _extract_tag_value(self, entity, tag_name):
"""Extra tag information from the API result (containers or images).
Cache extracted tags inside the entity object.
"""
if tag_name not in TAG_EXTRACTORS:
self.warning("{0} isn't a supported tag".format(tag_name))
re... |
Check if a container is excluded according to the filter rules. | def _is_container_excluded(self, container):
"""Check if a container is excluded according to the filter rules.
Requires _filter_containers to run first.
"""
container_name = DockerUtil.container_name_extractor(container)[0]
return container_name in self._filtered_containers |
Send health service checks for containers. | def _send_container_healthcheck_sc(self, containers_by_id):
"""Send health service checks for containers."""
for container in containers_by_id.itervalues():
healthcheck_tags = self._get_tags(container, HEALTHCHECK)
match = False
for tag in healthcheck_tags:
... |
Report container count per state | def _report_container_count(self, containers_by_id):
"""Report container count per state"""
m_func = FUNC_MAP[GAUGE][self.use_histogram]
per_state_count = defaultdict(int)
filterlambda = lambda ctr: not self._is_container_excluded(ctr)
containers = list(filter(filterlambda, con... |
Report volume count per state ( dangling or not ) | def _report_volume_count(self):
"""Report volume count per state (dangling or not)"""
m_func = FUNC_MAP[GAUGE][self.use_histogram]
attached_volumes = self.docker_util.client.volumes(filters={'dangling': False})
dangling_volumes = self.docker_util.client.volumes(filters={'dangling': True... |
Find container network metrics by looking at/ proc/ $PID/ net/ dev of the container process. | def _report_net_metrics(self, container, tags):
"""Find container network metrics by looking at /proc/$PID/net/dev of the container process."""
if self._disable_net_metrics:
self.log.debug("Network metrics are disabled. Skipping")
return
proc_net_file = os.path.join(cont... |
Get the list of events. | def _get_events(self):
"""Get the list of events."""
events, changed_container_ids = self.docker_util.get_events()
if not self._disable_net_metrics:
self._invalidate_network_mapping_cache(events)
if changed_container_ids and self._service_discovery:
get_sd_backend... |
Create the actual event to submit from a list of similar docker events | def _create_dd_event(self, events, image, c_tags, priority='Normal'):
"""Create the actual event to submit from a list of similar docker events"""
if not events:
return
max_timestamp = 0
status = defaultdict(int)
status_change = []
for ev, c_name in events:
... |
Report metrics about the volume space usage | def _report_disk_stats(self):
"""Report metrics about the volume space usage"""
stats = {
'docker.data.used': None,
'docker.data.total': None,
'docker.data.free': None,
'docker.metadata.used': None,
'docker.metadata.total': None,
'd... |
Cast the disk stats to float and convert them to bytes | def _format_disk_metrics(self, metrics):
"""Cast the disk stats to float and convert them to bytes"""
for name, raw_val in metrics.iteritems():
if raw_val:
match = DISK_STATS_RE.search(raw_val)
if match is None or len(match.groups()) != 2:
... |
Calculate a percentage of used disk space for data and metadata | def _calc_percent_disk_stats(self, stats):
"""Calculate a percentage of used disk space for data and metadata"""
mtypes = ['data', 'metadata']
percs = {}
for mtype in mtypes:
used = stats.get('docker.{0}.used'.format(mtype))
total = stats.get('docker.{0}.total'.fo... |
Find a specific cgroup file containing metrics to extract. | def _get_cgroup_from_proc(self, cgroup, pid, filename):
"""Find a specific cgroup file, containing metrics to extract."""
params = {
"file": filename,
}
return DockerUtil.find_cgroup_from_proc(self._mountpoints, pid, cgroup, self.docker_util._docker_root) % (params) |
Parse a cgroup pseudo file for key/ values. | def _parse_cgroup_file(self, stat_file):
"""Parse a cgroup pseudo file for key/values."""
self.log.debug("Opening cgroup file: %s" % stat_file)
try:
with open(stat_file, 'r') as fp:
if 'blkio' in stat_file:
return self._parse_blkio_metrics(fp.read(... |
Parse the blkio metrics. | def _parse_blkio_metrics(self, stats):
"""Parse the blkio metrics."""
metrics = {
'io_read': 0,
'io_write': 0,
}
for line in stats:
if 'Read' in line:
metrics['io_read'] += int(line.split()[2])
if 'Write' in line:
... |
Crawl/ proc to find container PIDs and add them to containers_by_id. | def _crawl_container_pids(self, container_dict, custom_cgroups=False):
"""Crawl `/proc` to find container PIDs and add them to `containers_by_id`."""
proc_path = os.path.join(self.docker_util._docker_root, 'proc')
pid_dirs = [_dir for _dir in os.listdir(proc_path) if _dir.isdigit()]
if ... |
Start an environment. | def start(ctx, check, env, agent, dev, base, env_vars):
"""Start an environment."""
if not file_exists(get_tox_file(check)):
abort('`{}` is not a testable check.'.format(check))
base_package = None
if base:
core_dir = os.path.expanduser(ctx.obj.get('core', ''))
if not dir_exists... |
Generic request handler for OpenStack API requests Raises specialized Exceptions for commonly encountered error codes | def _make_request(self, url, headers, params=None):
"""
Generic request handler for OpenStack API requests
Raises specialized Exceptions for commonly encountered error codes
"""
self.logger.debug("Request URL, Headers and Params: %s, %s, %s", url, headers, params)
# Chec... |
Returns all projects in the domain | def get_projects(self):
"""
Returns all projects in the domain
"""
url = urljoin(self.keystone_endpoint, "{}/{}".format(DEFAULT_KEYSTONE_API_VERSION, "projects"))
try:
r = self._make_request(url, self.headers)
return r.get('projects', [])
except E... |
Parse user identity out of init_config | def _get_user_identity(user):
"""
Parse user identity out of init_config
To guarantee a uniquely identifiable user, expects
{"user": {"name": "my_username", "password": "my_password",
"domain": {"id": "my_domain_id"}
}
}
"""
if... |
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog | def _get_neutron_endpoint(cls, json_resp):
"""
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service
Sends a CRITICAL service check when none are found registered in the Catalog
"""
valid_endpoint = cls._get_valid_endpoint(json_resp, ... |
Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog | def _get_nova_endpoint(cls, json_resp):
"""
Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog
"""
valid_endpoint = c... |
Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog | def _get_valid_endpoint(resp, name, entry_type):
"""
Parse the service catalog returned by the Identity API for an endpoint matching
the Nova service with the requested version
Sends a CRITICAL service check when no viable candidates are found in the Catalog
"""
catalog =... |
This command will: | def dep():
"""
This command will:
* Verify the uniqueness of dependency versions across all checks.
* Verify all the dependencies are pinned.
* Verify the embedded Python environment defined in the base check and requirements
listed in every integration are compatible.
"""
failed = Fa... |
Show metric info from a Prometheus endpoint. | def info(endpoint):
"""Show metric info from a Prometheus endpoint.
\b
Example:
$ ddev meta prom info :8080/_status/vars
"""
endpoint = sanitize_endpoint(endpoint)
metrics = parse_metrics(endpoint)
num_metrics = len(metrics)
num_gauge = 0
num_counter = 0
num_histogram = 0
... |
Interactively parse metric info from a Prometheus endpoint. | def parse(ctx, endpoint, check, here):
"""Interactively parse metric info from a Prometheus endpoint."""
if here:
output_dir = os.getcwd()
else:
output_dir = path_join(get_root(), check)
if not dir_exists(output_dir):
abort(
'Check `{check}` does not exist... |
Add this operation to the _Bulk instance bulkobj. | def _add_to_bulk(self, bulkobj):
"""Add this operation to the _Bulk instance `bulkobj`."""
bulkobj.add_delete(self._filter, 0, collation=self._collation) |
Add this operation to the _Bulk instance bulkobj. | def _add_to_bulk(self, bulkobj):
"""Add this operation to the _Bulk instance `bulkobj`."""
bulkobj.add_replace(self._filter, self._doc, self._upsert,
collation=self._collation) |
Add this operation to the _Bulk instance bulkobj. | def _add_to_bulk(self, bulkobj):
"""Add this operation to the _Bulk instance `bulkobj`."""
bulkobj.add_update(self._filter, self._doc, False, self._upsert,
collation=self._collation) |
Load a private key and the corresponding certificate. The certfile string must be the path to a single file in PEM format containing the certificate as well as any number of CA certificates needed to establish the certificate s authenticity. The keyfile string if present must point to a file containing the private key.... | def load_cert_chain(self, certfile, keyfile=None):
"""Load a private key and the corresponding certificate. The certfile
string must be the path to a single file in PEM format containing the
certificate as well as any number of CA certificates needed to
establish the certificate's authen... |
Wrap an existing Python socket sock and return an ssl. SSLSocket object. | def wrap_socket(self, sock, server_side=False,
do_handshake_on_connect=True,
suppress_ragged_eofs=True, dummy=None):
"""Wrap an existing Python socket sock and return an ssl.SSLSocket
object.
"""
return ssl.wrap_socket(sock, keyfile=self._keyfile,
... |
Parse the binary buffer in input searching for Prometheus messages of type MetricFamily [ 0 ] delimited by a varint32 [ 1 ]. | def parse_metric_family(buf):
"""
Parse the binary buffer in input, searching for Prometheus messages
of type MetricFamily [0] delimited by a varint32 [1].
[0] https://github.com/prometheus/client_model/blob/086fe7ca28bde6cec2acd5223423c1475a362858/metrics.proto#L76-%20%20L81 # noqa: E501
[1] http... |
Convert duplicate keys values to lists. | def multidict(ordered_pairs):
"""Convert duplicate keys values to lists."""
# read all values into lists
d = defaultdict(list)
for k, v in ordered_pairs:
d[k].append(v)
# unpack lists that have only 1 item
dict_copy = deepcopy(d)
for k, v in iteritems(dict_copy):
if len(v) ==... |
Generator yielding one Package instance for every corresponing line in a requirements file | def read_packages(reqs_file):
"""
Generator yielding one Package instance for every corresponing line in a
requirements file
"""
for line in stream_file_lines(reqs_file):
line = line.strip()
if not line.startswith(('#', '--hash')):
match = DEP_PATTERN.match(line)
... |
Dump the packages in the catalog in a requirements file | def write_packages(self, reqs_file):
"""
Dump the packages in the catalog in a requirements file
"""
write_file_lines(reqs_file, ('{}\n'.format(package) for package in self.packages)) |
Add a Package to the catalog for the given check | def add_package(self, check_name, package):
"""
Add a Package to the catalog for the given check
"""
self._package_set.add(package)
package_data = self._packages[package.name]
self._checks_deps[check_name].append(package)
# Versions
if package.version:
... |
Publish metrics for a subcontainer and handle filtering on tags | def _update_container_metrics(self, instance, subcontainer, kube_labels):
"""Publish metrics for a subcontainer and handle filtering on tags"""
tags = list(instance.get('tags', [])) # add support for custom tags
if len(subcontainer.get('aliases', [])) >= 1:
# The first alias seems ... |
Reports the number of running pods on this node tagged by service and creator | def _update_pods_metrics(self, instance, pods):
"""
Reports the number of running pods on this node, tagged by service and creator
We go though all the pods, extract tags then count them by tag list, sorted and
serialized in a pipe-separated string (it is an illegar character for tags)
... |
Process kube events and send ddog events The namespace filtering is done here instead of KubeEventRetriever to avoid interfering with service discovery | def _update_kube_events(self, instance, pods_list, event_items):
"""
Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery
"""
node_ip, node_name = self.kubeutil.get_node_inf... |
calls kubeutil. refresh_leader and compares the resulting leader status with the previous one. If it changed update the event collection logic | def refresh_leader_status(self, instance):
"""
calls kubeutil.refresh_leader and compares the resulting
leader status with the previous one.
If it changed, update the event collection logic
"""
if not self.leader_candidate:
return
leader_status = self... |
Main metric fetching method | def _read_rrd(self, rrd_path, hostname, device_name, tags):
''' Main metric fetching method '''
metric_count = 0
try:
info = self._get_rrd_info(rrd_path)
except Exception:
# Unable to read RRD file, ignore it
self.log.exception("Unable to read RRD fil... |
Fetch metadata about each RRD in this Cacti DB returning a list of tuples of ( hostname device_name rrd_path ) | def _fetch_rrd_meta(self, connection, rrd_path_root, whitelist, field_names, tags):
''' Fetch metadata about each RRD in this Cacti DB, returning a list of
tuples of (hostname, device_name, rrd_path)
'''
def _in_whitelist(rrd):
path = rrd.replace('<path_rra>/', '')
... |
Format a cacti metric name into a Datadog - friendly name | def _format_metric_name(self, m_name, cfunc):
''' Format a cacti metric name into a Datadog-friendly name '''
try:
aggr = CFUNC_TO_AGGR[cfunc]
except KeyError:
aggr = cfunc.lower()
try:
m_name = CACTI_TO_DD[m_name]
if aggr != 'avg':
... |
PERF_100NSEC_TIMER | def calculate_perf_100nsec_timer(previous, current, property_name):
"""
PERF_100NSEC_TIMER
https://technet.microsoft.com/en-us/library/cc728274(v=ws.10).aspx
"""
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestamp_Sys100NS... |
PERF_COUNTER_BULK_COUNT | def calculate_perf_counter_bulk_count(previous, current, property_name):
"""
PERF_COUNTER_BULK_COUNT
https://technet.microsoft.com/en-us/library/cc757486(v=ws.10).aspx
"""
n0 = previous[property_name]
n1 = current[property_name]
d0 = previous["Timestamp_Sys100NS"]
d1 = current["Timestam... |
PERF_COUNTER_100NS_QUEUELEN_TYPE | def calculate_perf_counter_100ns_queuelen_type(previous, current, property_name):
"""
PERF_COUNTER_100NS_QUEUELEN_TYPE
Average length of a queue to a resource over time in 100 nanosecond units.
https://msdn.microsoft.com/en-us/library/aa392905(v=vs.85).aspx
Formula (n1 - n0) / (d1 - d0)
"""
... |
Return whether the hostname and port combination was already seen | def _server_known(cls, host, port):
"""
Return whether the hostname and port combination was already seen
"""
with PostgreSql._known_servers_lock:
return (host, port) in PostgreSql._known_servers |
Store the host/ port combination for this server | def _set_server_known(cls, host, port):
"""
Store the host/port combination for this server
"""
with PostgreSql._known_servers_lock:
PostgreSql._known_servers.add((host, port)) |
Add NEWER_92_METRICS to the default set of COMMON_METRICS when server version is 9. 2 or later. | def _get_instance_metrics(self, key, db, database_size_metrics, collect_default_db):
"""
Add NEWER_92_METRICS to the default set of COMMON_METRICS when server
version is 9.2 or later.
Store the list of metrics in the check instance to avoid rebuilding it at
every collection cycl... |
Use either COMMON_BGW_METRICS or COMMON_BGW_METRICS + NEWER_92_BGW_METRICS depending on the postgres version. Uses a dictionnary to save the result for each instance | def _get_bgw_metrics(self, key, db):
"""Use either COMMON_BGW_METRICS or COMMON_BGW_METRICS + NEWER_92_BGW_METRICS
depending on the postgres version.
Uses a dictionnary to save the result for each instance
"""
# Extended 9.2+ metrics if needed
metrics = self.bgw_metrics.g... |
Use COMMON_ARCHIVER_METRICS to read from pg_stat_archiver as defined in 9. 4 ( first version to have this table ). Uses a dictionary to save the result for each instance | def _get_archiver_metrics(self, key, db):
"""Use COMMON_ARCHIVER_METRICS to read from pg_stat_archiver as
defined in 9.4 (first version to have this table).
Uses a dictionary to save the result for each instance
"""
# While there's only one set for now, prepare for future additio... |
Use either REPLICATION_METRICS_10 REPLICATION_METRICS_9_1 or REPLICATION_METRICS_9_1 + REPLICATION_METRICS_9_2 depending on the postgres version. Uses a dictionnary to save the result for each instance | def _get_replication_metrics(self, key, db):
""" Use either REPLICATION_METRICS_10, REPLICATION_METRICS_9_1, or
REPLICATION_METRICS_9_1 + REPLICATION_METRICS_9_2, depending on the
postgres version.
Uses a dictionnary to save the result for each instance
"""
metrics = self... |
Use ACTIVITY_METRICS_LT_8_3 or ACTIVITY_METRICS_8_3 or ACTIVITY_METRICS_9_2 depending on the postgres version in conjunction with ACTIVITY_QUERY_10 or ACTIVITY_QUERY_LT_10. Uses a dictionnary to save the result for each instance | def _get_activity_metrics(self, key, db):
""" Use ACTIVITY_METRICS_LT_8_3 or ACTIVITY_METRICS_8_3 or ACTIVITY_METRICS_9_2
depending on the postgres version in conjunction with ACTIVITY_QUERY_10 or ACTIVITY_QUERY_LT_10.
Uses a dictionnary to save the result for each instance
"""
m... |
Builds a dictionary from relations configuration while maintaining compatibility | def _build_relations_config(self, yamlconfig):
"""Builds a dictionary from relations configuration while maintaining compatibility
"""
config = {}
for element in yamlconfig:
if isinstance(element, str):
config[element] = {'relation_name': element, 'schemas': [... |
Query pg_stat_ * for various metrics If relations is not an empty list gather per - relation metrics on top of that. If custom_metrics is not an empty list gather custom metrics defined in postgres. yaml | def _collect_stats(
self,
key,
db,
instance_tags,
relations,
custom_metrics,
collect_function_metrics,
collect_count_metrics,
collect_activity_metrics,
collect_database_size_metrics,
collect_default_db,
interface_error,
... |
Get and memoize connections to instances | def get_connection(self, key, host, port, user, password, dbname, ssl, connect_fct, tags, use_cached=True):
"""Get and memoize connections to instances"""
if key in self.dbs and use_cached:
return self.dbs[key]
elif host != "" and user != "":
try:
if host... |
Given a list of custom_queries execute each query and parse the result for metrics | def _get_custom_queries(self, db, tags, custom_queries, programming_error):
"""
Given a list of custom_queries, execute each query and parse the result for metrics
"""
for custom_query in custom_queries:
metric_prefix = custom_query.get('metric_prefix')
if not met... |
The XML will have Stat Nodes and Nodes that contain the metrics themselves This code recursively goes through each Stat Node to properly setup tags where each Stat will have a different tag key depending on the context. | def process_stats(self, stats, prefix, metric_categories, nested_tags, tags, recursion_level=0):
"""
The XML will have Stat Nodes and Nodes that contain the metrics themselves
This code recursively goes through each Stat Node to properly setup tags
where each Stat will have a different t... |
Convert duration dur to microseconds. | def _to_micros(dur):
"""Convert duration 'dur' to microseconds."""
if hasattr(dur, 'total_seconds'):
return int(dur.total_seconds() * 10e5)
# Python 2.6
return dur.microseconds + (dur.seconds + dur.days * 24 * 3600) * 1000000 |
Validate event listeners | def _validate_event_listeners(option, listeners):
"""Validate event listeners"""
if not isinstance(listeners, Sequence):
raise TypeError("%s must be a list or tuple" % (option,))
for listener in listeners:
if not isinstance(listener, _EventListener):
raise TypeError("Listeners fo... |
Register a global event listener. | def register(listener):
"""Register a global event listener.
:Parameters:
- `listener`: A subclasses of :class:`CommandListener`,
:class:`ServerHeartbeatListener`, :class:`ServerListener`, or
:class:`TopologyListener`.
"""
if not isinstance(listener, _EventListener):
raise... |
List of registered event listeners. | def event_listeners(self):
"""List of registered event listeners."""
return (self.__command_listeners[:],
self.__server_heartbeat_listeners[:],
self.__server_listeners[:],
self.__topology_listeners[:]) |
Publish a CommandStartedEvent to all command listeners. | def publish_command_start(self, command, database_name,
request_id, connection_id, op_id=None):
"""Publish a CommandStartedEvent to all command listeners.
:Parameters:
- `command`: The command document.
- `database_name`: The name of the database this c... |
Publish a CommandSucceededEvent to all command listeners. | def publish_command_success(self, duration, reply, command_name,
request_id, connection_id, op_id=None):
"""Publish a CommandSucceededEvent to all command listeners.
:Parameters:
- `duration`: The command duration as a datetime.timedelta.
- `reply`: T... |
Publish a CommandFailedEvent to all command listeners. | def publish_command_failure(self, duration, failure, command_name,
request_id, connection_id, op_id=None):
"""Publish a CommandFailedEvent to all command listeners.
:Parameters:
- `duration`: The command duration as a datetime.timedelta.
- `failure`: ... |
Publish a ServerHeartbeatStartedEvent to all server heartbeat listeners. | def publish_server_heartbeat_started(self, connection_id):
"""Publish a ServerHeartbeatStartedEvent to all server heartbeat
listeners.
:Parameters:
- `connection_id`: The address (host/port pair) of the connection.
"""
event = ServerHeartbeatStartedEvent(connection_id)
... |
Publish a ServerHeartbeatSucceededEvent to all server heartbeat listeners. | def publish_server_heartbeat_succeeded(self, connection_id, duration,
reply):
"""Publish a ServerHeartbeatSucceededEvent to all server heartbeat
listeners.
:Parameters:
- `connection_id`: The address (host/port pair) of the connection.
... |
Publish a ServerHeartbeatFailedEvent to all server heartbeat listeners. | def publish_server_heartbeat_failed(self, connection_id, duration, reply):
"""Publish a ServerHeartbeatFailedEvent to all server heartbeat
listeners.
:Parameters:
- `connection_id`: The address (host/port pair) of the connection.
- `duration`: The execution time of the event i... |
Publish a ServerOpeningEvent to all server listeners. | def publish_server_opened(self, server_address, topology_id):
"""Publish a ServerOpeningEvent to all server listeners.
:Parameters:
- `server_address`: The address (host/port pair) of the server.
- `topology_id`: A unique identifier for the topology this server
is a part of... |
Publish a ServerClosedEvent to all server listeners. | def publish_server_closed(self, server_address, topology_id):
"""Publish a ServerClosedEvent to all server listeners.
:Parameters:
- `server_address`: The address (host/port pair) of the server.
- `topology_id`: A unique identifier for the topology this server
is a part of.... |
Publish a ServerDescriptionChangedEvent to all server listeners. | def publish_server_description_changed(self, previous_description,
new_description, server_address,
topology_id):
"""Publish a ServerDescriptionChangedEvent to all server listeners.
:Parameters:
- `previous_d... |
Publish a TopologyOpenedEvent to all topology listeners. | def publish_topology_opened(self, topology_id):
"""Publish a TopologyOpenedEvent to all topology listeners.
:Parameters:
- `topology_id`: A unique identifier for the topology this server
is a part of.
"""
event = TopologyOpenedEvent(topology_id)
for subscribe... |
Publish a TopologyClosedEvent to all topology listeners. | def publish_topology_closed(self, topology_id):
"""Publish a TopologyClosedEvent to all topology listeners.
:Parameters:
- `topology_id`: A unique identifier for the topology this server
is a part of.
"""
event = TopologyClosedEvent(topology_id)
for subscribe... |
Publish a TopologyDescriptionChangedEvent to all topology listeners. | def publish_topology_description_changed(self, previous_description,
new_description, topology_id):
"""Publish a TopologyDescriptionChangedEvent to all topology listeners.
:Parameters:
- `previous_description`: The previous topology description.
... |
root@postfix:/ opt/ datadog - agent/ agent/ checks. d# postqueue - p ---- Queue ID ----- -- Size -- --- Arrival Time ---- -- Sender/ Recipient ------ 3xWyLP6Nmfz23fk 367 Tue Aug 15 16: 17: 33 root@postfix. devnull. home ( deferred transport ) alice@crypto. io | def _get_postqueue_stats(self, postfix_config_dir, tags):
# get some intersting configuratin values from postconf
pc_output, _, _ = get_subprocess_output(['postconf', 'mail_version'], self.log, False)
postfix_version = pc_output.strip('\n').split('=')[1].strip()
pc_output, _, _ = get_su... |
Generates a markdown file containing the list of integrations shipped in a given Agent release. Agent version numbers are derived inspecting tags on integrations - core so running this tool might provide unexpected results if the repo is not up to date with the Agent release process. | def integrations(since, to, write, force):
"""
Generates a markdown file containing the list of integrations shipped in a
given Agent release. Agent version numbers are derived inspecting tags on
`integrations-core` so running this tool might provide unexpected results
if the repo is not up to date ... |
Query pgbouncer for various metrics | def _collect_stats(self, db, instance_tags):
"""Query pgbouncer for various metrics
"""
metric_scope = [self.STATS_METRICS, self.POOLS_METRICS, self.DATABASES_METRICS]
try:
with db.cursor(cursor_factory=pgextras.DictCursor) as cursor:
for scope in metric_sco... |
Get the params to pass to psycopg2. connect () based on passed - in vals from yaml settings file | def _get_connect_kwargs(self, host, port, user, password, database_url):
"""
Get the params to pass to psycopg2.connect() based on passed-in vals
from yaml settings file
"""
if database_url:
return {'dsn': database_url}
if not host:
raise CheckExc... |
Get and memoize connections to instances | def _get_connection(self, key, host='', port='', user='', password='', database_url='', tags=None, use_cached=True):
"Get and memoize connections to instances"
if key in self.dbs and use_cached:
return self.dbs[key]
try:
connect_kwargs = self._get_connect_kwargs(
... |
Returns the number of seconds between the current time and the set renew time. It can be negative if the leader election is running late. | def seconds_until_renew(self):
"""
Returns the number of seconds between the current time
and the set renew time. It can be negative if the
leader election is running late.
"""
delta = self.renew_time - datetime.now(self.renew_time.tzinfo)
return delta.total_secon... |
Create and return an error document. | def _make_error(index, code, errmsg, operation):
"""Create and return an error document.
"""
return {
_UINDEX: index,
_UCODE: code,
_UERRMSG: errmsg,
_UOP: operation
} |
Merge a result from a legacy opcode into the full results. | def _merge_legacy(run, full_result, result, index):
"""Merge a result from a legacy opcode into the full results.
"""
affected = result.get('n', 0)
errmsg = result.get("errmsg", result.get("err", ""))
if errmsg:
# wtimeout is not considered a hard failure in
# MongoDB 2.6 so don't t... |
Merge a group of results from write commands into the full result. | def _merge_command(run, full_result, results):
"""Merge a group of results from write commands into the full result.
"""
for offset, result in results:
affected = result.get("n", 0)
if run.op_type == _INSERT:
full_result["nInserted"] += affected
elif run.op_type == _DE... |
Add an operation to this Run instance. | def add(self, original_index, operation):
"""Add an operation to this Run instance.
:Parameters:
- `original_index`: The original index of this operation
within a larger bulk operation.
- `operation`: The operation document.
"""
self.index_map.append(orig... |
Add an insert document to the list of ops. | def add_insert(self, document):
"""Add an insert document to the list of ops.
"""
validate_is_document_type("document", document)
# Generate ObjectId client side.
if not (isinstance(document, RawBSONDocument) or '_id' in document):
document['_id'] = ObjectId()
... |
Create a replace document and add it to the list of ops. | def add_replace(self, selector, replacement, upsert=False,
collation=None):
"""Create a replace document and add it to the list of ops.
"""
validate_ok_for_replace(replacement)
cmd = SON([('q', selector), ('u', replacement),
('multi', False), ('upse... |
Create a delete document and add it to the list of ops. | def add_delete(self, selector, limit, collation=None):
"""Create a delete document and add it to the list of ops.
"""
cmd = SON([('q', selector), ('limit', limit)])
collation = validate_collation_or_none(collation)
if collation is not None:
self.uses_collation = True
... |
Generate batches of operations batched by type of operation in the order ** provided **. | def gen_ordered(self):
"""Generate batches of operations, batched by type of
operation, in the order **provided**.
"""
run = None
for idx, (op_type, operation) in enumerate(self.ops):
if run is None:
run = _Run(op_type)
elif run.op_type != ... |
Generate batches of operations batched by type of operation in arbitrary order. | def gen_unordered(self):
"""Generate batches of operations, batched by type of
operation, in arbitrary order.
"""
operations = [_Run(_INSERT), _Run(_UPDATE), _Run(_DELETE)]
for idx, (op_type, operation) in enumerate(self.ops):
operations[op_type].add(idx, operation)
... |
Execute using write commands. | def execute_command(self, sock_info, generator, write_concern):
"""Execute using write commands.
"""
# nModified is only reported for write commands, not legacy ops.
full_result = {
"writeErrors": [],
"writeConcernErrors": [],
"nInserted": 0,
... |
Execute all operations returning no results ( w = 0 ). | def execute_no_results(self, sock_info, generator):
"""Execute all operations, returning no results (w=0).
"""
# Cannot have both unacknowledged write and bypass document validation.
if self.bypass_doc_val and sock_info.max_wire_version >= 4:
raise OperationFailure("Cannot se... |
Execute using legacy wire protocol ops. | def execute_legacy(self, sock_info, generator, write_concern):
"""Execute using legacy wire protocol ops.
"""
coll = self.collection
full_result = {
"writeErrors": [],
"writeConcernErrors": [],
"nInserted": 0,
"nUpserted": 0,
"n... |
Execute operations. | def execute(self, write_concern):
"""Execute operations.
"""
if not self.ops:
raise InvalidOperation('No operations to execute')
if self.executed:
raise InvalidOperation('Bulk operations can '
'only be executed once.')
se... |
Update one document matching the selector. | def update_one(self, update):
"""Update one document matching the selector.
:Parameters:
- `update` (dict): the update operations to apply
"""
self.__bulk.add_update(self.__selector,
update, multi=False, upsert=True,
... |
Replace one entire document matching the selector criteria. | def replace_one(self, replacement):
"""Replace one entire document matching the selector criteria.
:Parameters:
- `replacement` (dict): the replacement document
"""
self.__bulk.add_replace(self.__selector, replacement, upsert=True,
collation=sel... |
Remove a single document matching the selector criteria. | def remove_one(self):
"""Remove a single document matching the selector criteria.
"""
self.__bulk.add_delete(self.__selector, _DELETE_ONE,
collation=self.__collation) |
Remove all documents matching the selector criteria. | def remove(self):
"""Remove all documents matching the selector criteria.
"""
self.__bulk.add_delete(self.__selector, _DELETE_ALL,
collation=self.__collation) |
Specify selection criteria for bulk operations. | def find(self, selector, collation=None):
"""Specify selection criteria for bulk operations.
:Parameters:
- `selector` (dict): the selection criteria for update
and remove operations.
- `collation` (optional): An instance of
:class:`~pymongo.collation.Collati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.