INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Set a metric
def _set_metric(self, metric_name, metric_type, value, tags=None): """ Set a metric """ if metric_type == self.GAUGE: self.gauge(metric_name, value, tags=tags) else: self.log.error('Metric type "{}" unknown'.format(metric_type))
Query the given URL and return the JSON response
def _rest_request_to_json(self, instance, url, object_path, query_params, tags=None): """ Query the given URL and return the JSON response """ if object_path: url = self._join_url_dir(url, object_path) # Add query_params as arguments if query_params: ...
Join a URL with multiple directories
def _join_url_dir(cls, url, *args): """ Join a URL with multiple directories """ for path in args: url = url.rstrip('/') + '/' url = urljoin(url, path.lstrip('/')) return url
Add $readPreference to spec when appropriate.
def _maybe_add_read_preference(spec, read_preference): """Add $readPreference to spec when appropriate.""" mode = read_preference.mode tag_sets = read_preference.tag_sets max_staleness = read_preference.max_staleness # Only add $readPreference if it's something other than primary to avoid # prob...
Convert a legacy write result to write commmand format.
def _convert_write_result(operation, command, result): """Convert a legacy write result to write commmand format.""" # Based on _merge_legacy from bulk.py affected = result.get("n", 0) res = {"ok": 1, "n": affected} errmsg = result.get("errmsg", result.get("err", "")) if errmsg: # The w...
Generate an explain command document.
def _gen_explain_command( coll, spec, projection, skip, limit, batch_size, options, read_concern): """Generate an explain command document.""" cmd = _gen_find_command( coll, spec, projection, skip, limit, batch_size, options) if read_concern.level: return SON([('explain', cmd...
Generate a find command document.
def _gen_find_command(coll, spec, projection, skip, limit, batch_size, options, read_concern=DEFAULT_READ_CONCERN, collation=None): """Generate a find command document.""" cmd = SON([('find', coll)]) if '$query' in spec: cmd.update([(_MODIFIERS[key], val) ...
Generate a getMore command document.
def _gen_get_more_command(cursor_id, coll, batch_size, max_await_time_ms): """Generate a getMore command document.""" cmd = SON([('getMore', cursor_id), ('collection', coll)]) if batch_size: cmd['batchSize'] = batch_size if max_await_time_ms is not None: cmd['maxTimeMS'] =...
Data to send to do a lastError.
def __last_error(namespace, args): """Data to send to do a lastError. """ cmd = SON([("getlasterror", 1)]) cmd.update(args) splitns = namespace.split('.', 1) return query(0, splitns[0] + '.$cmd', 0, -1, cmd, None, DEFAULT_CODEC_OPTIONS)
Takes message data and adds a message header based on the operation.
def __pack_message(operation, data): """Takes message data and adds a message header based on the operation. Returns the resultant message string. """ request_id = _randint() message = struct.pack("<i", 16 + len(data)) message += struct.pack("<i", request_id) message += _ZERO_32 # response...
Get an ** insert ** message.
def insert(collection_name, docs, check_keys, safe, last_error_args, continue_on_error, opts): """Get an **insert** message.""" options = 0 if continue_on_error: options += 1 data = struct.pack("<i", options) data += bson._make_c_string(collection_name) encoded = [bson.BSON.en...
Get an ** update ** message.
def update(collection_name, upsert, multi, spec, doc, safe, last_error_args, check_keys, opts): """Get an **update** message. """ options = 0 if upsert: options += 1 if multi: options += 2 data = _ZERO_32 data += bson._make_c_string(collection_name) data += st...
Get a ** query ** message.
def query(options, collection_name, num_to_skip, num_to_return, query, field_selector, opts, check_keys=False): """Get a **query** message. """ data = struct.pack("<I", options) data += bson._make_c_string(collection_name) data += struct.pack("<i", num_to_skip) data += struct.pack("<i"...
Get a ** delete ** message.
def delete(collection_name, spec, safe, last_error_args, opts, flags=0): """Get a **delete** message. `opts` is a CodecOptions. `flags` is a bit vector that may contain the SingleRemove flag or not: http://docs.mongodb.org/meta-driver/latest/legacy/mongodb-wire-protocol/#op-delete """ ...
Get a ** killCursors ** message.
def kill_cursors(cursor_ids): """Get a **killCursors** message. """ data = _ZERO_32 data += struct.pack("<i", len(cursor_ids)) for cursor_id in cursor_ids: data += struct.pack("<q", cursor_id) return __pack_message(2007, data)
Execute a batch of insert update or delete commands.
def _do_batched_write_command(namespace, operation, command, docs, check_keys, opts, ctx): """Execute a batch of insert, update, or delete commands. """ max_bson_size = ctx.max_bson_size max_write_batch_size = ctx.max_write_batch_size # Max BSON object size + 16k - 2 by...
Return a find command document for this query.
def as_command(self): """Return a find command document for this query. Should be called *after* get_message. """ if '$explain' in self.spec: self.name = 'explain' return _gen_explain_command( self.coll, self.spec, self.fields, self.ntoskip, ...
Get a query message possibly setting the slaveOk bit.
def get_message(self, set_slave_ok, is_mongos, use_cmd=False): """Get a query message, possibly setting the slaveOk bit.""" if set_slave_ok: # Set the slaveOk bit. flags = self.flags | 4 else: flags = self.flags ns = _UJOIN % (self.db, self.coll) ...
Return a getMore command document for this query.
def as_command(self): """Return a getMore command document for this query.""" return _gen_get_more_command(self.cursor_id, self.coll, self.ntoreturn, self.max_await_time_ms), self.db
Get a getmore message.
def get_message(self, dummy0, dummy1, use_cmd=False): """Get a getmore message.""" ns = _UJOIN % (self.db, self.coll) if use_cmd: ns = _UJOIN % (self.db, "$cmd") spec = self.as_command()[0] return query(0, ns, 0, -1, spec, None, self.codec_options) ...
A proxy for SocketInfo. legacy_write that handles event publishing.
def legacy_write(self, request_id, msg, max_doc_size, acknowledged, docs): """A proxy for SocketInfo.legacy_write that handles event publishing. """ if self.publish: duration = datetime.datetime.now() - self.start_time cmd = self._start(request_id, docs) start...
A proxy for SocketInfo. write_command that handles event publishing.
def write_command(self, request_id, msg, docs): """A proxy for SocketInfo.write_command that handles event publishing. """ if self.publish: duration = datetime.datetime.now() - self.start_time self._start(request_id, docs) start = datetime.datetime.now() ...
Publish a CommandStartedEvent.
def _start(self, request_id, docs): """Publish a CommandStartedEvent.""" cmd = self.command.copy() cmd[self.field] = docs self.listeners.publish_command_start( cmd, self.db_name, request_id, self.sock_info.address, self.op_id) return cmd
Publish a CommandSucceededEvent.
def _succeed(self, request_id, reply, duration): """Publish a CommandSucceededEvent.""" self.listeners.publish_command_success( duration, reply, self.name, request_id, self.sock_info.address, self.op_id)
Publish a CommandFailedEvent.
def _fail(self, request_id, failure, duration): """Publish a CommandFailedEvent.""" self.listeners.publish_command_failure( duration, failure, self.name, request_id, self.sock_info.address, self.op_id)
Get the machine portion of an ObjectId.
def _machine_bytes(): """Get the machine portion of an ObjectId. """ machine_hash = hashlib.md5() if PY3: # gethostname() returns a unicode string in python 3.x # while update() requires a byte string. machine_hash.update(socket.gethostname().encode()) else: # Calling...
Create a dummy ObjectId instance with a specific generation time.
def from_datetime(cls, generation_time): """Create a dummy ObjectId instance with a specific generation time. This method is useful for doing range queries on a field containing :class:`ObjectId` instances. .. warning:: It is not safe to insert a document containing an Objec...
Checks if a oid string is valid or not.
def is_valid(cls, oid): """Checks if a `oid` string is valid or not. :Parameters: - `oid`: the object id to validate .. versionadded:: 2.3 """ if not oid: return False try: ObjectId(oid) return True except (InvalidI...
Generate a new value for this ObjectId.
def __generate(self): """Generate a new value for this ObjectId. """ # 4 bytes current time oid = struct.pack(">i", int(time.time())) # 3 bytes machine oid += ObjectId._machine_bytes # 2 bytes pid oid += struct.pack(">H", os.getpid() % 0xFFFF) ...
Validate and use the given id for this ObjectId.
def __validate(self, oid): """Validate and use the given id for this ObjectId. Raises TypeError if id is not an instance of (:class:`basestring` (:class:`str` or :class:`bytes` in python 3), ObjectId) and InvalidId if it is not a valid ObjectId. :Parameters: -...
Get the master address from the instance configuration
def _get_master_address(self, instance): """ Get the master address from the instance configuration """ master_address = instance.get(MASTER_ADDRESS) if master_address is None: master_address = instance.get(DEPRECATED_MASTER_ADDRESS) if master_address: ...
Get the request address build with proxy if necessary
def _get_request_url(self, instance, url): """ Get the request address, build with proxy if necessary """ parsed = urlparse(url) _url = url if not (parsed.netloc and parsed.scheme) and is_affirmative(instance.get('spark_proxy_enabled', False)): master_address...
Determine what mode was specified
def _get_running_apps(self, instance, requests_config): """ Determine what mode was specified """ tags = instance.get('tags', []) if tags is None: tags = [] master_address = self._get_master_address(instance) # Get the cluster name from the instance co...
Return a dictionary of { app_id: ( app_name tracking_url ) } for the running Spark applications
def _standalone_init(self, spark_master_address, pre_20_mode, requests_config, tags): """ Return a dictionary of {app_id: (app_name, tracking_url)} for the running Spark applications """ metrics_json = self._rest_request_to_json( spark_master_address, SPARK_MASTER_STATE_PATH,...
Return a dictionary of { app_id: ( app_name tracking_url ) } for running Spark applications.
def _mesos_init(self, instance, master_address, requests_config, tags): """ Return a dictionary of {app_id: (app_name, tracking_url)} for running Spark applications. """ running_apps = {} metrics_json = self._rest_request_to_json( master_address, MESOS_MASTER_APP_PAT...
Return a dictionary of { app_id: ( app_name tracking_url ) } for running Spark applications.
def _yarn_init(self, rm_address, requests_config, tags): """ Return a dictionary of {app_id: (app_name, tracking_url)} for running Spark applications. """ running_apps = self._yarn_get_running_spark_apps(rm_address, requests_config, tags) # Report success after gathering all met...
Return the application URL from the app info page on the Spark master. Due to a bug we need to parse the HTML manually because we cannot fetch JSON data from HTTP interface.
def _get_standalone_app_url(self, app_id, spark_master_address, requests_config, tags): """ Return the application URL from the app info page on the Spark master. Due to a bug, we need to parse the HTML manually because we cannot fetch JSON data from HTTP interface. """ a...
Return a dictionary of { app_id: ( app_name tracking_url ) } for running Spark applications.
def _yarn_get_running_spark_apps(self, rm_address, requests_config, tags): """ Return a dictionary of {app_id: (app_name, tracking_url)} for running Spark applications. The `app_id` returned is that of the YARN application. This will eventually be mapped into a Spark application ID. ...
Traverses the Spark application master in YARN to get a Spark application ID.
def _get_spark_app_ids(self, running_apps, requests_config, tags): """ Traverses the Spark application master in YARN to get a Spark application ID. Return a dictionary of {app_id: (app_name, tracking_url)} for Spark applications """ spark_apps = {} for app_id, (app_name...
Get metrics for each Spark job.
def _spark_job_metrics(self, instance, running_apps, addl_tags, requests_config): """ Get metrics for each Spark job. """ for app_id, (app_name, tracking_url) in iteritems(running_apps): base_url = self._get_request_url(instance, tracking_url) response = self._re...
Get metrics for each Spark executor.
def _spark_executor_metrics(self, instance, running_apps, addl_tags, requests_config): """ Get metrics for each Spark executor. """ for app_id, (app_name, tracking_url) in iteritems(running_apps): base_url = self._get_request_url(instance, tracking_url) response ...
Get metrics for each Spark RDD.
def _spark_rdd_metrics(self, instance, running_apps, addl_tags, requests_config): """ Get metrics for each Spark RDD. """ for app_id, (app_name, tracking_url) in iteritems(running_apps): base_url = self._get_request_url(instance, tracking_url) response = self._re...
Get metrics for each application streaming statistics.
def _spark_streaming_statistics_metrics(self, instance, running_apps, addl_tags, requests_config): """ Get metrics for each application streaming statistics. """ for app_id, (app_name, tracking_url) in iteritems(running_apps): try: base_url = self._get_request...
Set a metric
def _set_metric(self, metric_name, metric_type, value, tags=None): """ Set a metric """ if tags is None: tags = [] if metric_type == GAUGE: self.gauge(metric_name, value, tags=tags) elif metric_type == COUNT: self.count(metric_name, val...
Query the given URL and return the response
def _rest_request(self, url, object_path, service_name, requests_config, tags, *args, **kwargs): """ Query the given URL and return the response """ service_check_tags = ['url:%s' % self._get_url_base(url)] + tags if object_path: url = self._join_url_dir(url, object_...
Query the given URL and return the JSON response
def _rest_request_to_json(self, address, object_path, service_name, requests_config, tags, *args, **kwargs): """ Query the given URL and return the JSON response """ response = self._rest_request(address, object_path, service_name, requests_config, tags, *args, **kwargs) try: ...
Return the base of a URL
def _get_url_base(cls, url): """ Return the base of a URL """ s = urlsplit(url) return urlunsplit([s.scheme, s.netloc, '', '', ''])
This parses tags from a dn designator. They look like this: topology/ pod - 1/ node - 101/ sys/ phys - [ eth1/ 6 ]/ CDeqptMacsectxpkts5min
def parse_capacity_tags(dn): """ This parses tags from a dn designator. They look like this: topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min """ tags = [] pod = get_pod_from_dn(dn) if pod: tags.append("fabric_pod_id:{}".format(pod)) node = get_node_from_dn(dn) ...
This grabs the event tags from the dn designator. They look like this: uni/ tn - DataDog/ ap - DtDg - AP1 - EcommerceApp/ epg - DtDg - Ecomm/ HDl2IngrPktsAg1h
def get_event_tags_from_dn(dn): """ This grabs the event tags from the dn designator. They look like this: uni/tn-DataDog/ap-DtDg-AP1-EcommerceApp/epg-DtDg-Ecomm/HDl2IngrPktsAg1h """ tags = [] node = get_node_from_dn(dn) if node: tags.append("node:" + node) app = get_app_from_dn(...
This parses the hostname from a dn designator. They look like this: topology/ pod - 1/ node - 101/ sys/ phys - [ eth1/ 6 ]/ CDeqptMacsectxpkts5min
def get_hostname_from_dn(dn): """ This parses the hostname from a dn designator. They look like this: topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min """ pod = get_pod_from_dn(dn) node = get_node_from_dn(dn) if pod and node: return "pod-{}-node-{}".format(pod, node) ...
the json objects look like this: { objType: { attributes: {... } } It always has the attributes nested below the object type This helper provides a way of getting at the attributes
def get_attributes(obj): """ the json objects look like this: { "objType": { "attributes": { ... } } It always has the attributes nested below the object type This helper provides a way of getting at the attributes """ if not obj or type(obj) is not dict: re...
When a counter is reset don t send a zero because it will look bad on the graphs This checks if the zero makes sense or not
def check_metric_can_be_zero(metric_name, metric_value, json_attributes): """ When a counter is reset, don't send a zero because it will look bad on the graphs This checks if the zero makes sense or not """ if "last" in metric_name.lower(): return True if not metric_value: return...
Create scaffolding for a new integration.
def create(ctx, name, integration_type, location, non_interactive, quiet, dry_run): """Create scaffolding for a new integration.""" repo_choice = ctx.obj['repo_choice'] root = resolve_path(location) if location else get_root() path_sep = os.path.sep integration_dir = os.path.join(root, normalize_pa...
Freezes any mutable object including dictionaries and lists for hashing. Accepts nested dictionaries.
def freeze(o): """ Freezes any mutable object including dictionaries and lists for hashing. Accepts nested dictionaries. """ if isinstance(o, (tuple, list)): return tuple(sorted(freeze(e) for e in o)) if isinstance(o, dict): return tuple(sorted((k, freeze(v)) for k, v in iterite...
Converts a decimal. Decimal to BID ( high bits low bits ).
def _decimal_to_128(value): """Converts a decimal.Decimal to BID (high bits, low bits). :Parameters: - `value`: An instance of decimal.Decimal """ with decimal.localcontext(_DEC128_CTX) as ctx: value = ctx.create_decimal(value) if value.is_infinite(): return _NINF if value.is...
Returns an instance of: class: decimal. Decimal for this: class: Decimal128.
def to_decimal(self): """Returns an instance of :class:`decimal.Decimal` for this :class:`Decimal128`. """ high = self.__high low = self.__low sign = 1 if (high & _SIGN) else 0 if (high & _SNAN) == _SNAN: return decimal.Decimal((sign, (), 'N')) ...
Create an instance of: class: Decimal128 from Binary Integer Decimal string.
def from_bid(cls, value): """Create an instance of :class:`Decimal128` from Binary Integer Decimal string. :Parameters: - `value`: 16 byte string (128-bit IEEE 754-2008 decimal floating point in Binary Integer Decimal (BID) format). """ if not isinstance(va...
Compile regex strings from queue_tag_re option and return list of compiled regex/ tag pairs
def _compile_tag_re(self): """ Compile regex strings from queue_tag_re option and return list of compiled regex/tag pairs """ queue_tag_list = [] for regex_str, tags in iteritems(self._queue_tag_re): try: queue_tag_list.append([re.compile(regex_str), [...
Determine the server type from an ismaster response.
def _get_server_type(doc): """Determine the server type from an ismaster response.""" if not doc.get('ok'): return SERVER_TYPE.Unknown if doc.get('isreplicaset'): return SERVER_TYPE.RSGhost elif doc.get('setName'): if doc.get('hidden'): return SERVER_TYPE.RSOther ...
List of hosts passives and arbiters known to this server.
def all_hosts(self): """List of hosts, passives, and arbiters known to this server.""" return set(imap(common.clean_node, itertools.chain( self._doc.get('hosts', []), self._doc.get('passives', []), self._doc.get('arbiters', []))))
Set up the gitlab_runner instance so it can be used in OpenMetricsBaseCheck
def _create_gitlab_runner_prometheus_instance(self, instance, init_config): """ Set up the gitlab_runner instance so it can be used in OpenMetricsBaseCheck """ # Mapping from Prometheus metrics names to Datadog ones # For now it's a 1:1 mapping allowed_metrics = init_conf...
Get namenode beans data from JMX endpoint
def _get_jmx_data(self, instance, jmx_address, tags): """ Get namenode beans data from JMX endpoint """ response = self._rest_request_to_json( instance, jmx_address, self.JMX_PATH, {'qry': self.HDFS_DATANODE_BEAN_NAME}, tags=tags ) beans = response.get('beans'...
Process HDFS Datanode metrics from given beans
def _hdfs_datanode_metrics(self, beans, tags): """ Process HDFS Datanode metrics from given beans """ # Only get the first bean bean = next(iter(beans)) bean_name = bean.get('name') self.log.debug("Bean name retrieved: {}".format(bean_name)) for metric, ...
Write the requirements - agent - release. txt file at the root of the repo listing all the Agent - based integrations pinned at the version they currently have in HEAD.
def requirements(ctx): """Write the `requirements-agent-release.txt` file at the root of the repo listing all the Agent-based integrations pinned at the version they currently have in HEAD. """ echo_info('Freezing check releases') checks = get_valid_checks() checks.remove('datadog_checks_dev...
Nest a payload in a dict under the keys contained in keys
def _nest_payload(self, keys, payload): """ Nest a payload in a dict under the keys contained in `keys` """ if len(keys) == 0: return payload return {keys[0]: self._nest_payload(keys[1:], payload)}
Recursively flattens the nginx json object. Returns the following: [ ( metric_name value tags ) ]
def _flatten_json(cls, metric_base, val, tags): """ Recursively flattens the nginx json object. Returns the following: [(metric_name, value, tags)] """ output = [] if isinstance(val, dict): # Pull out the server as a tag instead of trying to read as a metric ...
Return a list of tags from integrations - core representing an Agent release sorted by more recent first.
def get_agent_tags(since, to): """ Return a list of tags from integrations-core representing an Agent release, sorted by more recent first. """ agent_tags = sorted(parse_version_info(t) for t in git_tag_list(r'^\d+\.\d+\.\d+$')) # default value for `to` is the latest tag if to: to =...
Run commands in the proper repo.
def run(ctx, args): """Run commands in the proper repo.""" if not args: click.echo(ctx.get_help()) return with chdir(get_root()): result = run_command(args) ctx.exit(result.code)
Check if the server URL starts with a HTTP or HTTPS scheme fall back to http if not present
def _normalize_server_url(self, server): """ Check if the server URL starts with a HTTP or HTTPS scheme, fall back to http if not present """ server = server if server.startswith(("http://", "https://")) else "http://{}".format(server) return server
Get the running version of elasticsearch.
def _get_es_version(self, config): """ Get the running version of elasticsearch. """ try: data = self._get_data(config.url, config, send_sc=False) # pre-release versions of elasticearch are suffixed with -rcX etc.. # peel that off so that the map below...
overrides urlparse. urljoin since it removes base url path https:// docs. python. org/ 2/ library/ urlparse. html#urlparse. urljoin
def _join_url(self, base, url, admin_forwarder=False): """ overrides `urlparse.urljoin` since it removes base url path https://docs.python.org/2/library/urlparse.html#urlparse.urljoin """ if admin_forwarder: return base + url else: return urljoin(b...
Compute the URLs we need to hit depending on the running ES version
def _get_urls(self, version, cluster_stats): """ Compute the URLs we need to hit depending on the running ES version """ pshard_stats_url = "/_stats" health_url = "/_cluster/health" if version >= [0, 90, 10]: pending_tasks_url = "/_cluster/pending_tasks" ...
Hit a given URL and return the parsed json
def _get_data(self, url, config, send_sc=True): """ Hit a given URL and return the parsed json """ # Load basic authentication configuration, if available. if config.username and config.password: auth = (config.username, config.password) else: auth...
data: dictionary containing all the stats metric: datadog metric path: corresponding path in data flattened e. g. thread_pool. bulk. queue xform: a lambda to apply to the numerical value
def _process_metric(self, data, metric, xtype, path, xform=None, tags=None, hostname=None): """ data: dictionary containing all the stats metric: datadog metric path: corresponding path in data, flattened, e.g. thread_pool.bulk.queue xform: a lambda to apply to the numerical valu...
Resets state and uid set. To be called asap to free memory
def reset(self): """ Resets state and uid set. To be called asap to free memory """ self.reached_limit = False self.count = 0 self.seen.clear()
is_reached is to be called for every object that counts towards the limit. - When called with no uid the Limiter assumes this is a new object and unconditionally increments the counter ( less CPU and memory usage ). - When a given object can be passed multiple times a uid must be provided to deduplicate calls. Only the...
def is_reached(self, uid=None): """ is_reached is to be called for every object that counts towards the limit. - When called with no uid, the Limiter assumes this is a new object and unconditionally increments the counter (less CPU and memory usage). - When a given object can be ...
Fetch highwater offsets for each topic/ partition from Kafka cluster.
def _get_broker_offsets(self, instance, topics): """ Fetch highwater offsets for each topic/partition from Kafka cluster. Do this for all partitions in the cluster because even if it has no consumers, we may want to measure whether producers are successfully producing. No need t...
Fetch child nodes for a given Zookeeper path.
def _get_zk_path_children(self, zk_conn, zk_path, name_for_error): """Fetch child nodes for a given Zookeeper path.""" children = [] try: children = zk_conn.get_children(zk_path) except NoNodeError: self.log.info('No zookeeper node at %s', zk_path) except ...
Fetch Consumer Group offsets from Zookeeper.
def _get_zk_consumer_offsets(self, zk_hosts_ports, consumer_groups=None, zk_prefix=''): """ Fetch Consumer Group offsets from Zookeeper. Also fetch consumer_groups, topics, and partitions if not already specified in consumer_groups. :param dict consumer_groups: The consumer gro...
retrieve consumer offsets via the new consumer api. Offsets in this version are stored directly in kafka ( __consumer_offsets topic ) rather than in zookeeper
def _get_kafka_consumer_offsets(self, instance, consumer_groups): """ retrieve consumer offsets via the new consumer api. Offsets in this version are stored directly in kafka (__consumer_offsets topic) rather than in zookeeper """ consumer_offsets = {} topics = defaultdic...
Validate any explicitly specified consumer groups.
def _validate_explicit_consumer_groups(cls, val): """Validate any explicitly specified consumer groups. While the check does not require specifying consumer groups, if they are specified this method should be used to validate them. val = {'consumer_group': {'topic': [0, 1]}} ""...
Emit an event to the Datadog Event Stream.
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'): """Emit an event to the Datadog Event Stream.""" event_dict = { 'timestamp': int(time()), 'source_type_name': self.SOURCE_TYPE_NAME, 'msg_title': title, 'event_type': e...
Print packages that ve been added removed or changed
def display_package_changes(pre_packages, post_packages, indent=''): """ Print packages that've been added, removed or changed """ # use package name to determine what's changed pre_package_names = {p.name: p for p in pre_packages} post_package_names = {p.name: p for p in post_packages} add...
Resolve transient dependencies for any number of checks. If you want to do this en masse put all.
def resolve(checks, lazy, quiet): """Resolve transient dependencies for any number of checks. If you want to do this en masse, put `all`. """ root = get_root() if 'all' in checks: checks = os.listdir(root) for check_name in sorted(checks): pinned_reqs_file = os.path.join(root, c...
Pin a dependency for all checks that require it. This can also resolve transient dependencies.
def pin(package, version, checks, marker, resolving, lazy, quiet): """Pin a dependency for all checks that require it. This can also resolve transient dependencies. Setting the version to `none` will remove the package. You can specify an unlimited number of additional checks to apply the pin for v...
Combine all dependencies for the Agent s static environment.
def freeze(): """Combine all dependencies for the Agent's static environment.""" echo_waiting('Verifying collected packages...') catalog, errors = make_catalog() if errors: for error in errors: echo_failure(error) abort() static_file = get_agent_requirements() echo_...
Restart an Agent to detect environment changes.
def reload_env(check, env): """Restart an Agent to detect environment changes.""" envs = get_configured_envs(check) if not envs: echo_failure('No active environments found for `{}`.'.format(check)) echo_info('See what is available to start via `ddev env ls {}`.'.format(check)) abort(...
Set up the gitlab instance so it can be used in OpenMetricsBaseCheck
def _create_gitlab_prometheus_instance(self, instance, init_config): """ Set up the gitlab instance so it can be used in OpenMetricsBaseCheck """ # Mapping from Prometheus metrics names to Datadog ones # For now it's a 1:1 mapping allowed_metrics = init_config.get('allowe...
Submit a metric as a gauge additional tags provided will be added to the ones from the label provided via the metrics object.
def _submit_gauge(self, metric_name, val, metric, custom_tags=None, hostname=None): """ Submit a metric as a gauge, additional tags provided will be added to the ones from the label provided via the metrics object. `custom_tags` is an array of 'tag:value' that will be added to the ...
Validate tag sets for a MongoReplicaSetClient.
def _validate_tag_sets(tag_sets): """Validate tag sets for a MongoReplicaSetClient. """ if tag_sets is None: return tag_sets if not isinstance(tag_sets, list): raise TypeError(( "Tag sets %r invalid, must be a list") % (tag_sets,)) if len(tag_sets) == 0: raise Va...
Validate max_staleness.
def _validate_max_staleness(max_staleness): """Validate max_staleness.""" if max_staleness == -1: return -1 if not isinstance(max_staleness, integer_types): raise TypeError(_invalid_max_staleness_msg(max_staleness)) if max_staleness <= 0: raise ValueError(_invalid_max_staleness...
Read preference as a document.
def document(self): """Read preference as a document. """ doc = {'mode': self.__mongos_mode} if self.__tag_sets not in (None, [{}]): doc['tags'] = self.__tag_sets if self.__max_staleness != -1: doc['maxStalenessSeconds'] = self.__max_staleness retu...
Validate default configuration files.
def config(check): """Validate default configuration files.""" if check: checks = [check] else: checks = sorted(get_valid_checks()) files_failed = {} files_warned = {} num_files = 0 echo_waiting('Validating default configuration files...') for check in checks: c...
Get stats from the queue manager
def queue_manager_stats(self, queue_manager, tags): """ Get stats from the queue manager """ for mname, pymqi_value in iteritems(metrics.queue_manager_metrics()): try: m = queue_manager.inquire(pymqi_value) mname = '{}.queue_manager.{}'.format...
Grab stats from queues
def queue_stats(self, queue, tags): """ Grab stats from queues """ for mname, pymqi_value in iteritems(metrics.queue_metrics()): try: mname = '{}.queue.{}'.format(self.METRIC_PREFIX, mname) m = queue.inquire(pymqi_value) self.ga...
Get the version string for the given check.
def get_version_string(check_name): """ Get the version string for the given check. """ version = VERSION.search(read_version_file(check_name)) if version: return version.group(1)
Load the manifest file into a dictionary
def load_manifest(check_name): """ Load the manifest file into a dictionary """ manifest_path = os.path.join(get_root(), check_name, 'manifest.json') if file_exists(manifest_path): return json.loads(read_file(manifest_path)) return {}
Returns a dictionary mapping { check - package - name -- > pinned_version } from the given file contents. We can assume lines are in the form:
def parse_agent_req_file(contents): """ Returns a dictionary mapping {check-package-name --> pinned_version} from the given file contents. We can assume lines are in the form: datadog-active-directory==1.1.1; sys_platform == 'win32' """ catalog = OrderedDict() for line in contents.spli...
Query status and get a dictionary back. Extract each field out of the dictionary and stuff it in the corresponding metric.
def _collect_dict(self, metric_type, field_metric_map, query, db, tags): """ Query status and get a dictionary back. Extract each field out of the dictionary and stuff it in the corresponding metric. query: show status... field_metric_map: {"Seconds_behind_master": "mysq...
Get the pid_file variable
def _get_pid_file_variable(self, db): """ Get the `pid_file` variable """ pid_file = None try: with closing(db.cursor()) as cursor: cursor.execute("SHOW VARIABLES LIKE 'pid_file'") pid_file = cursor.fetchone()[1] except Exceptio...