INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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 `whitelist` and/or `blacklist`, with the `blacklist` taking precedence. An optional `key` function can be provided that will be passed each item. """ key = key or __return_self if...
Return an updated copy of a TopologyDescription.
def updated_topology_description(topology_description, server_description): """Return an updated copy of a TopologyDescription. :Parameters: - `topology_description`: the current TopologyDescription - `server_description`: a new ServerDescription that resulted from an ismaster call Cal...
Update topology description from a primary s ismaster response.
def _update_rs_from_primary( sds, replica_set_name, server_description, max_set_version, max_election_id): """Update topology description from a primary's ismaster response. Pass in a dict of ServerDescriptions, current replica set name, the ServerDescription we are ...
RS with known primary. Process a response from a non - primary.
def _update_rs_with_primary_from_member( sds, replica_set_name, server_description): """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 topolog...
RS without known primary. Update from a non - primary s response.
def _update_rs_no_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 topolo...
Current topology type is ReplicaSetWithPrimary. Is primary still known?
def _check_has_primary(sds): """Current topology type is ReplicaSetWithPrimary. Is primary still known? Pass in a dict of ServerDescriptions. Returns new topology type. """ for s in sds.values(): if s.server_type == SERVER_TYPE.RSPrimary: return TOPOLOGY_TYPE.ReplicaSetWithPrim...
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: topology_type = self._topology_type # The default ServerDesc...
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?
def has_readable_server(self, read_preference=ReadPreference.PRIMARY): """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`. De...
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 'windows' e...
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.
def get_subprocess_output(command, log, raise_on_empty_output=True, log_debug=True): """ 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...
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 "--pretty=format:%H %s" --date-order --date=...
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.
def changelog(since, to, write, force): """ 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 wit...
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 self._metadata: self._metadata[key] = {} self._metric_ids[key] = []
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. """ with self._lock: return counter_id in self._metadata[key]
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 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. """ wi...
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_name in sorted(os.listdir(root)):...
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 = logging.getLogger() rootLogger.addHandler(AgentLogHandler()) rootLogg...
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 callback has returned True move_end: start from the last line of the log""" try: self._open_file(move_end=move_end) while True: ...
This utility provides a convenient way to safely set up and tear down arbitrary types of environments.
def environment_run(up, down, sleep=None, endpoints=None, conditions=None, env_vars=None, wrapper=None): """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 c...
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 skip_proxy If True the retur...
def config_proxy_skip(proxies, uri, skip_proxy=False): """ 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. :para...
Clear the connection pool and stop the monitor.
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, (self._description.address, self._topology_id))) self._monitor.close...
Send an unacknowledged message to MongoDB.
def send_message(self, message, all_credentials): """Send an unacknowledged message to MongoDB. Can raise ConnectionFailure. :Parameters: - `message`: (request_id, data). - `all_credentials`: dict, maps auth source to MongoCredential. """ _, data, max_doc_si...
Send a message to MongoDB and return a Response object.
def send_message_with_response( self, operation, set_slave_okay, all_credentials, listeners, exhaust=False): """Send a message to MongoDB and return a Response object. Can raise ConnectionFailure. :Parameters: - ...
Return request_id data max_doc_size.
def _split_message(self, message): """Return request_id, data, max_doc_size. :Parameters: - `message`: (request_id, data, max_doc_size) or (request_id, data) """ if len(message) == 3: return message else: # get_more and kill_cursors messages don...
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"]) for upsert in self.bulk_api_result["upserted"])
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: echo_info(read_config_file_scrubbe...
Assigns values to config file entries. If the value is omitted you will be prompted with the input hidden if it is sensitive.
def set_value(ctx, key, value): """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" """ scrubbing = False if value is None: ...
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.
def rewind(self): """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 ...
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", "explain", "hint", ...
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 *must* close the socket ...
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 self.__hint: operators["$...
Set arbitrary query flags using a bitmask.
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): raise TypeError("mask must be an int") self.__check_okay_to_chain() if mask & _QUERY_OPTIONS["e...
Unset arbitrary query flags using a bitmask.
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): raise TypeError("mask must be an int") self.__check_okay_to_chain() if mask & _QUERY_...
Limits the number of results to be returned by this cursor.
def limit(self, limit): """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 take...
Skips the first skip results of this cursor.
def skip(self, skip): """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 l...
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.
def max_time_ms(self, max_time_ms): """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` ...
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.
def max_await_time_ms(self, max_await_time_ms): """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 o...
Adds max operator that specifies upper bound for specific index.
def max(self, spec): """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 """ if not ...
Adds min operator that specifies lower bound for specific index.
def min(self, spec): """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 """ if not ...
Sorts this cursor s results.
def sort(self, key_or_list, direction=None): """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 s...
Get the size of the results set for this query.
def count(self, with_limit_and_skip=False): """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 d...
Get a list of distinct values for key among all documents in the result set of this query.
def distinct(self, key): """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:...
Returns an explain plan record for this cursor.
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.__limit: c.__limit = -abs(c.__limit) return next(c)
Adds a $where clause to this query.
def where(self, code): """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. On...
Adds a: class: ~pymongo. collation. Collation to this query.
def collation(self, collation): """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:`...
Send a query or getmore operation and handles the response.
def __send_message(self, operation): """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 Connecti...
Refreshes the cursor with more data from Mongo.
def _refresh(self): """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. """ if l...
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.
def _deepcopy(self, x, memo=None): """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. """ if not hasattr(x, 'items'): y, is_list, iterator = [], True, enumer...
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 only! """ def wrapper(*args, **kwargs): try: method(*args, **kwargs) except Exception: args[0].pr...
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 the same way """ if self.exception_printed < 10: self.log.error(msg) self.exception_printed += 1
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 want to report """ i_key = self._instance_key(instance) if self.in_compatibility_mode(instance): ...
Returns a list of tags for every host that is detected by the vSphere integration.
def get_external_host_tags(self): """ 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},) """ self.log.debug("Sending external_host_tags now") external_host_tags = []...
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.
def _get_all_objs( self, server_instance, regexes=None, include_only_marked=False, tags=None, use_guest_hostname=False ): """ Explore vCenter infrastructure to discover hosts, virtual machines, etc. and compute their associated tags. Start at the vCenter `rootFolder`, so as t...
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_excluded(obj, properties, regexes, include_only_marked): """ 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...
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 the vCenter `rootFolder` and initiate hosts and virtual machines discovery. """ i_key = self._instance_key(instance) self.log.debug("Caching...
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 metrics for these MORs and then putting them in the Mor cache """ t = time.time() i_key = self._instance_key(instance) ...
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 _process_mor_objects_queue_async method to fill the Mor cache. """ i_key = self._instance_key(instance) self.mor_cache.init_instance(i...
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, attached with the corresponding ID """ # ## <TEST-INSTRUMENTATION> t = Timer() # ## </TEST-INSTRUMENTATION> ...
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 counter and apply pre-reporting transformation if needed. """ i_key = self._instance_key(instance) try: metadata = self...
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 = self._instance_key(instance) server_instance = self._get_...
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 metrics. """ i_key = self._instance_key(instance) if not self.mor_cache.contains(i_key): self.log.de...
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 won't do any checks This allows the same config to be installed on many servers but fail gracefully """ dsn, host, username, password, database, driver = self._...
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. """ metrics_to_collect = [] for name, counter_name, instance_name in self.METRICS: t...
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 documentation.
def typed_metric(self, instance, cfg_inst, table, base_name, user_type, sql_type, column): ''' 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 direct...
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 = instance.get('password') database = instance.g...
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, host, username, password, database, driver)
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_name) elif conn_key: dsn,...
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, db_name) elif conn_key: _, ...
Return a cursor to execute query against the db Cursor are cached in the self. connections dict
def get_cursor(self, instance, db_key, db_name=None): ''' Return a cursor to execute query against the db Cursor are cached in the self.connections dict ''' conn_key = self._conn_key(instance, db_key, db_name) try: conn = self.connections[conn_key]['conn'] ...
Return the type of the performance counter so that we can report it to Datadog correctly If the sql_type is one that needs a base ( PERF_RAW_LARGE_FRACTION and PERF_AVERAGE_BULK ) the name of the base counter will also be returned
def get_sql_type(self, instance, counter_name): ''' Return the type of the performance counter so that we can report it to Datadog correctly If the sql_type is one that needs a base (PERF_RAW_LARGE_FRACTION and PERF_AVERAGE_BULK), the name of the base counter will also be returne...
Fetch the metrics from the sys. dm_os_performance_counters table
def do_perf_counter_check(self, instance): """ Fetch the metrics from the sys.dm_os_performance_counters table """ custom_tags = instance.get('tags', []) if custom_tags is None: custom_tags = [] instance_key = self._conn_key(instance, self.DEFAULT_DB_KEY) ...
Fetch the metrics from the stored proc
def do_stored_procedure_check(self, instance, proc): """ Fetch the metrics from the stored proc """ guardSql = instance.get('proc_only_if') custom_tags = instance.get("tags", []) if (guardSql and self.proc_check_guard(instance, guardSql)) or not guardSql: se...
check to see if the guard SQL returns a single column containing 0 or 1 We return true if 1 else False
def proc_check_guard(self, instance, sql): """ check to see if the guard SQL returns a single column containing 0 or 1 We return true if 1, else False """ self.open_db_connections(instance, self.PROC_GUARD_DB_KEY) cursor = self.get_cursor(instance, self.PROC_GUARD_DB_KEY)...
We close the cursor explicitly b/ c we had proven memory leaks We handle any exception from closing although according to the doc: in adodbapi it is NOT an error to re - close a closed cursor
def close_cursor(self, cursor): """ We close the cursor explicitly b/c we had proven memory leaks We handle any exception from closing, although according to the doc: "in adodbapi, it is NOT an error to re-close a closed cursor" """ try: cursor.close() ...
We close the db connections explicitly b/ c when we don t they keep locks on the db. This presents as issues such as the SQL Server Agent being unable to stop.
def close_db_connections(self, instance, db_key, db_name=None): """ We close the db connections explicitly b/c when we don't they keep locks on the db. This presents as issues such as the SQL Server Agent being unable to stop. """ conn_key = self._conn_key(instance, db_ke...
We open the db connections explicitly so we can ensure they are open before we use them and are closable once we are finished. Open db connections keep locks on the db presenting issues such as the SQL Server Agent being unable to stop.
def open_db_connections(self, instance, db_key, db_name=None): """ We open the db connections explicitly, so we can ensure they are open before we use them, and are closable, once we are finished. Open db connections keep locks on the db, presenting issues such as the SQL Server ...
Because we need to query the metrics by matching pairs we can t query all of them together without having to perform some matching based on the name afterwards so instead we query instance by instance. We cache the list of instance so that we don t have to look it up every time
def fetch_metric(self, cursor, results, tags): ''' Because we need to query the metrics by matching pairs, we can't query all of them together without having to perform some matching based on the name afterwards so instead we query instance by instance. We cache the list of insta...
Transform each Kube DNS instance into a OpenMetricsBaseCheck instance
def create_generic_instances(self, instances): """ Transform each Kube DNS instance into a OpenMetricsBaseCheck instance """ generic_instances = [] for instance in instances: transformed_instance = self._create_kube_dns_instance(instance) generic_instances...
Set up kube_dns instance so it can be used in OpenMetricsBaseCheck
def _create_kube_dns_instance(self, instance): """ Set up kube_dns instance so it can be used in OpenMetricsBaseCheck """ kube_dns_instance = deepcopy(instance) # kube_dns uses 'prometheus_endpoint' and not 'prometheus_url', so we have to rename the key kube_dns_instance...
submit a kube_dns metric both as a gauge ( for compatibility ) and as a monotonic_count
def submit_as_gauge_and_monotonic_count(self, metric_suffix, metric, scraper_config): """ submit a kube_dns metric both as a gauge (for compatibility) and as a monotonic_count """ metric_name = scraper_config['namespace'] + metric_suffix for sample in metric.samples: ...
Internal command helper.
def _command(self, sock_info, command, slave_ok=False, read_preference=None, codec_options=None, check=True, allowable_errors=None, read_concern=DEFAULT_READ_CONCERN, write_concern=None, parse_write_concern_error=False, ...
Get a clone of this collection changing the specified settings.
def with_options( self, codec_options=None, read_preference=None, write_concern=None, read_concern=None): """Get a clone of this collection changing the specified settings. >>> coll1.read_preference Primary() >>> from pymongo import ReadPreference ...
** DEPRECATED ** - Initialize an unordered batch of write operations.
def initialize_unordered_bulk_op(self, bypass_document_validation=False): """**DEPRECATED** - Initialize an unordered batch of write operations. Operations will be performed on the server in arbitrary order, possibly in parallel. All operations will be attempted. :Parameters: ...
** DEPRECATED ** - Initialize an ordered batch of write operations.
def initialize_ordered_bulk_op(self, bypass_document_validation=False): """**DEPRECATED** - Initialize an ordered batch of write operations. Operations will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. :Par...
Send a batch of write operations to the server.
def bulk_write(self, requests, ordered=True, bypass_document_validation=False): """Send a batch of write operations to the server. Requests are passed as a list of write operation instances ( :class:`~pymongo.operations.InsertOne`, :class:`~pymongo.operations.UpdateOn...
Internal insert helper.
def _insert(self, sock_info, docs, ordered=True, check_keys=True, manipulate=False, write_concern=None, op_id=None, bypass_doc_val=False): """Internal insert helper.""" if isinstance(docs, collections.Mapping): return self._insert_one( sock_inf...
Insert a single document.
def insert_one(self, document, bypass_document_validation=False): """Insert a single document. >>> db.test.count({'x': 1}) 0 >>> result = db.test.insert_one({'x': 1}) >>> result.inserted_id ObjectId('54f112defba522406c9cc208') >>> db.test.find_one({'x...
Insert an iterable of documents.
def insert_many(self, documents, ordered=True, bypass_document_validation=False): """Insert an iterable of documents. >>> db.test.count() 0 >>> result = db.test.insert_many([{'x': i} for i in range(2)]) >>> result.inserted_ids [ObjectId('54f...
Replace a single document matching the filter.
def replace_one(self, filter, replacement, upsert=False, bypass_document_validation=False, collation=None): """Replace a single document matching the filter. >>> for doc in db.test.find({}): ... print(doc) ... {u'x': 1, u'_id': ObjectId('54f4c5bef...
Update a single document matching the filter.
def update_one(self, filter, update, upsert=False, bypass_document_validation=False, collation=None): """Update a single document matching the filter. >>> for doc in db.test.find(): ... print(doc) ... {u'x': 1, u'_id': 0} ...
Delete a single document matching the filter.
def delete_one(self, filter, collation=None): """Delete a single document matching the filter. >>> db.test.count({'x': 1}) 3 >>> result = db.test.delete_one({'x': 1}) >>> result.deleted_count 1 >>> db.test.count({'x': 1}) 2 :Paramet...
Delete one or more documents matching the filter.
def delete_many(self, filter, collation=None): """Delete one or more documents matching the filter. >>> db.test.count({'x': 1}) 3 >>> result = db.test.delete_many({'x': 1}) >>> result.deleted_count 3 >>> db.test.count({'x': 1}) 0 :P...