INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Get a single document from the database.
def find_one(self, filter=None, *args, **kwargs): """Get a single document from the database. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single document, or ``None`` if no matching documen...
Scan this entire collection in parallel.
def parallel_scan(self, num_cursors, **kwargs): """Scan this entire collection in parallel. Returns a list of up to ``num_cursors`` cursors that can be iterated concurrently. As long as the collection is not modified during scanning, each document appears once in one of the cursors resu...
Internal count helper.
def _count(self, cmd, collation=None): """Internal count helper.""" with self._socket_for_reads() as (sock_info, slave_ok): res = self._command( sock_info, cmd, slave_ok, allowable_errors=["ns missing"], codec_options=self.__write_response_code...
Get the number of documents in this collection.
def count(self, filter=None, **kwargs): """Get the number of documents in this collection. All optional count parameters should be passed as keyword arguments to this method. Valid options include: - `hint` (string or list of tuples): The index to use. Specify either the ...
Create one or more indexes on this collection.
def create_indexes(self, indexes): """Create one or more indexes on this collection. >>> from pymongo import IndexModel, ASCENDING, DESCENDING >>> index1 = IndexModel([("hello", DESCENDING), ... ("world", ASCENDING)], name="hello_world") >>> index2 =...
Internal create index helper.
def __create_index(self, keys, index_options): """Internal create index helper. :Parameters: - `keys`: a list of tuples [(key, type), (key, type), ...] - `index_options`: a dict of index options. """ index_doc = helpers._index_document(keys) index = {"key": i...
Creates an index on this collection.
def create_index(self, keys, **kwargs): """Creates an index on this collection. Takes either a single key or a list of (key, direction) pairs. The key(s) must be an instance of :class:`basestring` (:class:`str` in python 3), and the direction(s) must be one of (:data:`~pymongo.A...
** DEPRECATED ** - Ensures that an index exists on this collection.
def ensure_index(self, key_or_list, cache_for=300, **kwargs): """**DEPRECATED** - Ensures that an index exists on this collection. .. versionchanged:: 3.0 **DEPRECATED** """ warnings.warn("ensure_index is deprecated. Use create_index instead.", Deprecat...
Drops all indexes on this collection.
def drop_indexes(self): """Drops all indexes on this collection. Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automaticall...
Drops the specified index on this collection.
def drop_index(self, index_or_name): """Drops the specified index on this collection. Can be used on non-existant collections or collections with no indexes. Raises OperationFailure on an error (e.g. trying to drop an index that does not exist). `index_or_name` can be either an...
Rebuilds all indexes on this collection.
def reindex(self): """Rebuilds all indexes on this collection. .. warning:: reindex blocks all other operations (indexes are built in the foreground) and will be slow for large collections. .. versionchanged:: 3.4 Apply this collection's write concern automatic...
Get a cursor over the index documents for this collection.
def list_indexes(self): """Get a cursor over the index documents for this collection. >>> for index in db.test.list_indexes(): ... print(index) ... SON([(u'v', 1), (u'key', SON([(u'_id', 1)])), (u'name', u'_id_'), (u'ns', u'test.test')]) :Retu...
Get the options set on this collection.
def options(self): """Get the options set on this collection. Returns a dictionary of options and their values - see :meth:`~pymongo.database.Database.create_collection` for more information on the possible options. Returns an empty dictionary if the collection has not been crea...
Perform an aggregation using the aggregation framework on this collection.
def aggregate(self, pipeline, **kwargs): """Perform an aggregation using the aggregation framework on this collection. All optional aggregate parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to: - `allowDiskUse` (bool...
Rename this collection.
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :clas...
Get a list of distinct values for key among all documents in this collection.
def distinct(self, key, filter=None, **kwargs): """Get a list of distinct values for `key` among all documents in this collection. Raises :class:`TypeError` if `key` is not an instance of :class:`basestring` (:class:`str` in python 3). All optional distinct parameters should be...
Perform a map/ reduce operation on this collection.
def map_reduce(self, map, reduce, out, full_response=False, **kwargs): """Perform a map/reduce operation on this collection. If `full_response` is ``False`` (default) returns a :class:`~pymongo.collection.Collection` instance containing the results of the operation. Otherwise, returns t...
Perform an inline map/ reduce operation on this collection.
def inline_map_reduce(self, map, reduce, full_response=False, **kwargs): """Perform an inline map/reduce operation on this collection. Perform the map/reduce operation on the server in RAM. A result collection is not created. The result set is returned as a list of documents. I...
Internal findAndModify helper.
def __find_and_modify(self, filter, projection, sort, upsert=None, return_document=ReturnDocument.BEFORE, **kwargs): """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isinstance(return_document, bool): raise ValueError(...
Finds a single document and replaces it returning either the original or the replaced document.
def find_one_and_replace(self, filter, replacement, projection=None, sort=None, upsert=False, return_document=ReturnDocument.BEFORE, **kwargs): """Finds a single document and replaces it, returning either the original or the replaced document. ...
Finds a single document and updates it returning either the original or the updated document.
def find_one_and_update(self, filter, update, projection=None, sort=None, upsert=False, return_document=ReturnDocument.BEFORE, **kwargs): """Finds a single document and updates it, returning either the original or the updated document. >...
Save a document in this collection.
def save(self, to_save, manipulate=True, check_keys=True, **kwargs): """Save a document in this collection. **DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead. .. versionchanged:: 3.0 Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write ...
Insert a document ( s ) into this collection.
def insert(self, doc_or_docs, manipulate=True, check_keys=True, continue_on_error=False, **kwargs): """Insert a document(s) into this collection. **DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead. .. versionchanged:: 3.0 Removed the `safe` paramet...
Update a document ( s ) in this collection.
def update(self, spec, document, upsert=False, manipulate=False, multi=False, check_keys=True, **kwargs): """Update a document(s) in this collection. **DEPRECATED** - Use :meth:`replace_one`, :meth:`update_one`, or :meth:`update_many` instead. .. versionchanged:: 3.0 ...
Remove a document ( s ) from this collection.
def remove(self, spec_or_id=None, multi=True, **kwargs): """Remove a document(s) from this collection. **DEPRECATED** - Use :meth:`delete_one` or :meth:`delete_many` instead. .. versionchanged:: 3.0 Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write opera...
Update and return an object.
def find_and_modify(self, query={}, update=None, upsert=False, sort=None, full_response=False, manipulate=False, **kwargs): """Update and return an object. **DEPRECATED** - Use :meth:`find_one_and_delete`, :meth:`find_one_and_replace`, or :meth:`f...
Convert a Python regular expression into a Regex instance.
def from_native(cls, regex): """Convert a Python regular expression into a ``Regex`` instance. Note that in Python 3, a regular expression compiled from a :class:`str` has the ``re.UNICODE`` flag set. If it is undesirable to store this flag in a BSON regular expression, unset it first::...
Decode a BSON int32 to python int.
def _get_int(data, position, dummy0, dummy1, dummy2): """Decode a BSON int32 to python int.""" end = position + 4 return _UNPACK_INT(data[position:end])[0], end
Decode a BSON double to python float.
def _get_float(data, position, dummy0, dummy1, dummy2): """Decode a BSON double to python float.""" end = position + 8 return _UNPACK_FLOAT(data[position:end])[0], end
Decode a BSON subdocument to opts. document_class or bson. dbref. DBRef.
def _get_object(data, position, obj_end, opts, dummy): """Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.""" obj_size = _UNPACK_INT(data[position:position + 4])[0] end = position + obj_size - 1 if data[end:position + obj_size] != b"\x00": raise InvalidBSON("bad eoo") if...
Decode a BSON array to python list.
def _get_array(data, position, obj_end, opts, element_name): """Decode a BSON array to python list.""" size = _UNPACK_INT(data[position:position + 4])[0] end = position + size - 1 if data[end:end + 1] != b"\x00": raise InvalidBSON("bad eoo") position += 4 end -= 1 result = [] #...
Decode a BSON binary to bson. binary. Binary or python UUID.
def _get_binary(data, position, obj_end, opts, dummy1): """Decode a BSON binary to bson.binary.Binary or python UUID.""" length, subtype = _UNPACK_LENGTH_SUBTYPE(data[position:position + 5]) position += 5 if subtype == 2: length2 = _UNPACK_INT(data[position:position + 4])[0] position += ...
Decode a BSON ObjectId to bson. objectid. ObjectId.
def _get_oid(data, position, dummy0, dummy1, dummy2): """Decode a BSON ObjectId to bson.objectid.ObjectId.""" end = position + 12 return ObjectId(data[position:end]), end
Decode a BSON true/ false to python True/ False.
def _get_boolean(data, position, dummy0, dummy1, dummy2): """Decode a BSON true/false to python True/False.""" end = position + 1 boolean_byte = data[position:end] if boolean_byte == b'\x00': return False, end elif boolean_byte == b'\x01': return True, end raise InvalidBSON('inva...
Decode a BSON datetime to python datetime. datetime.
def _get_date(data, position, dummy0, opts, dummy1): """Decode a BSON datetime to python datetime.datetime.""" end = position + 8 millis = _UNPACK_LONG(data[position:end])[0] return _millis_to_datetime(millis, opts), end
Decode a BSON code to bson. code. Code.
def _get_code(data, position, obj_end, opts, element_name): """Decode a BSON code to bson.code.Code.""" code, position = _get_string(data, position, obj_end, opts, element_name) return Code(code), position
Decode a BSON code_w_scope to bson. code. Code.
def _get_code_w_scope(data, position, obj_end, opts, element_name): """Decode a BSON code_w_scope to bson.code.Code.""" code_end = position + _UNPACK_INT(data[position:position + 4])[0] code, position = _get_string( data, position + 4, code_end, opts, element_name) scope, position = _get_object(...
Decode ( deprecated ) BSON DBPointer to bson. dbref. DBRef.
def _get_ref(data, position, obj_end, opts, element_name): """Decode (deprecated) BSON DBPointer to bson.dbref.DBRef.""" collection, position = _get_string( data, position, obj_end, opts, element_name) oid, position = _get_oid(data, position, obj_end, opts, element_name) return DBRef(collection,...
Decode a BSON timestamp to bson. timestamp. Timestamp.
def _get_timestamp(data, position, dummy0, dummy1, dummy2): """Decode a BSON timestamp to bson.timestamp.Timestamp.""" end = position + 8 inc, timestamp = _UNPACK_TIMESTAMP(data[position:end]) return Timestamp(timestamp, inc), end
Decode a BSON int64 to bson. int64. Int64.
def _get_int64(data, position, dummy0, dummy1, dummy2): """Decode a BSON int64 to bson.int64.Int64.""" end = position + 8 return Int64(_UNPACK_LONG(data[position:end])[0]), end
Decode a BSON decimal128 to bson. decimal128. Decimal128.
def _get_decimal128(data, position, dummy0, dummy1, dummy2): """Decode a BSON decimal128 to bson.decimal128.Decimal128.""" end = position + 16 return Decimal128.from_bid(data[position:end]), end
Decode a single key value pair.
def _element_to_dict(data, position, obj_end, opts): """Decode a single key, value pair.""" element_type = data[position:position + 1] position += 1 element_name, position = _get_c_string(data, position, opts) try: value, position = _ELEMENT_GETTER[element_type](data, position, ...
Decode a BSON document.
def _elements_to_dict(data, position, obj_end, opts): """Decode a BSON document.""" result = opts.document_class() pos = position for key, value, pos in _iterate_elements(data, position, obj_end, opts): result[key] = value if pos != obj_end: raise InvalidBSON('bad object or element l...
Generate keys for encoded lists in the sequence b 0 \ x00 b 1 \ x00 b 2 \ x00...
def gen_list_name(): """Generate "keys" for encoded lists in the sequence b"0\x00", b"1\x00", b"2\x00", ... The first 1000 keys are returned from a pre-built cache. All subsequent keys are generated on the fly. """ for name in _LIST_NAMES: yield name counter = itertools.count(1000)...
Make a C string checking for embedded NUL characters.
def _make_c_string_check(string): """Make a 'C' string, checking for embedded NUL characters.""" if isinstance(string, bytes): if b"\x00" in string: raise InvalidDocument("BSON keys / regex patterns must not " "contain a NUL character") try: ...
Make a C string.
def _make_c_string(string): """Make a 'C' string.""" if isinstance(string, bytes): try: _utf_8_decode(string, None, True) return string + b"\x00" except UnicodeError: raise InvalidStringData("strings in documents must be valid " ...
Encode bson. dbref. DBRef.
def _encode_dbref(name, value, check_keys, opts): """Encode bson.dbref.DBRef.""" buf = bytearray(b"\x03" + name + b"\x00\x00\x00\x00") begin = len(buf) - 4 buf += _name_value_to_bson(b"$ref\x00", value.collection, check_keys, opts) buf += _name_value_to_bson(b"$id\x00...
Encode a list/ tuple.
def _encode_list(name, value, check_keys, opts): """Encode a list/tuple.""" lname = gen_list_name() data = b"".join([_name_value_to_bson(next(lname), item, check_keys, opts) for item in value]) return b"\x04" + name + _PACK_INT(len(data) + 5)...
Encode a python unicode ( python 2. x )/ str ( python 3. x ).
def _encode_text(name, value, dummy0, dummy1): """Encode a python unicode (python 2.x) / str (python 3.x).""" value = _utf_8_encode(value)[0] return b"\x02" + name + _PACK_INT(len(value) + 1) + value + b"\x00"
Encode bson. binary. Binary.
def _encode_binary(name, value, dummy0, dummy1): """Encode bson.binary.Binary.""" subtype = value.subtype if subtype == 2: value = _PACK_INT(len(value)) + value return b"\x05" + name + _PACK_LENGTH_SUBTYPE(len(value), subtype) + value
Encode uuid. UUID.
def _encode_uuid(name, value, dummy, opts): """Encode uuid.UUID.""" uuid_representation = opts.uuid_representation # Python Legacy Common Case if uuid_representation == OLD_UUID_SUBTYPE: return b"\x05" + name + b'\x10\x00\x00\x00\x03' + value.bytes # Java Legacy elif uuid_representation ...
Encode a python boolean ( True/ False ).
def _encode_bool(name, value, dummy0, dummy1): """Encode a python boolean (True/False).""" return b"\x08" + name + (value and b"\x01" or b"\x00")
Encode datetime. datetime.
def _encode_datetime(name, value, dummy0, dummy1): """Encode datetime.datetime.""" millis = _datetime_to_millis(value) return b"\x09" + name + _PACK_LONG(millis)
Encode a python regex or bson. regex. Regex.
def _encode_regex(name, value, dummy0, dummy1): """Encode a python regex or bson.regex.Regex.""" flags = value.flags # Python 2 common case if flags == 0: return b"\x0B" + name + _make_c_string_check(value.pattern) + b"\x00" # Python 3 common case elif flags == re.UNICODE: return...
Encode a python int.
def _encode_int(name, value, dummy0, dummy1): """Encode a python int.""" if -2147483648 <= value <= 2147483647: return b"\x10" + name + _PACK_INT(value) else: try: return b"\x12" + name + _PACK_LONG(value) except struct.error: raise OverflowError("BSON can onl...
Encode bson. timestamp. Timestamp.
def _encode_timestamp(name, value, dummy0, dummy1): """Encode bson.timestamp.Timestamp.""" return b"\x11" + name + _PACK_TIMESTAMP(value.inc, value.time)
Encode a python long ( python 2. x )
def _encode_long(name, value, dummy0, dummy1): """Encode a python long (python 2.x)""" try: return b"\x12" + name + _PACK_LONG(value) except struct.error: raise OverflowError("BSON can only handle up to 8-byte ints")
Encode a single name value pair.
def _name_value_to_bson(name, value, check_keys, opts): """Encode a single name, value pair.""" # First see if the type is already cached. KeyError will only ever # happen once per subtype. try: return _ENCODERS[type(value)](name, value, check_keys, opts) except KeyError: pass ...
Encode a single key value pair.
def _element_to_bson(key, value, check_keys, opts): """Encode a single key, value pair.""" if not isinstance(key, string_type): raise InvalidDocument("documents must have only string keys, " "key was %r" % (key,)) if check_keys: if key.startswith("$"): ...
Encode a document to BSON.
def _dict_to_bson(doc, check_keys, opts, top_level=True): """Encode a document to BSON.""" if _raw_document_class(doc): return doc.raw try: elements = [] if top_level and "_id" in doc: elements.append(_name_value_to_bson(b"_id\x00", doc["_id"], ...
Convert milliseconds since epoch UTC to datetime.
def _millis_to_datetime(millis, opts): """Convert milliseconds since epoch UTC to datetime.""" diff = ((millis % 1000) + 1000) % 1000 seconds = (millis - diff) / 1000 micros = diff * 1000 if opts.tz_aware: dt = EPOCH_AWARE + datetime.timedelta(seconds=seconds, ...
Decode BSON data to multiple documents.
def decode_all(data, codec_options=DEFAULT_CODEC_OPTIONS): """Decode BSON data to multiple documents. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `data`: BSON data - `codec_options` (optional): An instance of :class:`~bson.codec_options.Co...
Decode BSON data to multiple documents as a generator.
def decode_iter(data, codec_options=DEFAULT_CODEC_OPTIONS): """Decode BSON data to multiple documents as a generator. Works similarly to the decode_all function, but yields one document at a time. `data` must be a string of concatenated, valid, BSON-encoded documents. :Parameters: - `da...
Decode bson data from a file to multiple documents as a generator.
def decode_file_iter(file_obj, codec_options=DEFAULT_CODEC_OPTIONS): """Decode bson data from a file to multiple documents as a generator. Works similarly to the decode_all function, but reads from the file object in chunks and parses bson in chunks, yielding one document at a time. :Parameters: ...
Check that the given string represents valid: class: BSON data.
def is_valid(bson): """Check that the given string represents valid :class:`BSON` data. Raises :class:`TypeError` if `bson` is not an instance of :class:`str` (:class:`bytes` in python 3). Returns ``True`` if `bson` is valid :class:`BSON`, ``False`` otherwise. :Parameters: - `bson`: the data...
Encode a document to a new: class: BSON instance.
def encode(cls, document, check_keys=False, codec_options=DEFAULT_CODEC_OPTIONS): """Encode a document to a new :class:`BSON` instance. A document can be any mapping type (like :class:`dict`). Raises :class:`TypeError` if `document` is not a mapping type, or contains key...
Decode this BSON data.
def decode(self, codec_options=DEFAULT_CODEC_OPTIONS): """Decode this BSON data. By default, returns a BSON document represented as a Python :class:`dict`. To use a different :class:`MutableMapping` class, configure a :class:`~bson.codec_options.CodecOptions`:: >>> import c...
This is a stub to allow a check requiring Popen to run without an Agent ( e. g. during tests or development ) it s not supposed to be used anywhere outside the datadog_checks. utils package.
def subprocess_output(command, raise_on_empty_output): """ This is a stub to allow a check requiring `Popen` to run without an Agent (e.g. during tests or development), it's not supposed to be used anywhere outside the `datadog_checks.utils` package. """ # Use tempfile, allowing a larger amount of ...
Helper to generate a list of ( key direction ) pairs.
def _index_list(key_or_list, direction=None): """Helper to generate a list of (key, direction) pairs. Takes such a list, or a single key, or a single key and direction. """ if direction is not None: return [(key_or_list, direction)] else: if isinstance(key_or_list, string_type): ...
Unpack a response from the database.
def _unpack_response(response, cursor_id=None, codec_options=_UNICODE_REPLACE_CODEC_OPTIONS): """Unpack a response from the database. Check the response for errors and unpack, returning a dictionary containing the response data. Can raise CursorNotFound, NotMa...
Check the response to a command for errors.
def _check_command_response(response, msg=None, allowable_errors=None, parse_write_concern_error=False): """Check the response to a command for errors. """ if "ok" not in response: # Server didn't recognize our message as a command. raise OperationFailure(response...
Simple query helper for retrieving a first ( and possibly only ) batch.
def _first_batch(sock_info, db, coll, query, ntoreturn, slave_ok, codec_options, read_preference, cmd, listeners): """Simple query helper for retrieving a first (and possibly only) batch.""" query = _Query( 0, db, coll, 0, query, None, codec_options, read_preference, ntoreturn, ...
Backward compatibility helper for write command error handling.
def _check_write_command_response(results): """Backward compatibility helper for write command error handling. """ errors = [res for res in results if "writeErrors" in res[1] or "writeConcernError" in res[1]] if errors: # If multiple batches had errors # raise from the last...
Takes a sequence of field names and returns a matching dictionary.
def _fields_list_to_dict(fields, option_name): """Takes a sequence of field names and returns a matching dictionary. ["a", "b"] becomes {"a": 1, "b": 1} and ["a.b.c", "d", "a.c"] becomes {"a.b.c": 1, "d": 1, "a.c": 1} """ if isinstance(fields, collections.Mapping): return fields ...
Print exceptions raised by subscribers to stderr.
def _handle_exception(): """Print exceptions raised by subscribers to stderr.""" # Heavily influenced by logging.Handler.handleError. # See note here: # https://docs.python.org/3.4/library/sys.html#sys.__stderr__ if sys.stderr: einfo = sys.exc_info() try: traceback.print...
Set up the kubernetes_state instance so it can be used in OpenMetricsBaseCheck
def _create_kubernetes_state_prometheus_instance(self, instance): """ Set up the kubernetes_state instance so it can be used in OpenMetricsBaseCheck """ ksm_instance = deepcopy(instance) endpoint = instance.get('kube_state_url') if endpoint is None: raise Chec...
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:
def _condition_to_service_check(self, sample, sc_name, mapping, tags=None): """ 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: ...
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 { la...
def _condition_to_tag_check(self, sample, base_sc_name, mapping, scraper_config, tags=None): """ 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_cond...
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 string """ return '%s:%s' % (scraper_config['labels_mapper'].get(name, name), value)
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 string. Tag name is label name if not specified. Returns None if name was not found. """ value = labels.get(name) if value: ...
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-data issues on pod ...
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_schedule_check' curr_time...
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_counter = Counter() for sample in...
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", sample[self.SAMPLE_LABELS], scraper_config...
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 metric.samples: node_tag = self._label_to_tag("node"...
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: for sample in metric.samples: ...
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_TYPES: for sample in metric.sa...
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/kubernetes/blob/v1.6.1/pkg/api/v1/types...
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'], config['metric_name']) object_counter = Counter() ...
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: pod uid :param podlist: podlist dict object :return: pod dict object if found, None if not found """ for pod in podlist.get("items", []): try: if pod["meta...
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: bool """ try: if pod["metadata"]["annotations"]["kubernetes.io/config.source"] == "api": return False p...
Queries the agent6 container filter interface. It retrieves container name + image from the podlist so static pod filtering is not supported.
def is_excluded(self, cid, pod_uid=None): """ 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 metric...
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) else: return None
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 queried, including scheme :return: dict or None """ if self._token and url.lower().startswith('https'): return {'Authorization': 'Be...
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 PrometheusScaper object :param endpoint: url that will be scraped """ endpoint = scraper_config['prometheus_url'] scraper_config.upda...
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 = result.stdout.splitlines() # Remove empty lines return [f for f in ch...
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=%s {}{}'.format('' if target_tag is None else '{}... '.format(target_tag)...
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 = run_command('git add{} {}'.format(' -f' if...
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 result return run_c...