text
stringlengths
81
112k
Some metrics contains conditions, labels that have "condition" as name and "true", "false", or "unknown" as value. The metric value is expected to be a gauge equal to 0 or 1 in this case. For example: metric { label { name: "condition", value: "true" } # other labe...
Metrics from kube-state-metrics have changed For example: kube_node_status_condition{condition="Ready",node="ip-172-33-39-189.eu-west-1.compute",status="true"} 1 kube_node_status_condition{condition="OutOfDisk",node="ip-172-33-57-130.eu-west-1.compute",status="false"} 1 metric { ...
Lookups the labels_mapper table to see if replacing the tag name is necessary, then returns a "name:value" tag string def _format_tag(self, name, value, scraper_config): """ Lookups the labels_mapper table to see if replacing the tag name is necessary, then returns a "name:value" tag st...
Search for `name` in labels name and returns corresponding tag string. Tag name is label name if not specified. Returns None if name was not found. def _label_to_tag(self, name, labels, scraper_config, tag_name=None): """ Search for `name` in labels name and returns corresponding tag st...
Phase a pod is in. def kube_pod_status_phase(self, metric, scraper_config): """ Phase a pod is in. """ metric_name = scraper_config['namespace'] + '.pod.status_phase' status_phase_counter = Counter() for sample in metric.samples: # Counts aggregated cluster-wide to avoid no...
Time until the next schedule def kube_cronjob_next_schedule_time(self, metric, scraper_config): """ Time until the next schedule """ # Used as a service check so that one can be alerted if the cronjob's next schedule is in the past check_basename = scraper_config['namespace'] + '.cronjob.on_sch...
The ready status of a cluster node. v1.0+ def kube_node_status_condition(self, metric, scraper_config): """ The ready status of a cluster node. v1.0+""" base_check_name = scraper_config['namespace'] + '.node' metric_name = scraper_config['namespace'] + '.nodes.by_condition' by_condition...
The ready status of a cluster node (legacy) def kube_node_status_ready(self, metric, scraper_config): """ The ready status of a cluster node (legacy)""" service_check_name = scraper_config['namespace'] + '.node.ready' for sample in metric.samples: node_tag = self._label_to_tag("node...
Whether the node is in a network unavailable state (legacy) def kube_node_status_network_unavailable(self, metric, scraper_config): """ Whether the node is in a network unavailable state (legacy)""" service_check_name = scraper_config['namespace'] + '.node.network_unavailable' for sample in met...
Whether a node can schedule new pods. def kube_node_spec_unschedulable(self, metric, scraper_config): """ Whether a node can schedule new pods. """ metric_name = scraper_config['namespace'] + '.node.status' statuses = ('schedulable', 'unschedulable') if metric.type in METRIC_TYPES: ...
Quota and current usage by resource type. def kube_resourcequota(self, metric, scraper_config): """ Quota and current usage by resource type. """ metric_base_name = scraper_config['namespace'] + '.resourcequota.{}.{}' suffixes = {'used': 'used', 'hard': 'limit'} if metric.type in METRIC...
Resource limits by consumer type. def kube_limitrange(self, metric, scraper_config): """ Resource limits by consumer type. """ # type's cardinality's low: https://github.com/kubernetes/kubernetes/blob/v1.6.1/pkg/api/v1/types.go#L3872-L3879 # idem for resource: https://github.com/kubernetes/kube...
Count objects by whitelisted tags and submit counts as gauges. def count_objects_by_tags(self, metric, scraper_config): """ Count objects by whitelisted tags and submit counts as gauges. """ config = self.object_count_params[metric.name] metric_name = "{}.{}".format(scraper_config['namespace'],...
Searches for a pod uid in the podlist and returns the pod if found :param uid: pod uid :param podlist: podlist dict object :return: pod dict object if found, None if not found def get_pod_by_uid(uid, podlist): """ Searches for a pod uid in the podlist and returns the pod if found :param uid: po...
Return if the pod is a static pending pod See https://github.com/kubernetes/kubernetes/pull/57106 :param pod: dict :return: bool def is_static_pending_pod(pod): """ Return if the pod is a static pending pod See https://github.com/kubernetes/kubernetes/pull/57106 :param pod: dict :return...
Queries the agent6 container filter interface. It retrieves container name + image from the podlist, so static pod filtering is not supported. Result is cached between calls to avoid the python-go switching cost for prometheus metrics (will be called once per metric) :param cid: contain...
Returns the client certificates :return: tuple (crt,key) or None def cert_pair(self): """ Returns the client certificates :return: tuple (crt,key) or None """ if self._ssl_cert and self._ssl_private_key: return (self._ssl_cert, self._ssl_private_key) ...
Returns the https headers with credentials, if token is used and url is https :param url: url to be queried, including scheme :return: dict or None def headers(self, url): """ Returns the https headers with credentials, if token is used and url is https :param url: url to be que...
Configures a PrometheusScaper object with query credentials :param scraper: valid PrometheusScaper object :param endpoint: url that will be scraped def configure_scraper(self, scraper_config): """ Configures a PrometheusScaper object with query credentials :param scraper: valid ...
Return the list of file changed in the current branch compared to `master` def files_changed(): """ Return the list of file changed in the current branch compared to `master` """ with chdir(get_root()): result = run_command('git diff --name-only master...', capture='out') changed_files = re...
Get the list of commits from `target_tag` to `HEAD` for the given check def get_commits_since(check_name, target_tag=None): """ Get the list of commits from `target_tag` to `HEAD` for the given check """ root = get_root() target_path = os.path.join(root, check_name) command = 'git log --pretty=...
Return the contents of a file at a given tag def git_show_file(path, ref): """ Return the contents of a file at a given tag """ root = get_root() command = 'git show {}:{}'.format(ref, path) with chdir(root): return run_command(command, capture=True).stdout
Commit the changes for the given targets. def git_commit(targets, message, force=False, sign=False): """ Commit the changes for the given targets. """ root = get_root() target_paths = [] for t in targets: target_paths.append(os.path.join(root, t)) with chdir(root): result =...
Tag the repo using an annotated tag. def git_tag(tag_name, push=False): """ Tag the repo using an annotated tag. """ with chdir(get_root()): result = run_command('git tag -a {} -m "{}"'.format(tag_name, tag_name), capture=True) if push: if result.code != 0: ...
Return a list of all the tags in the git repo matching a regex passed in `pattern`. If `pattern` is None, return all the tags. def git_tag_list(pattern=None): """ Return a list of all the tags in the git repo matching a regex passed in `pattern`. If `pattern` is None, return all the tags. """ w...
Return a boolean value for whether the given file is tracked by git. def git_ls_files(filename): """ Return a boolean value for whether the given file is tracked by git. """ with chdir(get_root()): # https://stackoverflow.com/a/2406813 result = run_command('git ls-files --error-unmatch ...
When handling non english versions, the counters don't work quite as documented. This is because strings like "Bytes Sent/sec" might appear multiple times in the english master, and might not have mappings for each index. Search each index, and make sure the requested counter name actually appe...
Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps def gauge(self, *args, **kwargs): """ Compatability wrapper for Agents that do not submit gauge metrics with custom timestamps """ orig_gauge = super(Nagios, self).gauge # remove 'timestamp'...
Parse until the end of each tailer associated with this instance. We match instance and tailers based on the path to the Nagios configuration file Special case: Compatibility with the old conf when no conf file is specified but the path to the event_log is given def check(self, instance): ...
Actual nagios parsing Return True if we found an event, False otherwise def _parse_line(self, line): """ Actual nagios parsing Return True if we found an event, False otherwise """ # first isolate the timestamp and the event type try: self._line_parse...
Factory method called by the parsers def create_event(self, timestamp, event_type, hostname, fields, tags=None): """Factory method called by the parsers """ # Agent6 expects a specific set of fields, so we need to place all # extra fields in the msg_title and let the Datadog backend sep...
Create a command generator to perform all the snmp query. If mibs_path is not None, load the mibs present in the custom mibs folder. (Need to be in pysnmp format) def create_snmp_engine(self, mibs_path): ''' Create a command generator to perform all the snmp query. If mibs_path ...
Generate a Security Parameters object based on the instance's configuration. See http://pysnmp.sourceforge.net/docs/current/security-configuration.html def get_auth_data(cls, instance): ''' Generate a Security Parameters object based on the instance's configuration. See ...
Generate a Context Parameters object based on the instance's configuration. We do not use the hlapi currently, but the rfc3413.oneliner.cmdgen accepts Context Engine Id (always None for now) and Context Name parameters. def get_context_data(cls, instance): ''' Generate a Context...
Generate a Transport target object based on the instance's configuration def get_transport_target(cls, instance, timeout, retries): ''' Generate a Transport target object based on the instance's configuration ''' if "ip_address" not in instance: raise Exception("An IP addres...
Perform a snmpwalk on the domain specified by the oids, on the device configured in instance. lookup_names is a boolean to specify whether or not to use the mibs to resolve the name and values. Returns a dictionary: dict[oid/metric_name][row index] = value In case of sca...
Perform two series of SNMP requests, one for all that have MIB asociated and should be looked up and one for those specified by oids def _check(self, instance): ''' Perform two series of SNMP requests, one for all that have MIB asociated and should be looked up and one for those specifi...
For all the metrics that are specified as oid, the conf oid is going to exactly match or be a prefix of the oid sent back by the device Use the instance configuration to find the name to give to the metric Submit the results to the aggregator. def report_raw_metrics(self, metrics, results, tag...
For each of the metrics specified as needing to be resolved with mib, gather the tags requested in the instance conf for each row. Submit the results to the aggregator. def report_table_metrics(self, metrics, results, tags): ''' For each of the metrics specified as needing to be resolv...
Gather the tags for this row of the table (index) based on the results (all the results from the query). index_tags and column_tags are the tags to gather. - Those specified in index_tags contain the tag_group name and the index of the value we want to extract from the index tuple. ...
Convert the values reported as pysnmp-Managed Objects to values and report them to the aggregator def submit_metric(self, name, snmp_value, forced_type, tags=None): ''' Convert the values reported as pysnmp-Managed Objects to values and report them to the aggregator ''' ...
See https://github.com/python/cpython/blob/b02774f42108aaf18eb19865472c8d5cd95b5f11/Lib/bdb.py#L319-L332 def set_trace(self, frame=None): """See https://github.com/python/cpython/blob/b02774f42108aaf18eb19865472c8d5cd95b5f11/Lib/bdb.py#L319-L332""" self.reset() if frame is None: fr...
The current average latency or None. def round_trip_time(self): """The current average latency or None.""" # This override is for unittesting only! if self._address in self._host_to_round_trip_time: return self._host_to_round_trip_time[self._address] return self._round_trip...
Collect stats for all reachable networks def collect_networks_metrics(self, tags, network_ids, exclude_network_id_rules): """ Collect stats for all reachable networks """ networks = self.get_networks() filtered_networks = [] if not network_ids: # Filter out e...
Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' def _parse_uptime_string(self, uptime): """ Parse u' 16:53:48 up 1 day, 21:34, 3 users, load average: 0.04, 0.14, 0.19\n' """ uptime = uptime.strip() load_averages = uptime[uptime.find('load average:') :].split(':...
Submits stats for all hypervisors registered to this control plane Raises specific exceptions based on response code def collect_hypervisors_metrics( self, servers, custom_tags=None, use_shortname=False, collect_hypervisor_metrics=True, collect_hypervisor_load=Fa...
Guarantees a valid auth scope for this instance, and returns it Communicates with the identity server and initializes a new scope when one is absent, or has been forcibly removed due to token expiry def init_api(self, instance_config, custom_tags): """ Guarantees a valid auth scope for...
Tries to connect to the cadvisor endpoint, with given params :return: url if OK, raises exception if NOK def detect_cadvisor(kubelet_url, cadvisor_port): """ Tries to connect to the cadvisor endpoint, with given params :return: url if OK, raises exception if NOK """ if c...
Scrape and submit metrics from cadvisor :param: instance: check instance object :param: cadvisor_url: valid cadvisor url, as returned by detect_cadvisor() :param: pod_list: fresh podlist object from the kubelet :param: pod_list_utils: already initialised PodListUtils object def process_...
Recusively parses and submit metrics for a given entity, until reaching self.max_depth. Nested metric names are flattened: memory/usage -> memory.usage :param: metric: parent's metric name (check namespace for root stat objects) :param: dat: metric dictionnary to parse :param: ta...
Get the proper set of stats metrics for the specified ES version def stats_for_version(version): """ Get the proper set of stats metrics for the specified ES version """ metrics = dict(STATS_METRICS) # JVM additional metrics if version >= [0, 90, 10]: metrics.update(JVM_METRICS_POST_0_...
Get the proper set of pshard metrics for the specified ES version def pshard_stats_for_version(version): """ Get the proper set of pshard metrics for the specified ES version """ pshard_stats_metrics = dict(PRIMARY_SHARD_METRICS) if version >= [1, 0, 0]: pshard_stats_metrics.update(PRIMARY_...
Get the proper set of health metrics for the specified ES version def health_stats_for_version(version): """ Get the proper set of health metrics for the specified ES version """ cluster_health_metrics = dict(CLUSTER_HEALTH_METRICS) if version >= [2, 4, 0]: cluster_health_metrics.update(CLU...
Show all the checks that can be released. def ready(ctx, quiet): """Show all the checks that can be released.""" user_config = ctx.obj cached_prs = {} for target in sorted(get_valid_checks()): # get the name of the current release tag cur_version = get_version_string(target) ta...
Show all the pending PRs for a given check. def changes(ctx, check, dry_run): """Show all the pending PRs for a given check.""" if not dry_run and check not in get_valid_checks(): abort('Check `{}` is not an Agent-based Integration'.format(check)) # get the name of the current release tag cur_...
Tag the HEAD of the git repo with the current release number for a specific check. The tag is pushed to origin by default. You can tag everything at once by setting the check to `all`. Notice: specifying a different version than the one in __about__.py is a maintenance task that should be run under ve...
Perform a set of operations needed to release a single check: \b * update the version in __about__.py * update the changelog * update the requirements-agent-release.txt file * update in-toto metadata * commit the above changes You can release everything at once by setting the che...
Perform the operations needed to update the changelog. This method is supposed to be used by other tasks and not directly. def changelog(ctx, check, version, old_version, initial, quiet, dry_run): """Perform the operations needed to update the changelog. This method is supposed to be used by other tasks ...
Build a wheel for a check as it is on the repo HEAD def build(check, sdist): """Build a wheel for a check as it is on the repo HEAD""" if check in get_valid_checks(): check_dir = os.path.join(get_root(), check) else: check_dir = resolve_path(check) if not dir_exists(check_dir): ...
Release a specific check to PyPI as it is on the repo HEAD. def upload(ctx, check, sdist, dry_run): """Release a specific check to PyPI as it is on the repo HEAD.""" if check in get_valid_checks(): check_dir = os.path.join(get_root(), check) else: check_dir = resolve_path(check) if ...
Return the metrics received under the given name def metrics(self, name): """ Return the metrics received under the given name """ return [ MetricStub( ensure_unicode(stub.name), stub.type, stub.value, normalize...
Return the service checks received under the given name def service_checks(self, name): """ Return the service checks received under the given name """ return [ ServiceCheckStub( ensure_unicode(stub.check_id), ensure_unicode(stub.name), ...
Return all events def events(self): """ Return all events """ all_events = [{ensure_unicode(key): value for key, value in iteritems(ev)} for ev in self._events] for ev in all_events: to_decode = [] for key, value in iteritems(ev): if isin...
Assert a metric is tagged with tag def assert_metric_has_tag(self, metric_name, tag, count=None, at_least=1): """ Assert a metric is tagged with tag """ self._asserted.add(metric_name) candidates = [] for metric in self.metrics(metric_name): if tag in metric...
Assert a metric was processed by this stub def assert_metric(self, name, value=None, tags=None, count=None, at_least=1, hostname=None, metric_type=None): """ Assert a metric was processed by this stub """ self._asserted.add(name) tags = normalize_tags(tags, sort=True) c...
Assert a service check was processed by this stub def assert_service_check(self, name, status=None, tags=None, count=None, at_least=1, hostname=None, message=None): """ Assert a service check was processed by this stub """ tags = normalize_tags(tags, sort=True) candidates = [] ...
Return the metrics assertion coverage def metrics_asserted_pct(self): """ Return the metrics assertion coverage """ num_metrics = len(self._metrics) num_asserted = len(self._asserted) if num_metrics == 0: if num_asserted == 0: return 100 ...
Examine the response and raise an error is something is off def _process_response(cls, response): """ Examine the response and raise an error is something is off """ if len(response) != 1: raise BadResponseError("Malformed response: {}".format(response)) stats = lis...
Optional metric handler for 'items' stats key: "items:<slab_id>:<metric_name>" format value: return untouched Like all optional metric handlers returns metric, tags, value def get_items_stats(key, value): """ Optional metric handler for 'items' stats key: "items:<slab...
Optional metric handler for 'items' stats key: "items:<slab_id>:<metric_name>" format value: return untouched Like all optional metric handlers returns metric, tags, value def get_slabs_stats(key, value): """ Optional metric handler for 'items' stats key: "items:<slab...
instance: the check instance base_url: the url of the rabbitmq management api (e.g. http://localhost:15672/api) object_type: either QUEUE_TYPE or NODE_TYPE or EXCHANGE_TYPE max_detailed: the limit of objects to collect for this type filters: explicit or regexes filters of specified queue...
Collect metrics on currently open connection per vhost. def get_connections_stat( self, instance, base_url, object_type, vhosts, limit_vhosts, custom_tags, auth=None, ssl_verify=True ): """ Collect metrics on currently open connection per vhost. """ instance_proxy = self.get...
Check the aliveness API against all or a subset of vhosts. The API will return {"status": "ok"} and a 200 response code in the case that the check passes. def _check_aliveness(self, instance, base_url, vhosts, custom_tags, auth=None, ssl_verify=True): """ Check the aliveness API against...
Create a GridIn property. def _grid_in_property(field_name, docstring, read_only=False, closed_only=False): """Create a GridIn property.""" def getter(self): if closed_only and not self._closed: raise AttributeError("can only get %r on a closed file" % ...
Create a GridOut property. def _grid_out_property(field_name, docstring): """Create a GridOut property.""" def getter(self): self._ensure_file() # Protect against PHP-237 if field_name == 'length': return self._file.get(field_name, 0) return self._file.get(field_nam...
Flush `data` to a chunk. def __flush_data(self, data): """Flush `data` to a chunk. """ # Ensure the index, even if there's nothing to write, so # the filemd5 command always succeeds. self.__ensure_indexes() self._file['md5'].update(data) if not data: ...
Flush the buffer contents out to a chunk. def __flush_buffer(self): """Flush the buffer contents out to a chunk. """ self.__flush_data(self._buffer.getvalue()) self._buffer.close() self._buffer = StringIO()
Flush the file to the database. def __flush(self): """Flush the file to the database. """ try: self.__flush_buffer() self._file['md5'] = self._file["md5"].hexdigest() self._file["length"] = self._position self._file["uploadDate"] = datetime.datet...
Flush the file and close it. A closed file cannot be written any more. Calling :meth:`close` more than once is allowed. def close(self): """Flush the file and close it. A closed file cannot be written any more. Calling :meth:`close` more than once is allowed. """ ...
Write data to the file. There is no return value. `data` can be either a string of bytes or a file-like object (implementing :meth:`read`). If the file has an :attr:`encoding` attribute, `data` can also be a :class:`unicode` (:class:`str` in python 3) instance, which will be enc...
Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned. def readchunk(self): """Reads a chunk at a time. If the current position is within a chunk the remainder of the chunk is returned. """ received = len(self.__buffer) ...
Read at most `size` bytes from the file (less if there isn't enough data). The bytes are returned as an instance of :class:`str` (:class:`bytes` in python 3). If `size` is negative or omitted all data is read. :Parameters: - `size` (optional): the number of bytes to read def...
Set the current position of this file. :Parameters: - `pos`: the position (or offset if using relative positioning) to seek to - `whence` (optional): where to seek from. :attr:`os.SEEK_SET` (``0``) for absolute file positioning, :attr:`os.SEEK_CUR` (``1``) to ...
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT` def provider(self, value): """ Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT` """ result = None # `None` defaults to `ProviderArchitecture.DEFAULT` defaulted_value = v...
A property to retrieve the sampler connection information. def connection(self): """ A property to retrieve the sampler connection information. """ return {'host': self.host, 'namespace': self.namespace, 'username': self.username, 'password': self.password}
Return an index key used to cache the sampler connection. def connection_key(self): """ Return an index key used to cache the sampler connection. """ return "{host}:{namespace}:{username}".format(host=self.host, namespace=self.namespace, username=self.username)
Cache and return filters as a comprehensive WQL clause. def formatted_filters(self): """ Cache and return filters as a comprehensive WQL clause. """ if not self._formatted_filters: filters = deepcopy(self.filters) self._formatted_filters = self._format_filter(fil...
Compute new samples. def sample(self): """ Compute new samples. """ self._sampling = True try: if self.is_raw_perf_class and not self._previous_sample: self._current_sample = self._query() self._previous_sample = self._current_sample ...
Return the calculator for the given `counter_type`. Fallback with `get_raw`. def _get_property_calculator(self, counter_type): """ Return the calculator for the given `counter_type`. Fallback with `get_raw`. """ calculator = get_raw try: calculator = ...
Format WMI Object's RAW data based on the previous sample. Do not override the original WMI Object ! def _format_property_values(self, previous, current): """ Format WMI Object's RAW data based on the previous sample. Do not override the original WMI Object ! """ forma...
Create a new WMI connection def get_connection(self): """ Create a new WMI connection """ self.logger.debug( u"Connecting to WMI server " u"(host={host}, namespace={namespace}, provider={provider}, username={username}).".format( host=self.host, na...
Transform filters to a comprehensive WQL `WHERE` clause. Builds filter from a filter list. - filters: expects a list of dicts, typically: - [{'Property': value},...] or - [{'Property': (comparison_op, value)},...] NOTE: If we just provide a value we defa...
Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`. def _query(self): # pylint: disable=E0202 """ Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`. ""...
Parse WMI query results in a more comprehensive form. Returns: List of WMI objects ``` [ { 'freemegabytes': 19742.0, 'name': 'C:', 'avgdiskbytesperwrite': 1536.0 }, { 'freemegabytes': 19742.0, ...
Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. def _check_with_socket(self, sock_info, metadata=None): """Return (IsMaster, round_trip_time). Can raise ConnectionFailure or OperationFailure. """ cmd = SON([('ismaster', 1)]) if meta...
Verify that the checks versions are in sync with the requirements-agent-release.txt file def agent_reqs(): """Verify that the checks versions are in sync with the requirements-agent-release.txt file""" echo_info("Validating requirements-agent-release.txt...") agent_reqs_content = parse_agent_req_file(read...
Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` def _log_deprecation(self, deprecation_key): """ Logs a deprecation notice at most once per AgentCheck instance, for the pre-defined `deprecation_key` """ if not self._deprecations[depr...
Convert from CamelCase to camel_case And substitute illegal metric characters def convert_to_underscore_separated(self, name): """ Convert from CamelCase to camel_case And substitute illegal metric characters """ metric_name = self.FIRST_CAP_RE.sub(br'\1_\2', ensure_byte...
Normalize tags contents and type: - append `device_name` as `device:` tag - normalize tags type - doesn't mutate the passed list, returns a new list def _normalize_tags_type(self, tags, device_name=None, metric_name=None): """ Normalize tags contents and type: - append `...
Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whether to make sure that the metric name returned is in "snake_case" def normal...