INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Create a color function which returns a single hue and saturation with. different values ( HSV ). Accepted values are color strings as usable by PIL/ Pillow.
def get_single_color_func(color): """Create a color function which returns a single hue and saturation with. different values (HSV). Accepted values are color strings as usable by PIL/Pillow. >>> color_func1 = get_single_color_func('deepskyblue') >>> color_func2 = get_single_color_func('#00b4d2') ...
Create a word_cloud from words and frequencies.
def generate_from_frequencies(self, frequencies, max_font_size=None): # noqa: C901 """Create a word_cloud from words and frequencies. Parameters ---------- frequencies : dict from string to float A contains words and associated frequency. max_font_size : int ...
Splits a long text into words eliminates the stopwords.
def process_text(self, text): """Splits a long text into words, eliminates the stopwords. Parameters ---------- text : string The text to be processed. Returns ------- words : dict (string, int) Word tokens with associated frequency. ...
Generate wordcloud from text.
def generate_from_text(self, text): """Generate wordcloud from text. The input "text" is expected to be a natural text. If you pass a sorted list of words, words will appear in your output twice. To remove this duplication, set ``collocations=False``. Calls process_text and gen...
Recolor existing layout.
def recolor(self, random_state=None, color_func=None, colormap=None): """Recolor existing layout. Applying a new coloring is much faster than generating the whole wordcloud. Parameters ---------- random_state : RandomState, int, or None, default=None If not ...
Export to image file.
def to_file(self, filename): """Export to image file. Parameters ---------- filename : string Location to write to. Returns ------- self """ img = self.to_image() img.save(filename, optimize=True) return self
Cast to two dimensional boolean mask.
def _get_bolean_mask(self, mask): """Cast to two dimensional boolean mask.""" if mask.dtype.kind == 'f': warnings.warn("mask image should be unsigned byte between 0" " and 255. Got a float array") if mask.ndim == 2: boolean_mask = mask == 255 ...
Draw mask contour on a pillow image.
def _draw_contour(self, img): """Draw mask contour on a pillow image.""" if self.mask is None or self.contour_width == 0: return img mask = self._get_bolean_mask(self.mask) * 255 contour = Image.fromarray(mask.astype(np.uint8)) contour = contour.resize(img.size) ...
Retrieves the leader - election annotation from a given object and submits metrics and a service check.
def check_election_status(self, config): """ Retrieves the leader-election annotation from a given object, and submits metrics and a service check. An integration warning is sent if the object is not retrievable, or no record is found. Monitors on the service-check should have ...
Python2. 4 doesn t have a partition method so we provide our own that mimics str. partition from later releases.
def _partition(entity, sep): """Python2.4 doesn't have a partition method so we provide our own that mimics str.partition from later releases. Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the...
Python2. 4 doesn t have an rpartition method so we provide our own that mimics str. rpartition from later releases.
def _rpartition(entity, sep): """Python2.4 doesn't have an rpartition method so we provide our own that mimics str.rpartition from later releases. Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after ...
Validates the format of user information in a MongoDB URI. Reserved characters like:/ + and @ must be escaped following RFC 3986.
def parse_userinfo(userinfo): """Validates the format of user information in a MongoDB URI. Reserved characters like ':', '/', '+' and '@' must be escaped following RFC 3986. Returns a 2-tuple containing the unescaped username followed by the unescaped password. :Paramaters: - `userinf...
Validates an IPv6 literal host: port string.
def parse_ipv6_literal_host(entity, default_port): """Validates an IPv6 literal host:port string. Returns a 2-tuple of IPv6 literal followed by port where port is default_port if it wasn't specified in entity. :Parameters: - `entity`: A string that represents an IPv6 literal enclosed ...
Validates a host string
def parse_host(entity, default_port=DEFAULT_PORT): """Validates a host string Returns a 2-tuple of host followed by port where port is default_port if it wasn't specified in the string. :Parameters: - `entity`: A host or host:port string where host could be a hostname or IP...
Helper method for split_options which creates the options dict. Also handles the creation of a list for the URI tag_sets/ readpreferencetags portion.
def _parse_options(opts, delim): """Helper method for split_options which creates the options dict. Also handles the creation of a list for the URI tag_sets/ readpreferencetags portion.""" options = {} for opt in opts.split(delim): key, val = opt.split("=") if key.lower() == 'readpre...
Takes a string of the form host1 [: port ] host2 [: port ]... and splits it into ( host port ) tuples. If [: port ] isn t present the default_port is used.
def split_hosts(hosts, default_port=DEFAULT_PORT): """Takes a string of the form host1[:port],host2[:port]... and splits it into (host, port) tuples. If [:port] isn't present the default_port is used. Returns a set of 2-tuples containing the host name (or IP) followed by port number. :Paramete...
Parse and validate a MongoDB URI.
def parse_uri(uri, default_port=DEFAULT_PORT, validate=True, warn=False): """Parse and validate a MongoDB URI. Returns a dict of the form:: { 'nodelist': <list of (host, port) tuples>, 'username': <username> or None, 'password': <password> or None, 'data...
Apply max_staleness in seconds to a Selection with a known primary.
def _with_primary(max_staleness, selection): """Apply max_staleness, in seconds, to a Selection with a known primary.""" primary = selection.primary sds = [] for s in selection.server_descriptions: if s.server_type == SERVER_TYPE.RSSecondary: # See max-staleness.rst for explanation ...
Apply max_staleness in seconds to a Selection with no known primary.
def _no_primary(max_staleness, selection): """Apply max_staleness, in seconds, to a Selection with no known primary.""" # Secondary that's replicated the most recent writes. smax = selection.secondary_with_max_last_write_date() if not smax: # No secondaries and no primary, short-circuit out of h...
Apply max_staleness in seconds to a Selection.
def select(max_staleness, selection): """Apply max_staleness, in seconds, to a Selection.""" if max_staleness == -1: return selection # Server Selection Spec: If the TopologyType is ReplicaSetWithPrimary or # ReplicaSetNoPrimary, a client MUST raise an error if maxStaleness < # heartbeatFre...
Create an event with a message describing the replication state of a mongo node
def create_event(self, state, server, agentConfig): """Create an event with a message describing the replication state of a mongo node""" def get_state_description(state): if state == 0: return 'Starting Up' elif state == 1: return 'Pr...
A decorator to timeout a function. Decorated method calls are executed in a separate new thread with a specified timeout. Also check if a thread for the same function already exists before creating a new one. Note: Compatible with Windows ( thread based ).
def timeout(timeout): """ A decorator to timeout a function. Decorated method calls are executed in a separate new thread with a specified timeout. Also check if a thread for the same function already exists before creating a new one. Note: Compatible with Windows (thread based). """ def de...
Create a set of pids of selected processes. Search for search_string
def find_pids(self, name, search_string, exact_match, ignore_ad=True): """ Create a set of pids of selected processes. Search for search_string """ if not self.should_refresh_pid_cache(name): return self.pid_cache[name] ad_error_logger = self.log.debug ...
A psutil wrapper that is calling * psutil. method ( * args ** kwargs ) and returns the result OR * psutil. method ( * args ** kwargs ). accessor [ i ] for each accessors given in a list the result being indexed in a dictionary by the accessor name
def psutil_wrapper(self, process, method, accessors, try_sudo, *args, **kwargs): """ A psutil wrapper that is calling * psutil.method(*args, **kwargs) and returns the result OR * psutil.method(*args, **kwargs).accessor[i] for each accessors given in a list, the result bei...
Report a service check for each process in search_string. Report as OK if the process is in the warning thresholds CRITICAL out of the critical thresholds WARNING out of the warning thresholds
def _process_service_check(self, name, nb_procs, bounds, tags): """ Report a service check, for each process in search_string. Report as OK if the process is in the warning thresholds CRITICAL out of the critical thresholds WARNING o...
Filter pids by it s username.: param user: string with name of system user: param pids: set of pids to filter: return: set of filtered pids
def _filter_by_user(self, user, pids): """ Filter pids by it's username. :param user: string with name of system user :param pids: set of pids to filter :return: set of filtered pids """ filtered_pids = set() for pid in pids: try: ...
A wrapper around wmi. from_time to get a WMI - formatted time from a time struct.
def _dt_to_wmi(self, dt): ''' A wrapper around wmi.from_time to get a WMI-formatted time from a time struct. ''' return from_time( year=dt.year, month=dt.month, day=dt.day, hours=dt.hour, minutes=dt.minute, secon...
Generate the event s body to send to Datadog.
def _msg_text(self): """ Generate the event's body to send to Datadog. Consider `event_format` parameter: * Only use the specified list of event properties. * If unspecified, default to the EventLog's `Message` or `InsertionStrings`. """ msg_text = u"" i...
Compare this event s timestamp to a give timestamp.
def is_after(self, ts): ''' Compare this event's timestamp to a give timestamp. ''' if self.timestamp >= int(calendar.timegm(ts.timetuple())): return True return False
Convert a wmi formatted timestamp into an epoch.
def _wmi_to_ts(self, wmi_ts): ''' Convert a wmi formatted timestamp into an epoch. ''' year, month, day, hour, minute, second, microsecond, tz = to_time(wmi_ts) tz_delta = timedelta(minutes=int(tz)) if '+' in wmi_ts: tz_delta = -tz_delta dt = ( da...
Inject additional tags into the list already supplied to LogEvent.
def _tags(self, tags, event_code): ''' Inject additional tags into the list already supplied to LogEvent. ''' tags_list = [] if tags is not None: tags_list += list(tags) tags_list.append("event_id:{event_id}".format(event_id=event_code)) return tags_list
Kill a cursor.
def close(self, cursor_id, address): """Kill a cursor. Raises TypeError if cursor_id is not an instance of (int, long). :Parameters: - `cursor_id`: cursor id to close - `address`: the cursor's server's (host, port) pair .. versionchanged:: 3.0 Now requir...
Don t send the can connect service check if we have troubles getting the health status
def _get_health_status(self, url, ssl_params, timeout): """ Don't send the "can connect" service check if we have troubles getting the health status """ try: r = self._perform_request(url, "/health", ssl_params, timeout) # we don't use get() here so we can...
Stop environments.
def stop(check, env): """Stop environments.""" all_checks = check == 'all' checks = get_configured_checks() if all_checks else [check] if all_checks: env_indent = DEFAULT_INDENT status_indent = DEFAULT_INDENT * 2 else: env_indent = None status_indent = DEFAULT_INDENT...
Process both the istio_mesh instance and process_mixer instance associated with this instance
def check(self, instance): """ Process both the istio_mesh instance and process_mixer instance associated with this instance """ # Get the config for the istio_mesh instance istio_mesh_endpoint = instance.get('istio_mesh_endpoint') istio_mesh_config = self.config_map[ist...
Generalize each ( single ) Istio instance into two OpenMetricsBaseCheck instances
def create_generic_instances(self, instances): """ Generalize each (single) Istio instance into two OpenMetricsBaseCheck instances """ generic_instances = [] for instance in instances: istio_mesh_instance = self._create_istio_mesh_instance(instance) proce...
Grab the istio mesh scraper from the dict and return it if it exists otherwise create the scraper and add it to the dict
def _create_istio_mesh_instance(self, instance): """ Grab the istio mesh scraper from the dict and return it if it exists, otherwise create the scraper and add it to the dict """ endpoint = instance.get('istio_mesh_endpoint') if endpoint is None: raise CheckE...
Grab the mixer scraper from the dict and return it if it exists otherwise create the scraper and add it to the dict
def _create_process_mixer_instance(self, instance): """ Grab the mixer scraper from the dict and return it if it exists, otherwise create the scraper and add it to the dict """ endpoint = instance.get('mixer_endpoint') if endpoint is None: raise CheckException...
The dictionary containing the apps is cached during collection and reset at every check () call.
def get_apps_json(self, url, timeout, auth, acs_url, ssl_verify, tags, group): """ The dictionary containing the apps is cached during collection and reset at every `check()` call. """ if self.apps_response is not None: return self.apps_response # Marathon ap...
Ensure marathon. queue. count is reported as zero for apps without queued instances.
def ensure_queue_count( self, queued, url, timeout, auth, acs_url, ssl_verify, tags=None, label_tags=None, group=None ): """ Ensure `marathon.queue.count` is reported as zero for apps without queued instances. """ metric_name = '{}.count'.format(self.QUEUE_PREFIX) ap...
Verify if a custom check or integration can run on python 3. CHECK can be an integration name or a valid path to a Python module or package folder.
def py3(check): """Verify if a custom check or integration can run on python 3. CHECK can be an integration name or a valid path to a Python module or package folder. """ if check in get_valid_checks(): path_to_module = os.path.dirname(get_version_file(check)) else: path_to_module =...
Create a config object from an instance dictionary
def from_instance(instance, default_ca_certs=None): """ Create a config object from an instance dictionary """ method = instance.get('method', 'get') data = instance.get('data', {}) tags = instance.get('tags', []) ntlm_domain = instance.get('ntlm_domain') username = instance.get('usernam...
Change the Python code in the __about__. py module so that __version__ contains the new value.
def update_version_module(check_name, old_ver, new_ver): """ Change the Python code in the __about__.py module so that `__version__` contains the new value. """ version_file = get_version_file(check_name) contents = read_file(version_file) contents = contents.replace(old_ver, new_ver) w...
Compose a text line to be used in a requirements. txt file to install a check pinned to a specific version.
def get_agent_requirement_line(check, version): """ Compose a text line to be used in a requirements.txt file to install a check pinned to a specific version. """ package_name = get_package_name(check) # no manifest if check in ('datadog_checks_base', 'datadog_checks_downloader'): r...
Replace the requirements line for the given check
def update_agent_requirements(req_file, check, newline): """ Replace the requirements line for the given check """ package_name = get_package_name(check) lines = read_file_lines(req_file) for i, line in enumerate(lines): current_package_name = line.split('==')[0] if current_pac...
Modified version of https:// docs. python. org/ 3/ library/ os. html#os. scandir that returns https:// docs. python. org/ 3/ library/ os. html#os. DirEntry for files directly to take advantage of possible cached os. stat calls.
def _walk(top): """Modified version of https://docs.python.org/3/library/os.html#os.scandir that returns https://docs.python.org/3/library/os.html#os.DirEntry for files directly to take advantage of possible cached os.stat calls. """ dirs = [] nondirs = [] try: scandir_iter = scandi...
Get metrics related to YARN cluster
def _yarn_cluster_metrics(self, rm_address, instance, addl_tags): """ Get metrics related to YARN cluster """ metrics_json = self._rest_request_to_json(rm_address, instance, YARN_CLUSTER_METRICS_PATH, addl_tags) if metrics_json: yarn_metrics = metrics_json[YARN_CLUS...
Get metrics for running applications
def _yarn_app_metrics(self, rm_address, instance, app_tags, addl_tags): """ Get metrics for running applications """ metrics_json = self._rest_request_to_json( rm_address, instance, YARN_APPS_PATH, addl_tags, states=YARN_APPLICATION_STATES ) if metrics_json a...
Get metrics related to YARN nodes
def _yarn_node_metrics(self, rm_address, instance, addl_tags): """ Get metrics related to YARN nodes """ metrics_json = self._rest_request_to_json(rm_address, instance, YARN_NODES_PATH, addl_tags) if metrics_json and metrics_json['nodes'] is not None and metrics_json['nodes']['n...
Get metrics from YARN scheduler
def _yarn_scheduler_metrics(self, rm_address, instance, addl_tags, queue_blacklist): """ Get metrics from YARN scheduler """ metrics_json = self._rest_request_to_json(rm_address, instance, YARN_SCHEDULER_PATH, addl_tags) try: metrics_json = metrics_json['scheduler'][...
Get metrics from YARN scheduler if it s type is capacityScheduler
def _yarn_capacity_scheduler_metrics(self, metrics_json, addl_tags, queue_blacklist): """ Get metrics from YARN scheduler if it's type is capacityScheduler """ tags = ['queue_name:{}'.format(metrics_json['queueName'])] tags.extend(addl_tags) self._set_yarn_metrics_from_j...
Parse the JSON response and set the metrics
def _set_yarn_metrics_from_json(self, tags, metrics_json, yarn_metrics): """ Parse the JSON response and set the metrics """ for dict_path, metric in iteritems(yarn_metrics): metric_name, metric_type = metric metric_value = self._get_value_from_json(dict_path, me...
Get a value from a dictionary under N keys represented as str ( key1. key2... key { n } )
def _get_value_from_json(self, dict_path, metrics_json): """ Get a value from a dictionary under N keys, represented as str("key1.key2...key{n}") """ for key in dict_path.split('.'): if key in metrics_json: metrics_json = metrics_json.get(key) else...
Set a metric
def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None): """ Set a metric """ if metric_type == GAUGE: self.gauge(metric_name, value, tags=tags, device_name=device_name) elif metric_type == INCREMENT: self.increment(metric_name,...
Query the given URL and return the JSON response
def _rest_request_to_json(self, url, instance, object_path, tags, *args, **kwargs): """ Query the given URL and return the JSON response """ service_check_tags = ['url:{}'.format(self._get_url_base(url))] + tags service_check_tags = list(set(service_check_tags)) if objec...
Join a URL with multiple directories
def _join_url_dir(self, url, *args): """ Join a URL with multiple directories """ for path in args: url = url.rstrip('/') + '/' url = urljoin(url, path.lstrip('/')) return url
Return the base of a URL
def _get_url_base(self, url): """ Return the base of a URL """ s = urlsplit(url) return urlunsplit([s.scheme, s.netloc, '', '', ''])
Get the ntp server port
def _get_service_port(self, instance): """ Get the ntp server port """ host = instance.get('host', DEFAULT_HOST) port = instance.get('port', DEFAULT_PORT) # default port is the name of the service but lookup would fail # if the /etc/services file is missing. In th...
Create a copy of the instance and set default values. This is so the base class can create a scraper_config with the proper values.
def _create_cadvisor_prometheus_instance(self, instance): """ Create a copy of the instance and set default values. This is so the base class can create a scraper_config with the proper values. """ cadvisor_instance = deepcopy(instance) cadvisor_instance.update( ...
Return whether a metric is about a container or not. It can be about pods or even higher levels in the cgroup hierarchy and we don t want to report on that.: param metric:: return: bool
def _is_container_metric(labels): """ Return whether a metric is about a container or not. It can be about pods, or even higher levels in the cgroup hierarchy and we don't want to report on that. :param metric: :return: bool """ for lbl in CONTAINER_LABELS...
Return whether a metric is about a pod or not. It can be about containers pods or higher levels in the cgroup hierarchy and we don t want to report on that.: param metric: return bool
def _is_pod_metric(labels): """ Return whether a metric is about a pod or not. It can be about containers, pods, or higher levels in the cgroup hierarchy and we don't want to report on that. :param metric :return bool """ if 'container_name' in labels: ...
Should only be called on a container - scoped metric It gets the container id from the podlist using the metrics labels
def _get_container_id(self, labels): """ Should only be called on a container-scoped metric It gets the container id from the podlist using the metrics labels :param labels :return str or None """ namespace = CadvisorPrometheusScraperMixin._get_container_label(la...
Checks the labels indicate a container metric then extract the container id from them.
def _get_entity_id_if_container_metric(self, labels): """ Checks the labels indicate a container metric, then extract the container id from them. :param labels :return str or None """ if CadvisorPrometheusScraperMixin._is_container_metric(labels): pod...
Return the id of a pod: param labels:: return: str or None
def _get_pod_uid(self, labels): """ Return the id of a pod :param labels: :return: str or None """ namespace = CadvisorPrometheusScraperMixin._get_container_label(labels, "namespace") pod_name = CadvisorPrometheusScraperMixin._get_container_label(labels, "pod_name...
Return if the pod is on host Network Return False if the Pod isn t in the pod list: param pod_uid: str: return: bool
def _is_pod_host_networked(self, pod_uid): """ Return if the pod is on host Network Return False if the Pod isn't in the pod list :param pod_uid: str :return: bool """ for pod in self.pod_list['items']: if pod.get('metadata', {}).get('uid', '') == pod_...
: param labels: metric labels: iterable: return:
def _get_pod_by_metric_label(self, labels): """ :param labels: metric labels: iterable :return: """ pod_uid = self._get_pod_uid(labels) return get_pod_by_uid(pod_uid, self.pod_list)
Iterates over all metrics in a metric and sums the values matching the same uid. Modifies the metric family in place.: param metric: prometheus metric family: param uid_from_labels: function mapping a metric. label to a unique context id: return: dict with uid as keys metric object references as values
def _sum_values_by_context(metric, uid_from_labels): """ Iterates over all metrics in a metric and sums the values matching the same uid. Modifies the metric family in place. :param metric: prometheus metric family :param uid_from_labels: function mapping a metric.label to a uniq...
Takes a simple metric about a container reports it as a rate or gauge. If several series are found for a given container values are summed before submission.
def _process_container_metric(self, type, metric_name, metric, scraper_config): """ Takes a simple metric about a container, reports it as a rate or gauge. If several series are found for a given container, values are summed before submission. """ if metric.type not in METRIC_TYP...
Takes a simple metric about a pod reports it as a rate. If several series are found for a given pod values are summed before submission.
def _process_pod_rate(self, metric_name, metric, scraper_config): """ Takes a simple metric about a pod, reports it as a rate. If several series are found for a given pod, values are summed before submission. """ if metric.type not in METRIC_TYPES: self.log.error("Met...
Takes a metric object a metric name and a cache dict where it will store container_name -- > ( value tags ) so that _process_limit_metric can compute usage_pct it also submit said value and tags as a gauge.
def _process_usage_metric(self, m_name, metric, cache, scraper_config): """ Takes a metric object, a metric name, and a cache dict where it will store container_name --> (value, tags) so that _process_limit_metric can compute usage_pct it also submit said value and tags as a gauge. ...
Reports limit metrics if m_name is not an empty string and optionally checks in the given cache if there s a usage for each sample in the metric and reports the usage_pct
def _process_limit_metric(self, m_name, metric, cache, scraper_config, pct_m_name=None): """ Reports limit metrics if m_name is not an empty string, and optionally checks in the given cache if there's a usage for each sample in the metric and reports the usage_pct """ sam...
Number of bytes that are consumed by the container on this filesystem.
def container_fs_usage_bytes(self, metric, scraper_config): """ Number of bytes that are consumed by the container on this filesystem. """ metric_name = scraper_config['namespace'] + '.filesystem.usage' if metric.type not in METRIC_TYPES: self.log.error("Metric type %...
Number of bytes that can be consumed by the container on this filesystem. This method is used by container_fs_usage_bytes it doesn t report any metric
def container_fs_limit_bytes(self, metric, scraper_config): """ Number of bytes that can be consumed by the container on this filesystem. This method is used by container_fs_usage_bytes, it doesn't report any metric """ pct_m_name = scraper_config['namespace'] + '.filesystem.usag...
Report the member s replica set state * Submit a service check. * Create an event on state change.
def _report_replica_set_state(self, state, clean_server_name, replset_name): """ Report the member's replica set state * Submit a service check. * Create an event on state change. """ last_state = self._last_state_by_server.get(clean_server_name, -1) self._last_st...
Return a reasonable hostname for a replset membership event to mention.
def hostname_for_event(self, clean_server_name): """Return a reasonable hostname for a replset membership event to mention.""" uri = urlsplit(clean_server_name) if '@' in uri.netloc: hostname = uri.netloc.split('@')[1].split(':')[0] else: hostname = uri.netloc.spl...
Create an event with a message describing the replication state of a mongo node
def create_event(self, last_state, state, clean_server_name, replset_name): """Create an event with a message describing the replication state of a mongo node""" status = self.get_state_description(state) short_status = self.get_state_name(state) last_short_status = self.get...
Build the metric list to collect based on the instance preferences.
def _build_metric_list_to_collect(self, additional_metrics): """ Build the metric list to collect based on the instance preferences. """ metrics_to_collect = {} # Defaut metrics for default_metrics in itervalues(self.DEFAULT_METRICS): metrics_to_collect.updat...
Return and cache the list of metrics to collect.
def _get_metrics_to_collect(self, instance_key, additional_metrics): """ Return and cache the list of metrics to collect. """ if instance_key not in self.metrics_to_collect_by_instance: self.metrics_to_collect_by_instance[instance_key] = self._build_metric_list_to_collect(add...
Return the submit method and the metric name to use.
def _resolve_metric(self, original_metric_name, metrics_to_collect, prefix=""): """ Return the submit method and the metric name to use. The metric name is defined as follow: * If available, the normalized metric name alias * (Or) the normalized original metric name """ ...
Replace case - sensitive metric name characters normalize the metric name prefix and suffix according to its type.
def _normalize(self, metric_name, submit_method, prefix): """ Replace case-sensitive metric name characters, normalize the metric name, prefix and suffix according to its type. """ metric_prefix = "mongodb." if not prefix else "mongodb.{0}.".format(prefix) metric_suffix =...
Authenticate to the database.
def _authenticate(self, database, username, password, use_x509, server_name, service_check_tags): """ Authenticate to the database. Available mechanisms: * Username & password * X.509 More information: https://api.mongodb.com/python/current/examples/authenticati...
Parses a MongoDB - formatted URI ( e. g. mongodb:// user: pass
def _parse_uri(cls, server, sanitize_username=False): """ Parses a MongoDB-formatted URI (e.g. mongodb://user:pass@server/db) and returns parsed elements and a sanitized URI. """ parsed = pymongo.uri_parser.parse_uri(server) username = parsed.get('username') pass...
Collect indexes statistics for all collections in the configuration. This use the $indexStats command.
def _collect_indexes_stats(self, instance, db, tags): """ Collect indexes statistics for all collections in the configuration. This use the "$indexStats" command. """ for coll_name in instance.get('collections', []): try: for stats in db[coll_name].agg...
Returns a dictionary that looks a lot like what s sent back by db. serverStatus ()
def check(self, instance): """ Returns a dictionary that looks a lot like what's sent back by db.serverStatus() """ def total_seconds(td): """ Returns total seconds of a timedelta in a way that's safe for Python < 2.7 """ ...
Get the connection either with a username and password or without
def get_normal_connection(config): """ Get the connection either with a username and password or without """ if config.username and config.password: log.debug("connecting with username and password") queue_manager = pymqi.connect( config.queue_manager_name, config.channel, co...
Get the connection with SSL
def get_ssl_connection(config): """ Get the connection with SSL """ cd = pymqi.CD() cd.ChannelName = config.channel cd.ConnectionName = config.host_and_port cd.ChannelType = pymqi.CMQC.MQCHT_CLNTCONN cd.TransportType = pymqi.CMQC.MQXPT_TCP cd.SSLCipherSpec = config.ssl_cipher_spec ...
Run an Agent check.
def check_run(check, env, rate, times, pause, delay, log_level, as_json, break_point): """Run an Agent check.""" 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 {}`....
Parse user identity out of init_config
def get_user_identity(cls, instance_config): """ Parse user identity out of init_config To guarantee a uniquely identifiable user, expects {"user": {"name": "my_username", "password": "my_password", "domain": {"id": "my_domain_id"} } } ...
Parse authorization scope out of init_config
def get_auth_scope(cls, instance_config): """ Parse authorization scope out of init_config To guarantee a uniquely identifiable scope, expects either: {'project': {'name': 'my_project', 'domain': {'id': 'my_domain_id'}}} OR {'project': {'id': 'my_project_id'}} ""...
Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog
def get_neutron_endpoint(cls, json_resp): """ Parse the service catalog returned by the Identity API for an endpoint matching the Neutron service Sends a CRITICAL service check when none are found registered in the Catalog """ catalog = json_resp.get('token', {}).get('catalog', [...
Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog
def get_nova_endpoint(cls, json_resp, nova_api_version=None): """ Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog """ ...
Generic request handler for OpenStack API requests Raises specialized Exceptions for commonly encountered error codes
def _make_request_with_auth_fallback(self, url, headers=None, params=None): """ Generic request handler for OpenStack API requests Raises specialized Exceptions for commonly encountered error codes """ self.log.debug("Request URL and Params: %s, %s", url, params) try: ...
Collect stats for all reachable networks
def get_network_stats(self, tags): """ Collect stats for all reachable networks """ # FIXME: (aaditya) Check all networks defaults to true # until we can reliably assign agents to networks to monitor if is_affirmative(self.init_config.get('check_all_networks', True)): ...
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(':')[1].split(',') uptime_sec = uptime.split(',')[0] return {'load...
Guarantees a valid auth scope for this instance and returns it
def ensure_auth_scope(self, instance): """ 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 """ instance_scope = None ...
Returns the hypervisor running on this host and assumes a 1 - 1 between host and hypervisor
def get_local_hypervisor(self): """ Returns the hypervisor running on this host, and assumes a 1-1 between host and hypervisor """ # Look up hypervisors available filtered by my hostname host = self.get_my_hostname() hyp = self.get_all_hypervisor_ids(filter_by_host=host) ...
Returns all projects in the domain
def get_all_projects(self, scope): """ Returns all projects in the domain """ url = "{0}/{1}/{2}".format(self.keystone_server_url, DEFAULT_KEYSTONE_API_VERSION, "projects") headers = {'X-Auth-Token': scope.auth_token} try: r = self._make_request_with_auth_fall...
Returns the project that this instance of the check is scoped to
def get_scoped_project(self, project_auth_scope): """ Returns the project that this instance of the check is scoped to """ filter_params = {} url = "{0}/{1}/{2}".format(self.keystone_server_url, DEFAULT_KEYSTONE_API_VERSION, "projects") if project_auth_scope.tenant_id: ...
Returns a best guess for the hostname registered with OpenStack for this host
def get_my_hostname(self, split_hostname_on_first_period=False): """ Returns a best guess for the hostname registered with OpenStack for this host """ hostname = self.init_config.get("os_host") or self.hostname if split_hostname_on_first_period: hostname = hostname.s...
Returns a list of tags for every guest server that is detected by the OpenStack integration. List of pairs ( hostname list_of_tags )
def get_external_host_tags(self): """ Returns a list of tags for every guest server that is detected by the OpenStack integration. List of pairs (hostname, list_of_tags) """ self.log.debug("Collecting external_host_tags now") external_host_tags = [] for k, v in it...