INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Publish a TopologyOpenedEvent to all topology listeners. :Parameters: - `topology_id`: A unique identifier for the topology this server is a part of.
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. :Parameters: - `topology_id`: A unique identifier for the topology this server is a part of.
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. :Parameters: - `previous_description`: The previous topology description. - `new_description`: The new topology description. - `topology_id`: A unique identifier for the topology this server is a part of.
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) ...
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. If neither `--sinc...
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. :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. :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. :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.__bulk.add_update(self.__selector, update, multi=False, upsert=True, ...
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 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. :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...
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...
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 bulk execution. """ if write_concern is not None: validate_is_mapping("write_concern", write_concern) ...
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_...
def select_servers(self, selector, server_selection_timeout=None, address=None): """Return a list of Servers matching selector, or time out. :Parameters: - `selector`: function that takes a list of Servers and returns ...
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.choice(self.select_servers(selector, ...
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 description # once. Check if it's still in the descript...
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.ReplicaSetWithPrimary: ...
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 if topology_type not in (TOPOLOGY_TYPE.R...
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. self._description = self._description.reset() self._up...
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. """ server = self._servers.get(address) # "server" is None if another thread removed it from the topology. if se...
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_check()
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_descriptions().items(): if address not in self._servers: monitor = self._settings.mo...
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 ( TOPOLOGY_TYPE.ReplicaSetWithPrimary, TOPOLOGY_TYPE.ReplicaSetNoPrimary) i...
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 in self._mor: self._mor[key] = {}
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: self._mor[key][name] = mor self._mor[key][name]['creation_time'] = time.time()
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 key. If the key is not in the cache, raises a KeyError. If there's no Mor with the given name, raises a MorNotFoundError. """ with self._mor_lock: mors = self._...
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 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 """ with self._mor...
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...
def mors_batch(self, key, batch_size): """ 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...
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 in the cache, raises a KeyError. """ mors_to_purge = [] now = time.time() with self._mor_lock: # Don't change ...
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 parse_metric(metric, metric_mapping=METRIC_TREE): """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.dow...
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): try: yield metric + PERCENTILE_SU...
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...
def put(self, data, **kwargs): """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 pyth...
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...
def delete(self, file_id): """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....
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....
def find_one(self, filter=None, *args, **kwargs): """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 ...
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...
def exists(self, document_or_id=None, **kwargs): """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...
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...
def open_upload_stream(self, filename, chunk_size_bytes=None, metadata=None): """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 fie...
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...
def open_upload_stream_with_id( self, file_id, filename, chunk_size_bytes=None, metadata=None): """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 t...
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...
def upload_from_stream_with_id(self, file_id, filename, source, chunk_size_bytes=None, metadata=None): """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`. Sou...
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...
def open_download_stream(self, file_id): """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...
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...
def download_to_stream(self, file_id, destination): """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 fi...
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...
def delete(self, file_id): """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.upl...
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...
def open_download_stream_by_name(self, filename, revision=-1): """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_s...
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_success('{}:'.format(check)) ...
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) custom_headers.update(headers(self.agentConfig))...
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.socket(socket.AF_INET, socket.SOCK_STREAM) s...
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=False, tag_service_check_by_host=False, services_incl_filter=None, services_excl_filter=None, ...
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' in data_dict: try: ...
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 """ if collect_aggregates_only: if self._is_aggregate(data_dict): return T...
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, service_name): """ 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: [...
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 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' """ formatted_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 ): """ Data is a dictionary related to one host (one line) extracted from the csv. It should look like: {'pxname':'dogweb', 'svname':'i-45621...
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 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 ''' ...
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, tagged by the service and the backend. Statuses are defined in `STATUS_TO_SERVICE_CHECK` mapping. ''' cust...
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 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 tags_match(server_tags): ...
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...
def apply_tag_sets(tag_sets, selection): """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 acc...
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 be. """ metric_sources = get_metric_sources() if check: if check not in metric_sources: abort('Metadata file `{}` do...
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 mech == 'GSSAPI': properties = extra.get('authmech...
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("utf-8").replace(b"=", b"=3D").repl...
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 = credentials.username pa...
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') cmd = SON([('saslStart', 1), ...
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 use for MONGODB-CR passwd = _password_...
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_info.max_wire_version < 5: ra...
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 = response['nonce'] key = _a...
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 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 """ ...
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, scraper_config): """ 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 :p...
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 if not scraper_config['label_joins']: scraper_co...
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_config, metric_transformers=None): """ 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 a...
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...
def process_metric(self, metric, scraper_config, metric_transformers=None): """ 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 ...
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...
def poll(self, scraper_config, headers=None): """ 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 ...
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...
def submit_openmetric(self, metric_name, metric, scraper_config, hostname=None): """ 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'l...
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 and scraper_config['label_to_hostname'] in sample[self.S...
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 = sample[self.SAMPLE_VALUE] if not self._is_value_valid(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 to make sure we parse the rest of the # body correctly. Particularly, the Connections...
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 tuple (metrics, mode) if mode == 'inactive', metrics will be None """ buf.seek(0) first = buf.readline() # First is version string or error ...
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.compile(r'\d+%').findall(health) osd = re.compile(r'osd.\d+').findall...
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_manipulator` is deprecated. .. versionchanged:: 3.0 Deprecated add_son_manipulator. """ warnings.warn("add_son_manipulator is deprecated", ...
**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 """ warnings.warn("Database.incoming_manipulators() is deprecated", DeprecationWarning, stacklevel=2) ...
**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. .. versionadded:: 2.0 """ warnings.warn("Database.incoming_copying_manipulators() is deprecated", DeprecationWa...
**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 """ warnings.warn("Database.outgoing_manipulators() is deprecated", DeprecationWarning, stacklevel=2) ...
**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. .. versionadded:: 2.0 """ warnings.warn("Database.outgoing_copying_manipulators() is deprecated", DeprecationWa...