INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Update the last experiment group's iteration with experiment performance.
def update_iteration(self): """Update the last experiment group's iteration with experiment performance.""" iteration_config = self.get_iteration_config() if not iteration_config: return experiments_metrics = self.experiment_group.get_experiments_metrics( experime...
Update iteration's num_suggestions.
def update_iteration_num_suggestions(self, num_suggestions): """Update iteration's num_suggestions.""" iteration_config = self.experiment_group.iteration_config iteration_config.num_suggestions = num_suggestions self._update_config(iteration_config)
We only validate the config if passed. Also we use the ExperimentSpecification to check if this config was intended as an experiment.
def validate_config(self, config): """We only validate the config if passed. Also we use the ExperimentSpecification to check if this config was intended as an experiment. """ # config is optional if not config: return config spec = validate_experime...
Return the second part of the event_type e.g. >>> Event.event_type = 'experiment.deleted' >>> Event.get_event_action() == 'deleted'
def get_event_action(cls) -> Optional[str]: """Return the second part of the event_type e.g. >>> Event.event_type = 'experiment.deleted' >>> Event.get_event_action() == 'deleted' """ if not cls.actor: return None return event_context.get_event_action...
Get or Create a build job based on the params. If a build job already exists, then we check if the build has already an image created. If the image does not exists, and the job is already done we force create a new job. Returns: tuple: (build_job, image_exists[bool], build_status[bool])
def create_build_job(user, project, config, code_reference, configmap_refs=None, secret_refs=None): """Get or Create a build job based on the params. If a build job already exists, then we check if the build has already an image created. If the image does not exists, and the job is already done we force cr...
Scan a YAML stream and produce scanning tokens.
def scan(stream, Loader=Loader): """ Scan a YAML stream and produce scanning tokens. """ loader = Loader(stream) try: while loader.check_token(): yield loader.get_token() finally: loader.dispose()
Parse a YAML stream and produce parsing events.
def parse(stream, Loader=Loader): """ Parse a YAML stream and produce parsing events. """ loader = Loader(stream) try: while loader.check_event(): yield loader.get_event() finally: loader.dispose()
Parse the first YAML document in a stream and produce the corresponding representation tree.
def compose(stream, Loader=Loader): """ Parse the first YAML document in a stream and produce the corresponding representation tree. """ loader = Loader(stream) try: return loader.get_single_node() finally: loader.dispose()
Parse all YAML documents in a stream and produce corresponding representation trees.
def compose_all(stream, Loader=Loader): """ Parse all YAML documents in a stream and produce corresponding representation trees. """ loader = Loader(stream) try: while loader.check_node(): yield loader.get_node() finally: loader.dispose()
Parse the first YAML document in a stream and produce the corresponding Python object.
def load(stream, Loader=None): """ Parse the first YAML document in a stream and produce the corresponding Python object. """ if Loader is None: load_warning('load') Loader = FullLoader loader = Loader(stream) try: return loader.get_single_data() finally: ...
Parse all YAML documents in a stream and produce corresponding Python objects.
def load_all(stream, Loader=None): """ Parse all YAML documents in a stream and produce corresponding Python objects. """ if Loader is None: load_warning('load_all') Loader = FullLoader loader = Loader(stream) try: while loader.check_data(): yield loader....
Emit YAML parsing events into a stream. If stream is None, return the produced string instead.
def emit(events, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): """ Emit YAML parsing events into a stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: from Strin...
Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead.
def serialize(node, stream=None, Dumper=Dumper, **kwds): """ Serialize a representation tree into a YAML stream. If stream is None, return the produced string instead. """ return serialize_all([node], stream, Dumper=Dumper, **kwds)
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
def dump(data, stream=None, Dumper=Dumper, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=Dumper, **kwds)
Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead.
def safe_dump_all(documents, stream=None, **kwds): """ Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. """ return dump_all(documents, stream, Dumper=SafeDumper, **kwds)
Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead.
def safe_dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=SafeDumper, **kwds)
Add an implicit scalar detector. If an implicit scalar value matches the given regexp, the corresponding tag is assigned to the scalar. first is a sequence of possible initial characters or None.
def add_implicit_resolver(tag, regexp, first=None, Loader=Loader, Dumper=Dumper): """ Add an implicit scalar detector. If an implicit scalar value matches the given regexp, the corresponding tag is assigned to the scalar. first is a sequence of possible initial characters or None. """ ...
Add a path based resolver for the given tag. A path is a list of keys that forms a path to a node in the representation tree. Keys can be string values, integers, or None.
def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper): """ Add a path based resolver for the given tag. A path is a list of keys that forms a path to a node in the representation tree. Keys can be string values, integers, or None. """ Loader.add_path_resolver(tag, path, k...
Convert a Python object to a representation node.
def to_yaml(cls, dumper, data): """ Convert a Python object to a representation node. """ return dumper.represent_yaml_object(cls.yaml_tag, data, cls, flow_style=cls.yaml_flow_style)
Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.
def serialize_all(nodes, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize a sequence of representation trees into a YAML stream....
Do not produce empty tokens.
def something(TokenClass): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), TokenClass, text context.pos = match.end() return callback
Set the previously saved indentation level.
def set_indent(TokenClass, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_inden...
Process an empty line in a block scalar.
def parse_block_scalar_empty_line(IndentTokenClass, ContentTokenClass): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if te...
Process indentation spaces in a plain scalar.
def parse_plain_scalar_indent(TokenClass): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: ...
Collocation score
def score(count_bigram, count1, count2, n_words): """Collocation score""" if n_words <= count1 or n_words <= count2: # only one words appears in the whole document return 0 N = n_words c12 = count_bigram c1 = count1 c2 = count2 p = c2 / N p1 = c12 / c1 p2 = (c2 - c12)...
Normalize cases and remove plurals. Each word is represented by the most common case. If a word appears with an "s" on the end and without an "s" on the end, the version with "s" is assumed to be a plural and merged with the version without "s" (except if the word ends with "ss"). Parameters -...
def process_tokens(words, normalize_plurals=True): """Normalize cases and remove plurals. Each word is represented by the most common case. If a word appears with an "s" on the end and without an "s" on the end, the version with "s" is assumed to be a plural and merged with the version without "s" ...
Returns a single_color_func associated with the word
def get_color_func(self, word): """Returns a single_color_func associated with the word""" try: color_func = next( color_func for (color_func, words) in self.color_func_to_words if word in words) except StopIteration: color_func = self.defa...
Random hue color generation. Default coloring method. This just picks a random hue with value 80% and lumination 50%. Parameters ---------- word, font_size, position, orientation : ignored. random_state : random.Random object or None, (default=None) If a random object is given, this ...
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None): """Random hue color generation. Default coloring method. This just picks a random hue with value 80% and lumination 50%. Parameters ---------- word, font_...
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')
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. Parameters ---------- frequencies : dict from string to float A contains words and associated frequency. max_font_size : int Use this font-size instead of self.max_font_size Returns ------- ...
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. Parameters ---------- text : string The text to be processed. Returns ------- words : dict (string, int) Word tokens with associated frequency. ..versionchanged:: 1.2.2 ...
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. 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 generate_from_frequencies. ..versionchang...
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. Applying a new coloring is much faster than generating the whole wordcloud. Parameters ---------- random_state : RandomState, int, or None, default=None If not None, a fixed random state is used. If an int is given, this is used ...
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. Parameters ---------- filename : string Location to write to. Returns ------- self
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. An integration warning is sent if the object is not retrievable, or no record is found. Monitors on the service-check should have no-data alerts enabled to account for this. T...
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. 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 separator. If the separator is not ...
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. 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 the separator. If the separator is no...
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. Returns a 2-tuple containing the unescaped username followed by the unescaped password. :Paramaters: - `userinfo`: A string of the form <username>:<...
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. 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 in braces (e.g. '[::1]' or '[::1]:27017'). ...
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 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 address. - `default_port`: The port number to use...
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. Returns a set of 2-tuples containing the host name (or IP) followed by port number. :Parameters: - `hosts`: A string of the form host1[:port],h...
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. Returns a dict of the form:: { 'nodelist': <list of (host, port) tuples>, 'username': <username> or None, 'password': <password> or None, 'database': <database name> or None, 'collection': <collection name> or No...
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. Consider `event_format` parameter: * Only use the specified list of event properties. * If unspecified, default to the EventLog's `Message` or `InsertionStrings`.
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. 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 requires an `address` argument.
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 :param labels :return str or None
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. :param labels :return str or None
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 refer...
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 %...