text
stringlengths
81
112k
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) ...
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. If neither `--sinc...
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: ...
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 d...
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_k...
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 ...
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 c...
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: f...
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. def add(self, original_index, operation): """Add an operation to this Run instance. ...
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): ...
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',...
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 colla...
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)...
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_typ...
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": [], ...
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_versio...
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, ...
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 execut...
Update one document matching the selector. :Parameters: - `update` (dict): the update operations to apply def update_one(self, update): """Update one document matching the selector. :Parameters: - `update` (dict): the update operations to apply """ self.__b...
Replace one entire document matching the selector criteria. :Parameters: - `replacement` (dict): the replacement document def replace_one(self, replacement): """Replace one entire document matching the selector criteria. :Parameters: - `replacement` (dict): the replacement...
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. :Parameters: - `selector` (dict): the selection criteria for update and remove operations. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. This option is only supported on Mon...
Execute all provided operations. :Parameters: - write_concern (optional): the write concern for this bulk execution. def execute(self, write_concern=None): """Execute all provided operations. :Parameters: - write_concern (optional): the write concern for this b...
Return a list of Servers matching selector, or time out. :Parameters: - `selector`: function that takes a list of Servers and returns a subset of them. - `server_selection_timeout` (optional): maximum seconds to wait. If not provided, the default value common.SERVER_...
Like select_servers, but choose a random server if several match. def select_server(self, selector, server_selection_timeout=None, address=None): """Like select_servers, but choose a random server if several match.""" return random.choic...
Process a new ServerDescription after an ismaster call completes. def on_change(self, server_description): """Process a new ServerDescription after an ismaster call completes.""" # We do no I/O holding the lock. with self._lock: # Any monitored server was definitely in the topology ...
Return primary's address or None. def get_primary(self): """Return primary's address or None.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: topology_type = self._description.topology_type if topology_type != TOPOLOGY_TYPE.Repl...
Return set of replica set member addresses. def _get_replica_set_members(self, selector): """Return set of replica set member addresses.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: topology_type = self._description.topology_type ...
Wake all monitors, wait for at least one to check its server. def request_check_all(self, wait_time=5): """Wake all monitors, wait for at least one to check its server.""" with self._lock: self._request_check_all() self._condition.wait(wait_time)
Clear our pool for a server, mark it Unknown, and check it soon. def reset_server_and_request_check(self, address): """Clear our pool for a server, mark it Unknown, and check it soon.""" with self._lock: self._reset_server(address) self._request_check(address)
Clear pools and terminate monitors. Topology reopens on demand. def close(self): """Clear pools and terminate monitors. Topology reopens on demand.""" with self._lock: for server in self._servers.values(): server.close() # Mark all servers Unknown. s...
Clear our pool for a server and mark it Unknown. Hold the lock when calling this. Does *not* request an immediate check. def _reset_server(self, address): """Clear our pool for a server and mark it Unknown. Hold the lock when calling this. Does *not* request an immediate check. """ ...
Wake one monitor. Hold the lock when calling this. def _request_check(self, address): """Wake one monitor. Hold the lock when calling this.""" server = self._servers.get(address) # "server" is None if another thread removed it from the topology. if server: server.request_ch...
Sync our Servers from TopologyDescription.server_descriptions. Hold the lock while calling this. def _update_servers(self): """Sync our Servers from TopologyDescription.server_descriptions. Hold the lock while calling this. """ for address, sd in self._description.server_descr...
Format an error message if server selection fails. Hold the lock when calling this. def _error_message(self, selector): """Format an error message if server selection fails. Hold the lock when calling this. """ is_replica_set = self._description.topology_type in ( ...
Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. def init_instance(self, key): """ Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. """ with self._mor_lock: if key not i...
Store a Mor object in the cache with the given name. If the key is not in the cache, raises a KeyError. def set_mor(self, key, name, mor): """ Store a Mor object in the cache with the given name. If the key is not in the cache, raises a KeyError. """ with self._mor_lock:...
Return the Mor object identified by `name` for the given instance key. If the key is not in the cache, raises a KeyError. If there's no Mor with the given name, raises a MorNotFoundError. def get_mor(self, key, name): """ Return the Mor object identified by `name` for the given instance...
Store a list of metric identifiers for the given instance key and Mor object name. If the key is not in the cache, raises a KeyError. If the Mor object is not in the cache, raises a MorNotFoundError def set_metrics(self, key, name, metrics): """ Store a list of metric identifier...
Generator returning all the mors in the cache for the given instance key. def mors(self, key): """ Generator returning all the mors in the cache for the given instance key. """ with self._mor_lock: for k, v in iteritems(self._mor.get(key, {})): yield k, v
Generator returning as many dictionaries containing `batch_size` Mor objects as needed to iterate all the content of the cache. This has to be iterated twice, like: for batch in cache.mors_batch('key', 100): for name, mor in batch: # use the Mor object he...
Remove all the items in the cache for the given key that are older than ttl seconds. If the key is not in the cache, raises a KeyError. def purge(self, key, ttl): """ Remove all the items in the cache for the given key that are older than ttl seconds. If the key is not i...
Takes a metric formatted by Envoy and splits it into a unique metric name. Returns the unique metric name, a list of tags, and the name of the submission method. Example: 'listener.0.0.0.0_80.downstream_cx_total' -> ('listener.downstream_cx_total', ['address:0.0.0.0_80'], 'count') def pars...
Iterates over histogram data, yielding metric-value pairs. def parse_histogram(metric, histogram): """Iterates over histogram data, yielding metric-value pairs.""" for match in HISTOGRAM.finditer(histogram): percentile, value = match.groups() value = float(value) if not isnan(value): ...
Put data in GridFS as a new file. Equivalent to doing:: try: f = new_file(**kwargs) f.write(data) finally: f.close() `data` can be either an instance of :class:`str` (:class:`bytes` in python 3) or a file-like object providing a :m...
Delete a file from GridFS by ``"_id"``. Deletes all data belonging to the file with ``"_id"``: `file_id`. .. warning:: Any processes/threads reading from the file while this method is executing will likely see an invalid/corrupt file. Care should be taken to avoid concurr...
Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single :class:`~gridfs.grid_file.GridOut`, or ``None`` if no matching file is found. For example:: file = fs....
Check if a file exists in this instance of :class:`GridFS`. The file to check for can be specified by the value of its ``_id`` key, or by passing in a query document. A query document can be passed in as dictionary, or by using keyword arguments. Thus, the following three calls are equi...
Opens a Stream that the application can write the contents of the file to. The user must specify the filename, and can choose to add any additional information in the metadata field of the file document or modify the chunk size. For example:: my_db = MongoClient().tes...
Opens a Stream that the application can write the contents of the file to. The user must specify the file id and filename, and can choose to add any additional information in the metadata field of the file document or modify the chunk size. For example:: my_db = Mongo...
Uploads a user file to a GridFS bucket with a custom file id. Reads the contents of the user file from `source` and uploads it to the file `filename`. Source can be a string or file-like object. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) fil...
Opens a Stream from which the application can read the contents of the stored file specified by file_id. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # get _id of file to read. file_id = fs.upload_from_stream("test_file", "data I want to sto...
Downloads the contents of the stored file specified by file_id and writes the contents to `destination`. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to read file_id = fs.upload_from_stream("test_file", "data I want to stor...
Given an file_id, delete this stored file's files collection document and associated chunks from a GridFS bucket. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to delete file_id = fs.upload_from_stream("test_file", "data I w...
Opens a Stream from which the application can read the contents of `filename` and optional `revision`. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) grid_out = fs.open_download_stream_by_name("test_file") contents = grid_out.read() R...
List active or available environments. def ls(checks): """List active or available environments.""" if checks: checks = sorted(get_testable_checks() & set(checks)) for check in checks: envs = get_available_tox_envs(check, e2e_only=True) if envs: echo_su...
Hit a given http url and return the stats lines def _fetch_url_data(self, url, username, password, verify, custom_headers): ''' Hit a given http url and return the stats lines ''' # Try to fetch data from the stats URL auth = (username, password) url = "%s%s" % (url, STATS_URL) ...
Hit a given stats socket and return the stats lines def _fetch_socket_data(self, parsed_url): ''' Hit a given stats socket and return the stats lines ''' self.log.debug("Fetching haproxy stats from socket: %s" % parsed_url.geturl()) if parsed_url.scheme == 'tcp': sock = socket.soc...
Main data-processing loop. For each piece of useful data, we'll either save a metric, save an event or both. def _process_data( self, data, collect_aggregates_only, process_events, url=None, collect_status_metrics=False, collect_status_metrics_by_host=Fal...
Adds spct if relevant, adds service def _update_data_dict(self, data_dict, back_or_front): """ Adds spct if relevant, adds service """ data_dict['back_or_front'] = back_or_front # The percentage of used sessions based on 'scur' and 'slim' if 'slim' in data_dict and 'scur...
if collect_aggregates_only, we process only the aggregates else we process all except Services.BACKEND def _should_process(self, data_dict, collect_aggregates_only): """ if collect_aggregates_only, we process only the aggregates else we process all except Services.BACKEND ...
Use a named regexp on the current service_name to create extra tags Example HAProxy service name: be_edge_http_sre-prod_elk Example named regexp: be_edge_http_(?P<team>[a-z]+)\\-(?P<env>[a-z]+)_(?P<app>.*) Resulting tags: ['team:sre','env:prod','app:elk'] def _tag_from_regex(self, tags_regex, s...
Try to normalize the HAProxy status as one of the statuses defined in `ALL_STATUSES`, if it can't be matched return the status as-is in a tag-friendly format ex: 'UP 1/2' -> 'up' 'no check' -> 'no_check' def _normalize_status(status): """ Try to normalize the HAProxy status ...
Data is a dictionary related to one host (one line) extracted from the csv. It should look like: {'pxname':'dogweb', 'svname':'i-4562165', 'scur':'42', ...} def _process_metrics( self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None, active_tag=None ...
Main event processing loop. An event will be created for a service status change. Service checks on the server side can be used to provide the same functionality def _process_event(self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None): ''' Main event p...
Report a service check, tagged by the service and the backend. Statuses are defined in `STATUS_TO_SERVICE_CHECK` mapping. def _process_service_check( self, data, url, tag_by_host=False, services_incl_filter=None, services_excl_filter=None, custom_tags=None ): ''' Report a service check,...
All servers matching one tag set. A tag set is a dict. A server matches if its tags are a superset: A server tagged {'a': '1', 'b': '2'} matches the tag set {'a': '1'}. The empty tag set {} matches any server. def apply_single_tag_set(tag_set, selection): """All servers matching one tag set. A t...
All servers match a list of tag sets. tag_sets is a list of dicts. The empty tag set {} matches any server, and may be provided at the end of the list as a fallback. So [{'a': 'value'}, {}] expresses a preference for servers tagged {'a': 'value'}, but accepts any server if none matches the first pr...
Validates metadata.csv files If `check` is specified, only the check will be validated, otherwise all metadata files in the repo will be. def metadata(check): """Validates metadata.csv files If `check` is specified, only the check will be validated, otherwise all metadata files in the repo will b...
Build and return a mechanism specific credentials tuple. def _build_credentials_tuple(mech, source, user, passwd, extra): """Build and return a mechanism specific credentials tuple. """ user = _unicode(user) if user is not None else None password = passwd if passwd is None else _unicode(passwd) if ...
Split a scram response into key, value pairs. def _parse_scram_response(response): """Split a scram response into key, value pairs.""" return dict(item.split(b"=", 1) for item in response.split(b","))
Authenticate using SCRAM-SHA-1. def _authenticate_scram_sha1(credentials, sock_info): """Authenticate using SCRAM-SHA-1.""" username = credentials.username password = credentials.password source = credentials.source # Make local _hmac = hmac.HMAC _sha1 = sha1 user = username.encode("u...
Authenticate using GSSAPI. def _authenticate_gssapi(credentials, sock_info): """Authenticate using GSSAPI. """ if not HAVE_KERBEROS: raise ConfigurationError('The "kerberos" module must be ' 'installed to use GSSAPI authentication.') try: username = cre...
Authenticate using SASL PLAIN (RFC 4616) def _authenticate_plain(credentials, sock_info): """Authenticate using SASL PLAIN (RFC 4616) """ source = credentials.source username = credentials.username password = credentials.password payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8')...
Authenticate using CRAM-MD5 (RFC 2195) def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we us...
Authenticate using MONGODB-X509. def _authenticate_x509(credentials, sock_info): """Authenticate using MONGODB-X509. """ query = SON([('authenticate', 1), ('mechanism', 'MONGODB-X509')]) if credentials.username is not None: query['user'] = credentials.username elif sock_inf...
Authenticate using MONGODB-CR. def _authenticate_mongo_cr(credentials, sock_info): """Authenticate using MONGODB-CR. """ source = credentials.source username = credentials.username password = credentials.password # Get a nonce response = sock_info.command(source, {'getnonce': 1}) nonce ...
Authenticate sock_info. def authenticate(credentials, sock_info): """Authenticate sock_info.""" mechanism = credentials.mechanism auth_func = _AUTH_MAP.get(mechanism) auth_func(credentials, sock_info)
Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric def parse_metric_family(self, response, scraper_config): """ Parse the Met...
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 ...
Poll the data from prometheus and return the metrics as a generator. def scrape_metrics(self, scraper_config): """ Poll the data from prometheus and return the metrics as a generator. """ response = self.poll(scraper_config) try: # no dry run if no label joins ...
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, scraper_conf...
Handle a prometheus metric according to the following flow: - search scraper_config['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 `metric_transformers` is...
Custom headers can be added to the default headers. Returns a valid requests.Response, raise requests.HTTPError if the status code of the requests.Response isn't valid - see response.raise_for_status() The caller needs to close the requests.Response :param endpoint: string url endpoin...
For each sample in the metric, 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 metric...
If hostname is None, look at label_to_hostname setting def _get_hostname(self, hostname, sample, scraper_config): """ If hostname is None, look at label_to_hostname setting """ if ( hostname is None and scraper_config['label_to_hostname'] is not None ...
Extracts metrics from a prometheus histogram and sends them as gauges def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None): """ Extracts metrics from a prometheus histogram and sends them as gauges """ for sample in metric.samples: val ...
`buf` is a readable file-like object returns a tuple: (metrics, tags, mode, version) def parse_stat(self, buf): """ `buf` is a readable file-like object returns a tuple: (metrics, tags, mode, version) """ metrics = [] buf.seek(0) # Check the version line...
Parse `mntr` command's content. `buf` is a readable file-like object Returns: a tuple (metrics, mode) if mode == 'inactive', metrics will be None def parse_mntr(self, buf): """ Parse `mntr` command's content. `buf` is a readable file-like object Returns: a tupl...
Take a single health check string, return (OSD name, percentage used) def _osd_pct_used(self, health): """Take a single health check string, return (OSD name, percentage used)""" # Full string looks like: osd.2 is full at 95% # Near full string: osd.1 is near full at 94% pct = re.compil...
Add a new son manipulator to this database. **DEPRECATED** - `add_son_manipulator` is deprecated. .. versionchanged:: 3.0 Deprecated add_son_manipulator. def add_son_manipulator(self, manipulator): """Add a new son manipulator to this database. **DEPRECATED** - `add_son_man...
**DEPRECATED**: All incoming SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 def incoming_manipulators(self): """**DEPRECATED**: All incoming SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 "...
**DEPRECATED**: All incoming SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 def incoming_copying_manipulators(self): """**DEPRECATED**: All incoming SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. vers...
**DEPRECATED**: All outgoing SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 def outgoing_manipulators(self): """**DEPRECATED**: All outgoing SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 "...
**DEPRECATED**: All outgoing SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 def outgoing_copying_manipulators(self): """**DEPRECATED**: All outgoing SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. vers...
Get a :class:`~pymongo.collection.Collection` with the given name and options. Useful for creating a :class:`~pymongo.collection.Collection` with different codec options, read preference, and/or write concern from this :class:`Database`. >>> db.read_preference Prima...
Get a Collection instance with the default settings. def _collection_default_options(self, name, **kargs): """Get a Collection instance with the default settings.""" wc = (self.write_concern if self.write_concern.acknowledged else WriteConcern()) return self.get_collection( ...
Create a new :class:`~pymongo.collection.Collection` in this database. Normally collection creation is automatic. This method should only be used to specify options on creation. :class:`~pymongo.errors.CollectionInvalid` will be raised if the collection already exists. ...