INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Execute all provided operations.
def execute(self, write_concern=None): """Execute all provided operations. :Parameters: - write_concern (optional): the write concern for this bulk execution. """ if write_concern is not None: validate_is_mapping("write_concern", write_concern) ...
Return a list of Servers matching selector or time out.
def select_servers(self, selector, server_selection_timeout=None, address=None): """Return a list of Servers matching selector, or time out. :Parameters: - `selector`: function that takes a list of Servers and returns ...
Like select_servers but choose a random server if several match.
def select_server(self, selector, server_selection_timeout=None, address=None): """Like select_servers, but choose a random server if several match.""" return random.choice(self.select_servers(selector, ...
Process a new ServerDescription after an ismaster call completes.
def on_change(self, server_description): """Process a new ServerDescription after an ismaster call completes.""" # We do no I/O holding the lock. with self._lock: # Any monitored server was definitely in the topology description # once. Check if it's still in the descript...
Return primary s address or None.
def get_primary(self): """Return primary's address or None.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: topology_type = self._description.topology_type if topology_type != TOPOLOGY_TYPE.ReplicaSetWithPrimary: ...
Return set of replica set member addresses.
def _get_replica_set_members(self, selector): """Return set of replica set member addresses.""" # Implemented here in Topology instead of MongoClient, so it can lock. with self._lock: topology_type = self._description.topology_type if topology_type not in (TOPOLOGY_TYPE.R...
Wake all monitors wait for at least one to check its server.
def request_check_all(self, wait_time=5): """Wake all monitors, wait for at least one to check its server.""" with self._lock: self._request_check_all() self._condition.wait(wait_time)
Clear our pool for a server mark it Unknown and check it soon.
def reset_server_and_request_check(self, address): """Clear our pool for a server, mark it Unknown, and check it soon.""" with self._lock: self._reset_server(address) self._request_check(address)
Clear pools and terminate monitors. Topology reopens on demand.
def close(self): """Clear pools and terminate monitors. Topology reopens on demand.""" with self._lock: for server in self._servers.values(): server.close() # Mark all servers Unknown. self._description = self._description.reset() self._up...
Clear our pool for a server and mark it Unknown.
def _reset_server(self, address): """Clear our pool for a server and mark it Unknown. Hold the lock when calling this. Does *not* request an immediate check. """ server = self._servers.get(address) # "server" is None if another thread removed it from the topology. if se...
Wake one monitor. Hold the lock when calling this.
def _request_check(self, address): """Wake one monitor. Hold the lock when calling this.""" server = self._servers.get(address) # "server" is None if another thread removed it from the topology. if server: server.request_check()
Sync our Servers from TopologyDescription. server_descriptions.
def _update_servers(self): """Sync our Servers from TopologyDescription.server_descriptions. Hold the lock while calling this. """ for address, sd in self._description.server_descriptions().items(): if address not in self._servers: monitor = self._settings.mo...
Format an error message if server selection fails.
def _error_message(self, selector): """Format an error message if server selection fails. Hold the lock when calling this. """ is_replica_set = self._description.topology_type in ( TOPOLOGY_TYPE.ReplicaSetWithPrimary, TOPOLOGY_TYPE.ReplicaSetNoPrimary) i...
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._mor_lock: if key not in self._mor: self._mor[key] = {}
Store a Mor object in the cache with the given name. If the key is not in the cache raises a KeyError.
def set_mor(self, key, name, mor): """ Store a Mor object in the cache with the given name. If the key is not in the cache, raises a KeyError. """ with self._mor_lock: self._mor[key][name] = mor self._mor[key][name]['creation_time'] = time.time()
Return the Mor object identified by name for the given instance key. If the key is not in the cache raises a KeyError. If there s no Mor with the given name raises a MorNotFoundError.
def get_mor(self, key, name): """ Return the Mor object identified by `name` for the given instance key. If the key is not in the cache, raises a KeyError. If there's no Mor with the given name, raises a MorNotFoundError. """ with self._mor_lock: mors = self._...
Store a list of metric identifiers for the given instance key and Mor object name. If the key is not in the cache raises a KeyError. If the Mor object is not in the cache raises a MorNotFoundError
def set_metrics(self, key, name, metrics): """ Store a list of metric identifiers for the given instance key and Mor object name. If the key is not in the cache, raises a KeyError. If the Mor object is not in the cache, raises a MorNotFoundError """ with self._mor...
Generator returning all the mors in the cache for the given instance key.
def mors(self, key): """ Generator returning all the mors in the cache for the given instance key. """ with self._mor_lock: for k, v in iteritems(self._mor.get(key, {})): yield k, v
Generator returning as many dictionaries containing batch_size Mor objects as needed to iterate all the content of the cache. This has to be iterated twice like:
def mors_batch(self, key, batch_size): """ Generator returning as many dictionaries containing `batch_size` Mor objects as needed to iterate all the content of the cache. This has to be iterated twice, like: for batch in cache.mors_batch('key', 100): for name...
Remove all the items in the cache for the given key that are older than ttl seconds. If the key is not in the cache raises a KeyError.
def purge(self, key, ttl): """ Remove all the items in the cache for the given key that are older than ttl seconds. If the key is not in the cache, raises a KeyError. """ mors_to_purge = [] now = time.time() with self._mor_lock: # Don't change ...
Takes a metric formatted by Envoy and splits it into a unique metric name. Returns the unique metric name a list of tags and the name of the submission method.
def parse_metric(metric, metric_mapping=METRIC_TREE): """Takes a metric formatted by Envoy and splits it into a unique metric name. Returns the unique metric name, a list of tags, and the name of the submission method. Example: 'listener.0.0.0.0_80.downstream_cx_total' -> ('listener.dow...
Iterates over histogram data yielding metric - value pairs.
def parse_histogram(metric, histogram): """Iterates over histogram data, yielding metric-value pairs.""" for match in HISTOGRAM.finditer(histogram): percentile, value = match.groups() value = float(value) if not isnan(value): try: yield metric + PERCENTILE_SU...
Put data in GridFS as a new file.
def put(self, data, **kwargs): """Put data in GridFS as a new file. Equivalent to doing:: try: f = new_file(**kwargs) f.write(data) finally: f.close() `data` can be either an instance of :class:`str` (:class:`bytes` in pyth...
Delete a file from GridFS by _id.
def delete(self, file_id): """Delete a file from GridFS by ``"_id"``. Deletes all data belonging to the file with ``"_id"``: `file_id`. .. warning:: Any processes/threads reading from the file while this method is executing will likely see an invalid/corrupt file....
Get a single file from gridfs.
def find_one(self, filter=None, *args, **kwargs): """Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single :class:`~gridfs.grid_file.GridOut`, or ``None`` if no ...
Check if a file exists in this instance of: class: GridFS.
def exists(self, document_or_id=None, **kwargs): """Check if a file exists in this instance of :class:`GridFS`. The file to check for can be specified by the value of its ``_id`` key, or by passing in a query document. A query document can be passed in as dictionary, or by using keyword...
Opens a Stream that the application can write the contents of the file to.
def open_upload_stream(self, filename, chunk_size_bytes=None, metadata=None): """Opens a Stream that the application can write the contents of the file to. The user must specify the filename, and can choose to add any additional information in the metadata fie...
Opens a Stream that the application can write the contents of the file to.
def open_upload_stream_with_id( self, file_id, filename, chunk_size_bytes=None, metadata=None): """Opens a Stream that the application can write the contents of the file to. The user must specify the file id and filename, and can choose to add any additional information in t...
Uploads a user file to a GridFS bucket with a custom file id.
def upload_from_stream_with_id(self, file_id, filename, source, chunk_size_bytes=None, metadata=None): """Uploads a user file to a GridFS bucket with a custom file id. Reads the contents of the user file from `source` and uploads it to the file `filename`. Sou...
Opens a Stream from which the application can read the contents of the stored file specified by file_id.
def open_download_stream(self, file_id): """Opens a Stream from which the application can read the contents of the stored file specified by file_id. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # get _id of file to read. file_id = fs...
Downloads the contents of the stored file specified by file_id and writes the contents to destination.
def download_to_stream(self, file_id, destination): """Downloads the contents of the stored file specified by file_id and writes the contents to `destination`. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to read fi...
Given an file_id delete this stored file s files collection document and associated chunks from a GridFS bucket.
def delete(self, file_id): """Given an file_id, delete this stored file's files collection document and associated chunks from a GridFS bucket. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) # Get _id of file to delete file_id = fs.upl...
Opens a Stream from which the application can read the contents of filename and optional revision.
def open_download_stream_by_name(self, filename, revision=-1): """Opens a Stream from which the application can read the contents of `filename` and optional `revision`. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) grid_out = fs.open_download_s...
List active or available environments.
def ls(checks): """List active or available environments.""" if checks: checks = sorted(get_testable_checks() & set(checks)) for check in checks: envs = get_available_tox_envs(check, e2e_only=True) if envs: echo_success('{}:'.format(check)) ...
Hit a given http url and return the stats lines
def _fetch_url_data(self, url, username, password, verify, custom_headers): ''' Hit a given http url and return the stats lines ''' # Try to fetch data from the stats URL auth = (username, password) url = "%s%s" % (url, STATS_URL) custom_headers.update(headers(self.agentConfig))...
Hit a given stats socket and return the stats lines
def _fetch_socket_data(self, parsed_url): ''' Hit a given stats socket and return the stats lines ''' self.log.debug("Fetching haproxy stats from socket: %s" % parsed_url.geturl()) if parsed_url.scheme == 'tcp': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s...
Main data - processing loop. For each piece of useful data we ll either save a metric save an event or both.
def _process_data( self, data, collect_aggregates_only, process_events, url=None, collect_status_metrics=False, collect_status_metrics_by_host=False, tag_service_check_by_host=False, services_incl_filter=None, services_excl_filter=None, ...
Adds spct if relevant adds service
def _update_data_dict(self, data_dict, back_or_front): """ Adds spct if relevant, adds service """ data_dict['back_or_front'] = back_or_front # The percentage of used sessions based on 'scur' and 'slim' if 'slim' in data_dict and 'scur' in data_dict: try: ...
if collect_aggregates_only we process only the aggregates else we process all except Services. BACKEND
def _should_process(self, data_dict, collect_aggregates_only): """ if collect_aggregates_only, we process only the aggregates else we process all except Services.BACKEND """ if collect_aggregates_only: if self._is_aggregate(data_dict): return T...
Use a named regexp on the current service_name to create extra tags Example HAProxy service name: be_edge_http_sre - prod_elk Example named regexp: be_edge_http_ ( ?P<team > [ a - z ] + ) \\ - ( ?P<env > [ a - z ] + ) _ ( ?P<app >. * ) Resulting tags: [ team: sre env: prod app: elk ]
def _tag_from_regex(self, tags_regex, service_name): """ Use a named regexp on the current service_name to create extra tags Example HAProxy service name: be_edge_http_sre-prod_elk Example named regexp: be_edge_http_(?P<team>[a-z]+)\\-(?P<env>[a-z]+)_(?P<app>.*) Resulting tags: [...
Try to normalize the HAProxy status as one of the statuses defined in ALL_STATUSES if it can t be matched return the status as - is in a tag - friendly format ex: UP 1/ 2 - > up no check - > no_check
def _normalize_status(status): """ Try to normalize the HAProxy status as one of the statuses defined in `ALL_STATUSES`, if it can't be matched return the status as-is in a tag-friendly format ex: 'UP 1/2' -> 'up' 'no check' -> 'no_check' """ formatted_status ...
Data is a dictionary related to one host ( one line ) extracted from the csv. It should look like: { pxname: dogweb svname: i - 4562165 scur: 42... }
def _process_metrics( self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None, active_tag=None ): """ Data is a dictionary related to one host (one line) extracted from the csv. It should look like: {'pxname':'dogweb', 'svname':'i-45621...
Main event processing loop. An event will be created for a service status change. Service checks on the server side can be used to provide the same functionality
def _process_event(self, data, url, services_incl_filter=None, services_excl_filter=None, custom_tags=None): ''' Main event processing loop. An event will be created for a service status change. Service checks on the server side can be used to provide the same functionality ''' ...
Report a service check tagged by the service and the backend. Statuses are defined in STATUS_TO_SERVICE_CHECK mapping.
def _process_service_check( self, data, url, tag_by_host=False, services_incl_filter=None, services_excl_filter=None, custom_tags=None ): ''' Report a service check, tagged by the service and the backend. Statuses are defined in `STATUS_TO_SERVICE_CHECK` mapping. ''' cust...
All servers matching one tag set.
def apply_single_tag_set(tag_set, selection): """All servers matching one tag set. A tag set is a dict. A server matches if its tags are a superset: A server tagged {'a': '1', 'b': '2'} matches the tag set {'a': '1'}. The empty tag set {} matches any server. """ def tags_match(server_tags): ...
All servers match a list of tag sets.
def apply_tag_sets(tag_sets, selection): """All servers match a list of tag sets. tag_sets is a list of dicts. The empty tag set {} matches any server, and may be provided at the end of the list as a fallback. So [{'a': 'value'}, {}] expresses a preference for servers tagged {'a': 'value'}, but acc...
Validates metadata. csv files
def metadata(check): """Validates metadata.csv files If `check` is specified, only the check will be validated, otherwise all metadata files in the repo will be. """ metric_sources = get_metric_sources() if check: if check not in metric_sources: abort('Metadata file `{}` do...
Build and return a mechanism specific credentials tuple.
def _build_credentials_tuple(mech, source, user, passwd, extra): """Build and return a mechanism specific credentials tuple. """ user = _unicode(user) if user is not None else None password = passwd if passwd is None else _unicode(passwd) if mech == 'GSSAPI': properties = extra.get('authmech...
Split a scram response into key value pairs.
def _parse_scram_response(response): """Split a scram response into key, value pairs.""" return dict(item.split(b"=", 1) for item in response.split(b","))
Authenticate using SCRAM - SHA - 1.
def _authenticate_scram_sha1(credentials, sock_info): """Authenticate using SCRAM-SHA-1.""" username = credentials.username password = credentials.password source = credentials.source # Make local _hmac = hmac.HMAC _sha1 = sha1 user = username.encode("utf-8").replace(b"=", b"=3D").repl...
Authenticate using GSSAPI.
def _authenticate_gssapi(credentials, sock_info): """Authenticate using GSSAPI. """ if not HAVE_KERBEROS: raise ConfigurationError('The "kerberos" module must be ' 'installed to use GSSAPI authentication.') try: username = credentials.username pa...
Authenticate using SASL PLAIN ( RFC 4616 )
def _authenticate_plain(credentials, sock_info): """Authenticate using SASL PLAIN (RFC 4616) """ source = credentials.source username = credentials.username password = credentials.password payload = ('\x00%s\x00%s' % (username, password)).encode('utf-8') cmd = SON([('saslStart', 1), ...
Authenticate using CRAM - MD5 ( RFC 2195 )
def _authenticate_cram_md5(credentials, sock_info): """Authenticate using CRAM-MD5 (RFC 2195) """ source = credentials.source username = credentials.username password = credentials.password # The password used as the mac key is the # same as what we use for MONGODB-CR passwd = _password_...
Authenticate using MONGODB - X509.
def _authenticate_x509(credentials, sock_info): """Authenticate using MONGODB-X509. """ query = SON([('authenticate', 1), ('mechanism', 'MONGODB-X509')]) if credentials.username is not None: query['user'] = credentials.username elif sock_info.max_wire_version < 5: ra...
Authenticate using MONGODB - CR.
def _authenticate_mongo_cr(credentials, sock_info): """Authenticate using MONGODB-CR. """ source = credentials.source username = credentials.username password = credentials.password # Get a nonce response = sock_info.command(source, {'getnonce': 1}) nonce = response['nonce'] key = _a...
Authenticate sock_info.
def authenticate(credentials, sock_info): """Authenticate sock_info.""" mechanism = credentials.mechanism auth_func = _AUTH_MAP.get(mechanism) auth_func(credentials, sock_info)
Parse the MetricFamily from a valid requests. Response object to provide a MetricFamily object ( see [ 0 ] ) The text format uses iter_lines () generator.: param response: requests. Response: return: core. Metric
def parse_metric_family(self, response, scraper_config): """ Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. :param response: requests.Response :return: core.Metric """ ...
Filters out the text input line by line to avoid parsing and processing metrics we know we don t want to process. This only works on text/ plain payloads and is an INTERNAL FEATURE implemented for the kubelet check: param input_get: line generator: output: generator of filtered lines
def _text_filter_input(self, input_gen, scraper_config): """ Filters out the text input line by line to avoid parsing and processing metrics we know we don't want to process. This only works on `text/plain` payloads, and is an INTERNAL FEATURE implemented for the kubelet check :p...
Poll the data from prometheus and return the metrics as a generator.
def scrape_metrics(self, scraper_config): """ Poll the data from prometheus and return the metrics as a generator. """ response = self.poll(scraper_config) try: # no dry run if no label joins if not scraper_config['label_joins']: scraper_co...
Polls the data from prometheus and pushes them as gauges endpoint is the metrics endpoint to use to poll metrics from Prometheus
def process(self, scraper_config, metric_transformers=None): """ Polls the data from prometheus and pushes them as gauges `endpoint` is the metrics endpoint to use to poll metrics from Prometheus Note that if the instance has a 'tags' attribute, it will be pushed automatically a...
Handle a prometheus metric according to the following flow: - search scraper_config [ metrics_mapper ] for a prometheus. metric < -- > datadog. metric mapping - call check method with the same name as the metric - log some info if none of the above worked
def process_metric(self, metric, scraper_config, metric_transformers=None): """ Handle a prometheus metric according to the following flow: - search scraper_config['metrics_mapper'] for a prometheus.metric <--> datadog.metric mapping - call check method with the same name as the ...
Custom headers can be added to the default headers.
def poll(self, scraper_config, headers=None): """ Custom headers can be added to the default headers. Returns a valid requests.Response, raise requests.HTTPError if the status code of the requests.Response isn't valid - see response.raise_for_status() The caller needs to close ...
For each sample in the metric report it as a gauge with all labels as tags except if a labels dict is passed in which case keys are label names we ll extract and corresponding values are tag names we ll use ( eg: { node: node } ).
def submit_openmetric(self, metric_name, metric, scraper_config, hostname=None): """ For each sample in the metric, report it as a gauge with all labels as tags except if a labels dict is passed, in which case keys are label names we'll extract and corresponding values are tag names we'l...
If hostname is None look at label_to_hostname setting
def _get_hostname(self, hostname, sample, scraper_config): """ If hostname is None, look at label_to_hostname setting """ if ( hostname is None and scraper_config['label_to_hostname'] is not None and scraper_config['label_to_hostname'] in sample[self.S...
Extracts metrics from a prometheus histogram and sends them as gauges
def _submit_gauges_from_histogram(self, metric_name, metric, scraper_config, hostname=None): """ Extracts metrics from a prometheus histogram and sends them as gauges """ for sample in metric.samples: val = sample[self.SAMPLE_VALUE] if not self._is_value_valid(val...
buf is a readable file - like object returns a tuple: ( metrics tags mode version )
def parse_stat(self, buf): """ `buf` is a readable file-like object returns a tuple: (metrics, tags, mode, version) """ metrics = [] buf.seek(0) # Check the version line to make sure we parse the rest of the # body correctly. Particularly, the Connections...
Parse mntr command s content. buf is a readable file - like object
def parse_mntr(self, buf): """ Parse `mntr` command's content. `buf` is a readable file-like object Returns: a tuple (metrics, mode) if mode == 'inactive', metrics will be None """ buf.seek(0) first = buf.readline() # First is version string or error ...
Take a single health check string return ( OSD name percentage used )
def _osd_pct_used(self, health): """Take a single health check string, return (OSD name, percentage used)""" # Full string looks like: osd.2 is full at 95% # Near full string: osd.1 is near full at 94% pct = re.compile(r'\d+%').findall(health) osd = re.compile(r'osd.\d+').findall...
Add a new son manipulator to this database.
def add_son_manipulator(self, manipulator): """Add a new son manipulator to this database. **DEPRECATED** - `add_son_manipulator` is deprecated. .. versionchanged:: 3.0 Deprecated add_son_manipulator. """ warnings.warn("add_son_manipulator is deprecated", ...
** DEPRECATED **: All incoming SON manipulators.
def incoming_manipulators(self): """**DEPRECATED**: All incoming SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 """ warnings.warn("Database.incoming_manipulators() is deprecated", DeprecationWarning, stacklevel=2) ...
** DEPRECATED **: All incoming SON copying manipulators.
def incoming_copying_manipulators(self): """**DEPRECATED**: All incoming SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 """ warnings.warn("Database.incoming_copying_manipulators() is deprecated", DeprecationWa...
** DEPRECATED **: All outgoing SON manipulators.
def outgoing_manipulators(self): """**DEPRECATED**: All outgoing SON manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 """ warnings.warn("Database.outgoing_manipulators() is deprecated", DeprecationWarning, stacklevel=2) ...
** DEPRECATED **: All outgoing SON copying manipulators.
def outgoing_copying_manipulators(self): """**DEPRECATED**: All outgoing SON copying manipulators. .. versionchanged:: 3.5 Deprecated. .. versionadded:: 2.0 """ warnings.warn("Database.outgoing_copying_manipulators() is deprecated", DeprecationWa...
Get a: class: ~pymongo. collection. Collection with the given name and options.
def get_collection(self, name, codec_options=None, read_preference=None, write_concern=None, read_concern=None): """Get a :class:`~pymongo.collection.Collection` with the given name and options. Useful for creating a :class:`~pymongo.collection.Collection` with di...
Get a Collection instance with the default settings.
def _collection_default_options(self, name, **kargs): """Get a Collection instance with the default settings.""" wc = (self.write_concern if self.write_concern.acknowledged else WriteConcern()) return self.get_collection( name, codec_options=DEFAULT_CODEC_OPTIONS, ...
Create a new: class: ~pymongo. collection. Collection in this database.
def create_collection(self, name, codec_options=None, read_preference=None, write_concern=None, read_concern=None, **kwargs): """Create a new :class:`~pymongo.collection.Collection` in this database. Normally collection creation is automatic. ...
Apply incoming manipulators to son.
def _apply_incoming_manipulators(self, son, collection): """Apply incoming manipulators to `son`.""" for manipulator in self.__incoming_manipulators: son = manipulator.transform_incoming(son, collection) return son
Apply incoming copying manipulators to son.
def _apply_incoming_copying_manipulators(self, son, collection): """Apply incoming copying manipulators to `son`.""" for manipulator in self.__incoming_copying_manipulators: son = manipulator.transform_incoming(son, collection) return son
Apply manipulators to an incoming SON object before it gets stored.
def _fix_incoming(self, son, collection): """Apply manipulators to an incoming SON object before it gets stored. :Parameters: - `son`: the son object going into the database - `collection`: the collection the son object is being saved in """ son = self._apply_incomin...
Apply manipulators to a SON object as it comes out of the database.
def _fix_outgoing(self, son, collection): """Apply manipulators to a SON object as it comes out of the database. :Parameters: - `son`: the son object coming out of the database - `collection`: the collection the son object was saved in """ for manipulator in reversed...
Internal command helper.
def _command(self, sock_info, command, slave_ok=False, value=1, check=True, allowable_errors=None, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, write_concern=None, parse_write_concern_error=False, **kwargs): """I...
Issue a MongoDB command.
def command(self, command, value=1, check=True, allowable_errors=None, read_preference=ReadPreference.PRIMARY, codec_options=DEFAULT_CODEC_OPTIONS, **kwargs): """Issue a MongoDB command. Send command `command` to the database and return the response. If `command`...
Internal listCollections helper.
def _list_collections(self, sock_info, slave_okay, criteria=None): """Internal listCollections helper.""" criteria = criteria or {} cmd = SON([("listCollections", 1), ("cursor", {})]) if criteria: cmd["filter"] = criteria if sock_info.max_wire_version > 2: ...
Get a list of all the collection names in this database.
def collection_names(self, include_system_collections=True): """Get a list of all the collection names in this database. :Parameters: - `include_system_collections` (optional): if ``False`` list will not include system collections (e.g ``system.indexes``) """ with ...
Drop a collection.
def drop_collection(self, name_or_collection): """Drop a collection. :Parameters: - `name_or_collection`: the name of a collection to drop or the collection object itself .. note:: The :attr:`~pymongo.database.Database.write_concern` of this database is automat...
Get information on operations currently running.
def current_op(self, include_all=False): """Get information on operations currently running. :Parameters: - `include_all` (optional): if ``True`` also list currently idle operations in the result """ cmd = SON([("currentOp", 1), ("$all", include_all)]) with...
** DEPRECATED **: Get the error if one occurred on the last operation.
def error(self): """**DEPRECATED**: Get the error if one occurred on the last operation. This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern ``w=1`` and report their errors by default. .. versionchanged:: 2.8 ...
** DEPRECATED **: Get the most recent error on this database.
def previous_error(self): """**DEPRECATED**: Get the most recent error on this database. This method is obsolete: all MongoDB write operations (insert, update, remove, and so on) use the write concern ``w=1`` and report their errors by default. Only returns errors that have occ...
Use a command to create ( if create = True ) or modify a user.
def _create_or_update_user( self, create, name, password, read_only, **kwargs): """Use a command to create (if create=True) or modify a user. """ opts = {} if read_only or (create and "roles" not in kwargs): warnings.warn("Creating a user with the read_only option...
Uses v1 system to add users i. e. saving to system. users.
def _legacy_add_user(self, name, password, read_only, **kwargs): """Uses v1 system to add users, i.e. saving to system.users. """ # Use a Collection with the default codec_options. system_users = self._collection_default_options('system.users') user = system_users.find_one({"user...
Create user name with password password.
def add_user(self, name, password=None, read_only=None, **kwargs): """Create user `name` with password `password`. Add a new user with permissions for this :class:`Database`. .. note:: Will change the password if user `name` already exists. :Parameters: - `name`: the name of...
Remove user name from this: class: Database.
def remove_user(self, name): """Remove user `name` from this :class:`Database`. User `name` will no longer have permissions to access this :class:`Database`. :Parameters: - `name`: the name of the user to remove """ try: cmd = SON([("dropUser", nam...
** DEPRECATED **: Authenticate to use this database.
def authenticate(self, name=None, password=None, source=None, mechanism='DEFAULT', **kwargs): """**DEPRECATED**: Authenticate to use this database. Authentication lasts for the life of the underlying client instance, or until :meth:`logout` is called. Raises :class...
** DEPRECATED **: Deauthorize use of this database.
def logout(self): """**DEPRECATED**: Deauthorize use of this database.""" warnings.warn("Database.logout() is deprecated", DeprecationWarning, stacklevel=2) # Sockets will be deauthenticated as they are used. self.client._purge_credentials(self.name)
** DEPRECATED **: Evaluate a JavaScript expression in MongoDB.
def eval(self, code, *args): """**DEPRECATED**: Evaluate a JavaScript expression in MongoDB. :Parameters: - `code`: string representation of JavaScript code to be evaluated - `args` (optional): additional positional arguments are passed to the `code` being ev...
Get a list of the names of the functions stored in this database.
def list(self): """Get a list of the names of the functions stored in this database.""" return [x["_id"] for x in self._db.system.js.find(projection=["_id"])]
Move _id to the front if it s there.
def transform_incoming(self, son, collection): """Move _id to the front if it's there. """ if not "_id" in son: return son transformed = SON({"_id": son["_id"]}) transformed.update(son) return transformed
Replace embedded documents with DBRefs.
def transform_incoming(self, son, collection): """Replace embedded documents with DBRefs. """ def transform_value(value): if isinstance(value, collections.MutableMapping): if "_id" in value and "_ns" in value: return DBRef(value["_ns"], transform_...
This function provides a convenient API wrapping subprocess. Popen. Captured output is guaranteed not to deadlock but will still reside in memory in the end.
def run_command(command, capture=None, check=False, encoding='utf-8', shell=False, env=None): """This function provides a convenient API wrapping subprocess.Popen. Captured output is guaranteed not to deadlock, but will still reside in memory in the end. :param command: The command to run in a subprocess. ...
Get HDFS namenode metrics from JMX
def _hdfs_namenode_metrics(self, beans, metrics, tags): """ Get HDFS namenode metrics from JMX """ bean = next(iter(beans)) bean_name = bean.get('name') if bean_name != bean_name: raise Exception("Unexpected bean name {}".format(bean_name)) for metri...