text
stringlengths
81
112k
Fetch WMI metrics. def check(self, instance): """ Fetch WMI metrics. """ # Connection information host = instance.get('host', "localhost") namespace = instance.get('namespace', "root\\cimv2") provider = instance.get('provider') username = instance.get('us...
Remove all configuration for environments. def prune(force): """Remove all configuration for environments.""" if not force: echo_warning( 'Removing configuration of environments that may be in use will leave ' 'them in a potentially unusable state. If you wish to proceed (e.g. y...
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_kubelet_prometheus_instance(self, instance): """ Create a copy of the instance and set default values. This is so the base class can create a s...
Perform and return a GET request against kubelet. Support auth and TLS validation. def perform_kubelet_query(self, url, verbose=True, timeout=10, stream=False): """ Perform and return a GET request against kubelet. Support auth and TLS validation. """ return requests.get( ur...
Looks up the agent's kubernetes_pod_expiration_duration option and returns either: - None if expiration is disabled (set to 0) - A (timezone aware) datetime object to compare against def _compute_pod_expiration_datetime(): """ Looks up the agent's kubernetes_pod_expiration_duration ...
Reports the number of running pods on this node and the running containers in pods, tagged by service and creator. :param pods: pod list object :param instance_tags: list of tags def _report_pods_running(self, pods, instance_tags): """ Reports the number of running pods on this...
Reports pod requests & limits by looking at pod specs. def _report_container_spec_metrics(self, pod_list, instance_tags): """Reports pod requests & limits by looking at pod specs.""" for pod in pod_list['items']: pod_name = pod.get('metadata', {}).get('name') pod_phase = pod.get...
Reports container state & reasons by looking at container statuses def _report_container_state_metrics(self, pod_list, instance_tags): """Reports container state & reasons by looking at container statuses""" if pod_list.get('expired_count'): self.gauge(self.NAMESPACE + '.pods.expired', pod_...
Parse quantity allows to convert the value in the resources spec like: resources: requests: cpu: "100m" memory": "200Mi" limits: memory: "300Mi" :param string: str :return: float def parse_quantity(string): """ Parse quanti...
Convert a socket.error to ConnectionFailure and raise it. def _raise_connection_failure(address, error): """Convert a socket.error to ConnectionFailure and raise it.""" host, port = address # If connecting to a Unix socket, port will be None. if port is not None: msg = '%s:%d: %s' % (host, port...
Given (host, port) and PoolOptions, connect and return a socket object. Can raise socket.error. This is a modified version of create_connection from CPython >= 2.6. def _create_connection(address, options): """Given (host, port) and PoolOptions, connect and return a socket object. Can raise socket.e...
Given (host, port) and PoolOptions, return a configured socket. Can raise socket.error, ConnectionFailure, or CertificateError. Sets socket's SSL and timeout options. def _configured_socket(address, options): """Given (host, port) and PoolOptions, return a configured socket. Can raise socket.error, ...
Execute a command or raise ConnectionFailure or OperationFailure. :Parameters: - `dbname`: name of the database on which to run the command - `spec`: a command document as a dict, SON, or mapping object - `slave_ok`: whether to set the SlaveOkay wire protocol bit - `read...
Send a raw BSON message or raise ConnectionFailure. If a network exception is raised, the socket is closed. def send_message(self, message, max_doc_size): """Send a raw BSON message or raise ConnectionFailure. If a network exception is raised, the socket is closed. """ if (sel...
Receive a raw BSON message or raise ConnectionFailure. If any exception is raised, the socket is closed. def receive_message(self, operation, request_id): """Receive a raw BSON message or raise ConnectionFailure. If any exception is raised, the socket is closed. """ try: ...
Send OP_INSERT, etc., optionally returning response as a dict. Can raise ConnectionFailure or OperationFailure. :Parameters: - `request_id`: an int. - `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DELETE message, perhaps with a getlasterror command appended. - ...
Send "insert" etc. command, returning response as a dict. Can raise ConnectionFailure or OperationFailure. :Parameters: - `request_id`: an int. - `msg`: bytes, the command message. def write_command(self, request_id, msg): """Send "insert" etc. command, returning response ...
Update this socket's authentication. Log in or out to bring this socket's credentials up to date with those provided. Can raise ConnectionFailure or OperationFailure. :Parameters: - `all_credentials`: dict, maps auth source to MongoCredential. def check_auth(self, all_credentials): ...
Log in to the server and store these credentials in `authset`. Can raise ConnectionFailure or OperationFailure. :Parameters: - `credentials`: A MongoCredential. def authenticate(self, credentials): """Log in to the server and store these credentials in `authset`. Can raise ...
Connect to Mongo and return a new SocketInfo. Can raise ConnectionFailure or CertificateError. Note that the pool does not keep a reference to the socket -- you must call return_socket() when you're done with it. def connect(self): """Connect to Mongo and return a new SocketInfo. ...
Get a socket from the pool. Use with a "with" statement. Returns a :class:`SocketInfo` object wrapping a connected :class:`socket.socket`. This method should always be used in a with-statement:: with pool.get_socket(credentials, checkout) as socket_info: socket_inf...
Get or create a SocketInfo. Can raise ConnectionFailure. def _get_socket_no_auth(self): """Get or create a SocketInfo. Can raise ConnectionFailure.""" # We use the pid here to avoid issues with fork / multiprocessing. # See test.test_client:TestClient.test_fork for an example of # what ...
Return the socket to the pool, or if it's closed discard it. def return_socket(self, sock_info): """Return the socket to the pool, or if it's closed discard it.""" if self.pid != os.getpid(): self.reset() else: if sock_info.pool_id != self.pool_id: sock_i...
This side-effecty function checks if this socket has been idle for for longer than the max idle time, or if the socket has been closed by some external network error, and if so, attempts to create a new socket. If this connection attempt fails we raise the ConnectionFailure. Che...
This filters `items` by a regular expression `whitelist` and/or `blacklist`, with the `blacklist` taking precedence. An optional `key` function can be provided that will be passed each item. def pattern_filter(items, whitelist=None, blacklist=None, key=None): """This filters `items` by a regular expression...
Return an updated copy of a TopologyDescription. :Parameters: - `topology_description`: the current TopologyDescription - `server_description`: a new ServerDescription that resulted from an ismaster call Called after attempting (successfully or not) to call ismaster on the server at se...
Update topology description from a primary's ismaster response. Pass in a dict of ServerDescriptions, current replica set name, the ServerDescription we are processing, and the TopologyDescription's max_set_version and max_election_id if any. Returns (new topology type, new replica_set_name, new max_s...
RS with known primary. Process a response from a non-primary. Pass in a dict of ServerDescriptions, current replica set name, and the ServerDescription we are processing. Returns new topology type. def _update_rs_with_primary_from_member( sds, replica_set_name, server_description)...
RS without known primary. Update from a non-primary's response. Pass in a dict of ServerDescriptions, current replica set name, and the ServerDescription we are processing. Returns (new topology type, new replica_set_name). def _update_rs_no_primary_from_member( sds, replica_set_name, ...
Current topology type is ReplicaSetWithPrimary. Is primary still known? Pass in a dict of ServerDescriptions. Returns new topology type. def _check_has_primary(sds): """Current topology type is ReplicaSetWithPrimary. Is primary still known? Pass in a dict of ServerDescriptions. Returns new topo...
A copy of this description, with all servers marked Unknown. def reset(self): """A copy of this description, with all servers marked Unknown.""" if self._topology_type == TOPOLOGY_TYPE.ReplicaSetWithPrimary: topology_type = TOPOLOGY_TYPE.ReplicaSetNoPrimary else: topolog...
Minimum of all servers' max wire versions, or None. def common_wire_version(self): """Minimum of all servers' max wire versions, or None.""" servers = self.known_servers if servers: return min(s.max_wire_version for s in self.known_servers) return None
Does this topology have any readable servers available matching the given read preference? :Parameters: - `read_preference`: an instance of a read preference from :mod:`~pymongo.read_preferences`. Defaults to :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`. ...
Human-friendly OS name def get_os(): """ Human-friendly OS name """ if sys.platform == 'darwin': return 'mac' elif sys.platform.find('freebsd') != -1: return 'freebsd' elif sys.platform.find('linux') != -1: return 'linux' elif sys.platform.find('win32') != -1: ...
Return true if this is a BSD like operating system. def is_bsd(name=None): """ Return true if this is a BSD like operating system. """ name = name or sys.platform return Platform.is_darwin(name) or Platform.is_freebsd(name)
Return true if the platform is a unix, False otherwise. def is_unix(name=None): """ Return true if the platform is a unix, False otherwise. """ name = name or sys.platform return Platform.is_darwin(name) or Platform.is_linux(name) or Platform.is_freebsd(name)
Run the given subprocess command and return its output. Raise an Exception if an error occurs. :param command: The command to run. Using a list of strings is recommended. The command will be run in a subprocess without using a shell, as such shell features like shell pip...
Show changes since a specific date. def changes(since, out_file, eager): """Show changes since a specific date.""" root = get_root() history_data = defaultdict(lambda: {'lines': deque(), 'releasers': set()}) with chdir(root): result = run_command( ( 'git log "--pret...
Generates a markdown file containing the list of checks that changed for a given Agent release. Agent version numbers are derived inspecting tags on `integrations-core` so running this tool might provide unexpected results if the repo is not up to date with the Agent release process. If neither `--sinc...
Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. def init_instance(self, key): """ Create an empty instance if it doesn't exist. If the instance already exists, this is a noop. """ with self._lock: if key not in se...
Return whether a counter_id is present for a given instance key. If the key is not in the cache, raises a KeyError. def contains(self, key, counter_id): """ Return whether a counter_id is present for a given instance key. If the key is not in the cache, raises a KeyError. """ ...
Store the metadata for the given instance key. def set_metadata(self, key, metadata): """ Store the metadata for the given instance key. """ with self._lock: self._metadata[key] = metadata
Store the list of metric IDs we will want to collect for the given instance key def set_metric_ids(self, key, metric_ids): """ Store the list of metric IDs we will want to collect for the given instance key """ with self._lock: self._metric_ids[key] = metric_ids
Return the metadata for the metric identified by `counter_id` for the given instance key. If the key is not in the cache, raises a KeyError. If there's no metric with the given counter_id, raises a MetadataNotFoundError. def get_metadata(self, key, counter_id): """ Return the metadata f...
Validate `manifest.json` files. def manifest(fix, include_extras): """Validate `manifest.json` files.""" all_guids = {} root = get_root() root_name = basepath(get_root()) ok_checks = 0 failed_checks = 0 fixed_checks = 0 echo_info("Validating all manifest.json files...") for check_...
Map log levels to strings def _get_py_loglevel(lvl): """ Map log levels to strings """ if not lvl: lvl = 'INFO' return LOG_LEVEL_MAP.get(lvl.upper(), logging.DEBUG)
Initialize logging (set up forwarding to Go backend and sane defaults) def init_logging(): """ Initialize logging (set up forwarding to Go backend and sane defaults) """ # Forward to Go backend logging.addLevelName(TRACE_LEVEL, 'TRACE') logging.setLoggerClass(AgentLogger) rootLogger = loggi...
Read line-by-line and run callback on each line. line_by_line: yield each time a callback has returned True move_end: start from the last line of the log def tail(self, line_by_line=True, move_end=True): """Read line-by-line and run callback on each line. line_by_line: yield each time a...
This utility provides a convenient way to safely set up and tear down arbitrary types of environments. :param up: A custom setup callable. :type up: ``callable`` :param down: A custom tear down callable. :type down: ``callable`` :param sleep: Number of seconds to wait before yielding. :type sle...
Returns an amended copy of the proxies dictionary - used by `requests`, it will disable the proxy if the uri provided is to be reached directly. :param proxies A dict with existing proxies: `https`, `http`, and `no` are potential keys. :param uri URI to determine if a proxy is necessary or not. :param s...
Clear the connection pool and stop the monitor. Reconnect with open(). def close(self): """Clear the connection pool and stop the monitor. Reconnect with open(). """ if self._publish: self._events.put((self._listener.publish_server_closed, ...
Send an unacknowledged message to MongoDB. Can raise ConnectionFailure. :Parameters: - `message`: (request_id, data). - `all_credentials`: dict, maps auth source to MongoCredential. def send_message(self, message, all_credentials): """Send an unacknowledged message to Mong...
Send a message to MongoDB and return a Response object. Can raise ConnectionFailure. :Parameters: - `operation`: A _Query or _GetMore object. - `set_slave_okay`: Pass to operation.get_message. - `all_credentials`: dict, maps auth source to MongoCredential. - `li...
Return request_id, data, max_doc_size. :Parameters: - `message`: (request_id, data, max_doc_size) or (request_id, data) def _split_message(self, message): """Return request_id, data, max_doc_size. :Parameters: - `message`: (request_id, data, max_doc_size) or (request_id, d...
A map of operation index to the _id of the upserted document. def upserted_ids(self): """A map of operation index to the _id of the upserted document.""" self._raise_if_unacknowledged("upserted_ids") if self.__bulk_api_result: return dict((upsert["index"], upsert["_id"]) ...
Show the contents of the config file. def show(all_keys): """Show the contents of the config file.""" if not config_file_exists(): echo_info('No config file found! Please try `ddev config restore`.') else: if all_keys: echo_info(read_config_file().rstrip()) else: ...
Assigns values to config file entries. If the value is omitted, you will be prompted, with the input hidden if it is sensitive. \b $ ddev config set github.user foo New setting: [github] user = "foo" def set_value(ctx, key, value): """Assigns values to config file entries. If the value is ...
Return this instance's socket to the connection pool. def close(self): """Return this instance's socket to the connection pool. """ if not self.__closed: self.__closed = True self.pool.return_socket(self.sock) self.sock, self.pool = None, None
Rewind this cursor to its unevaluated state. Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resul...
Internal clone helper. def _clone(self, deepcopy=True): """Internal clone helper.""" clone = self._clone_base() values_to_clone = ("spec", "projection", "skip", "limit", "max_time_ms", "max_await_time_ms", "comment", "max", "min", "ordering"...
Closes this cursor. def __die(self, synchronous=False): """Closes this cursor. """ if self.__id and not self.__killed: if self.__exhaust and self.__exhaust_mgr: # If this is an exhaust cursor and we haven't completely # exhausted the result set we *mu...
Get the spec to use for a query. def __query_spec(self): """Get the spec to use for a query. """ operators = self.__modifiers.copy() if self.__ordering: operators["$orderby"] = self.__ordering if self.__explain: operators["$explain"] = True if sel...
Set arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) def add_option(self, mask): """Set arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) """ if not isinstance(mask, int): rais...
Unset arbitrary query flags using a bitmask. To unset the tailable flag: cursor.remove_option(2) def remove_option(self, mask): """Unset arbitrary query flags using a bitmask. To unset the tailable flag: cursor.remove_option(2) """ if not isinstance(mask, int):...
Limits the number of results to be returned by this cursor. Raises :exc:`TypeError` if `limit` is not an integer. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. The last `limit` applied to this cursor takes precedence. A limit of ``0`` is e...
Skips the first `skip` results of this cursor. Raises :exc:`TypeError` if `skip` is not an integer. Raises :exc:`ValueError` if `skip` is less than ``0``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has already been used. The last `skip` applied to this cursor...
Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms` is ``None`` no limit is applied. Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``....
Specifies a time limit for a getMore operation on a :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other types of cursor max_await_time_ms is ignored. Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or ``None``. Raises :exc:`~pymongo.errors.InvalidOpe...
Adds `max` operator that specifies upper bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order. .. versionadded:: 2.7 def max(self, spec): """Adds `max` operator that s...
Adds `min` operator that specifies lower bound for specific index. :Parameters: - `spec`: a list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. .. versionadded:: 2.7 def min(self, spec): """Adds `min` operator that s...
Sorts this cursor's results. Pass a field name and a direction, either :data:`~pymongo.ASCENDING` or :data:`~pymongo.DESCENDING`:: for doc in collection.find().sort('field', pymongo.ASCENDING): print(doc) To sort by multiple fields, pass a list of (key, direction) ...
Get the size of the results set for this query. Returns the number of documents in the results set for this query. Does not take :meth:`limit` and :meth:`skip` into account by default - set `with_limit_and_skip` to ``True`` if that is the desired behavior. Raises :class:`~pymongo.errors...
Get a list of distinct values for `key` among all documents in the result set of this query. Raises :class:`TypeError` if `key` is not an instance of :class:`basestring` (:class:`str` in python 3). The :meth:`distinct` method obeys the :attr:`~pymongo.collection.Collection.read...
Returns an explain plan record for this cursor. .. mongodoc:: explain def explain(self): """Returns an explain plan record for this cursor. .. mongodoc:: explain """ c = self.clone() c.__explain = True # always use a hard limit for explains if c.__limi...
Adds a $where clause to this query. The `code` argument must be an instance of :class:`basestring` (:class:`str` in python 3) or :class:`~bson.code.Code` containing a JavaScript expression. This expression will be evaluated for each document scanned. Only those documents for whi...
Adds a :class:`~pymongo.collation.Collation` to this query. This option is only supported on MongoDB 3.4 and above. Raises :exc:`TypeError` if `collation` is not an instance of :class:`~pymongo.collation.Collation` or a ``dict``. Raises :exc:`~pymongo.errors.InvalidOperation` if this :...
Send a query or getmore operation and handles the response. If operation is ``None`` this is an exhaust cursor, which reads the next result batch off the exhaust socket instead of sending getMore messages to the server. Can raise ConnectionFailure. def __send_message(self, operation):...
Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. def _refresh(self): """Refreshes the cursor wi...
Advance the cursor. def next(self): """Advance the cursor.""" if self.__empty: raise StopIteration if len(self.__data) or self._refresh(): if self.__manipulate: _db = self.__collection.database return _db._fix_outgoing(self.__data.popleft(...
Deepcopy helper for the data dictionary or list. Regular expressions cannot be deep copied but as they are immutable we don't have to copy them when cloning. def _deepcopy(self, x, memo=None): """Deepcopy helper for the data dictionary or list. Regular expressions cannot be deep copie...
Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck only! def trace_method(method): """ Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck onl...
Print exceptions happening in separate threads Prevent from logging a ton of them if a potentially big number of them fail the same way def print_exception(self, msg): """ Print exceptions happening in separate threads Prevent from logging a ton of them if a potentially big number of them fail ...
Compare the available metrics for one MOR we have computed and intersect them with the set of metrics we want to report def _compute_needed_metrics(self, instance, available_metrics): """ Compare the available metrics for one MOR we have computed and intersect them with the set of metrics we wa...
Returns a list of tags for every host that is detected by the vSphere integration. Returns a list of pairs (hostname, {'SOURCE_TYPE: list_of_tags},) def get_external_host_tags(self): """ Returns a list of tags for every host that is detected by the vSphere integration. ...
Explore vCenter infrastructure to discover hosts, virtual machines, etc. and compute their associated tags. Start at the vCenter `rootFolder`, so as to collect every objet. Example topology: ``` rootFolder - datacenter1 - compute_resou...
Return `True` if the given host or virtual machine is excluded by the user configuration, i.e. violates any of the following rules: * Do not match the corresponding `*_include_only` regular expressions * Is "non-labeled" while `include_only_marked` is enabled (virtual machine only) def _is_excl...
Fill the Mor objects queue that will be asynchronously processed later. Resolve the vCenter `rootFolder` and initiate hosts and virtual machines discovery. def _cache_morlist_raw(self, instance): """ Fill the Mor objects queue that will be asynchronously processed later. Resolve...
Process a batch of items popped from the objects queue by querying the available metrics for these MORs and then putting them in the Mor cache def _process_mor_objects_queue_async(self, instance, mors): """ Process a batch of items popped from the objects queue by querying the available ...
Pops `batch_morlist_size` items from the mor objects queue and run asynchronously the _process_mor_objects_queue_async method to fill the Mor cache. def _process_mor_objects_queue(self, instance): """ Pops `batch_morlist_size` items from the mor objects queue and run asynchronously the ...
Get all the performance counters metadata meaning name/group/description... from the server instance, attached with the corresponding ID def _cache_metrics_metadata(self, instance): """ Get all the performance counters metadata meaning name/group/description... from the server instance,...
Given the counter_id, look up for the metrics metadata to check the vsphere type of the counter and apply pre-reporting transformation if needed. def _transform_value(self, instance, counter_id, value): """ Given the counter_id, look up for the metrics metadata to check the vsphere type of the ...
Task that collects the metrics listed in the morlist for one MOR def _collect_metrics_async(self, instance, query_specs): """ Task that collects the metrics listed in the morlist for one MOR """ # ## <TEST-INSTRUMENTATION> t = Timer() # ## </TEST-INSTRUMENTATION> i_key =...
Calls asynchronously _collect_metrics_async on all MORs, as the job queue is processed the Aggregator will receive the metrics. def collect_metrics(self, instance): """ Calls asynchronously _collect_metrics_async on all MORs, as the job queue is processed the Aggregator will receive the...
Check if the database we're targeting actually exists If not then we won't do any checks This allows the same config to be installed on many servers but fail gracefully def _check_db_exists(self, instance): """ Check if the database we're targeting actually exists If not then we...
Store the list of metrics to collect by instance_key. Will also create and cache cursors to query the db. def _make_metric_list_to_collect(self, instance, custom_metrics): """ Store the list of metrics to collect by instance_key. Will also create and cache cursors to query the db. ...
Create the appropriate SqlServerMetric object, each implementing its method to fetch the metrics properly. If a `type` was specified in the config, it is used to report the value directly fetched from SQLServer. Otherwise, it is decided based on the sql_type, according to microsoft's doc...
Convenience method to extract info from instance def _get_access_info(self, instance, db_key, db_name=None): ''' Convenience method to extract info from instance ''' dsn = instance.get('dsn') host = instance.get('host') username = instance.get('username') password = inst...
Return a key to use for the connection cache def _conn_key(self, instance, db_key, db_name=None): ''' Return a key to use for the connection cache ''' dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_name) return '{}:{}:{}:{}:{}:{}'.format(dsn...
Return a connection string to use with odbc def _conn_string_odbc(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with odbc ''' if instance: dsn, host, username, password, database, driver = self._get_access_info(instance, db_key, db_...
Return a connection string to use with adodbapi def _conn_string_adodbapi(self, db_key, instance=None, conn_key=None, db_name=None): ''' Return a connection string to use with adodbapi ''' if instance: _, host, username, password, database, _ = self._get_access_info(instance, db_key...