INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Retrieve the slaves statuses using: 1. The performance_schema. threads table. Non - blocking requires version > 5. 6. 0 2. The information_schema. processlist table. Blocking
def _get_slave_status(self, db, above_560, nonblocking): """ Retrieve the slaves' statuses using: 1. The `performance_schema.threads` table. Non-blocking, requires version > 5.6.0 2. The `information_schema.processlist` table. Blocking """ try: with closing(db...
Return a dictionary for each job counter { counter_group_name: [ counter_name ] } }
def _parse_general_counters(self, init_config): """ Return a dictionary for each job counter { counter_group_name: [ counter_name ] } } """ job_counter = {} if init_config.get('general_counters'): # Parse...
Return a dictionary for each job counter { job_name: { counter_group_name: [ counter_name ] } } }
def _parse_job_specific_counters(self, init_config): """ Return a dictionary for each job counter { job_name: { counter_group_name: [ counter_name ] } } } """ job_counter = {} if init_confi...
Return a dictionary of { app_id: ( app_name tracking_url ) } for the running MapReduce applications
def _get_running_app_ids(self, rm_address, auth, ssl_verify): """ Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications """ metrics_json = self._rest_request_to_json( rm_address, auth, ssl_verify, ...
Get metrics for each MapReduce job. Return a dictionary for each MapReduce job { job_id: { job_name: job_name app_name: app_name user_name: user_name tracking_url: tracking_url }
def _mapreduce_job_metrics(self, running_apps, auth, ssl_verify, addl_tags): """ Get metrics for each MapReduce job. Return a dictionary for each MapReduce job { job_id: { 'job_name': job_name, 'app_name': app_name, 'user_name': user_name, ...
Get custom metrics specified for each counter
def _mapreduce_job_counters_metrics(self, running_jobs, auth, ssl_verify, addl_tags): """ Get custom metrics specified for each counter """ for job_metrics in itervalues(running_jobs): job_name = job_metrics['job_name'] # Check if the job_name exist in the custom...
Get metrics for each MapReduce task Return a dictionary of { task_id: tracking_url } for each MapReduce task
def _mapreduce_task_metrics(self, running_jobs, auth, ssl_verify, addl_tags): """ Get metrics for each MapReduce task Return a dictionary of {task_id: 'tracking_url'} for each MapReduce task """ for job_stats in itervalues(running_jobs): metrics_json = self._rest_req...
Parse the JSON response and set the metrics
def _set_metrics_from_json(self, metrics_json, metrics, tags): """ Parse the JSON response and set the metrics """ for status, (metric_name, metric_type) in iteritems(metrics): metric_status = metrics_json.get(status) if metric_status is not None: ...
Set a metric
def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None): """ Set a metric """ if metric_type == self.HISTOGRAM: self.histogram(metric_name, value, tags=tags, device_name=device_name) elif metric_type == self.INCREMENT: self.incr...
Query the given URL and return the JSON response
def _rest_request_to_json(self, address, auth, ssl_verify, object_path, service_name, tags=None, *args, **kwargs): """ Query the given URL and return the JSON response """ response_json = None tags = [] if tags is None else tags service_check_tags = ['url:{}'.format(self...
Reads init_config for psutil methods to call on the current process Calls those methods and stores the raw output
def _psutil_config_to_stats(self, instance): """ Reads `init_config` for `psutil` methods to call on the current process Calls those methods and stores the raw output :returns a dictionary of statistic_name: value """ process_metrics = instance.get('process_metrics', sel...
Saves sample metrics from psutil
def _register_psutil_metrics(self, stats, names_to_metric_types, tags=None): """ Saves sample metrics from psutil :param stats: a dictionary that looks like: { 'memory_info': OrderedDict([('rss', 24395776), ('vms', 144666624)]), 'io_counters': OrderedDict([('read_count...
Get a Docker container s IP address from its id or name.
def get_container_ip(container_id_or_name): """Get a Docker container's IP address from its id or name.""" command = [ 'docker', 'inspect', '-f', '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}', container_id_or_name, ] return run_command(command, captu...
This utility provides a convenient way to safely set up and tear down Docker environments.
def docker_run( compose_file=None, build=False, service_name=None, up=None, down=None, sleep=None, endpoints=None, log_patterns=None, conditions=None, env_vars=None, wrapper=None, ): """This utility provides a convenient way to safely set up and tear down Docker environme...
Get the SON document representation of this DBRef.
def as_doc(self): """Get the SON document representation of this DBRef. Generally not needed by application developers """ doc = SON([("$ref", self.collection), ("$id", self.id)]) if self.database is not None: doc["$db"] = self.database doc...
Reset the config object to its initial state
def clear(self): """ Reset the config object to its initial state """ with self._lock: self._config = { CacheConfig.Morlist: {'last': defaultdict(float), 'intl': {}}, CacheConfig.Metadata: {'last': defaultdict(float), 'intl': {}}, }
Notice: this will return the defaultdict default value also for keys that are not in the configuration this is a tradeoff to keep the code simple.
def get_last(self, type_, key): """ Notice: this will return the defaultdict default value also for keys that are not in the configuration, this is a tradeoff to keep the code simple. """ self._check_type(type_) with self._lock: return self._config[type_]['las...
Get a list of possible paths containing certificates
def _get_ca_certs_paths(): """ Get a list of possible paths containing certificates Check is installed via pip to: * Windows: embedded/lib/site-packages/datadog_checks/http_check * Linux: embedded/lib/python2.7/site-packages/datadog_checks/http_check Certificate is installed to: * embed...
Validate logo files. Specifying no check will validate all logos
def logos(check): """Validate logo files. Specifying no check will validate all logos""" valid_checks = get_valid_integrations() if check: if check in valid_checks: checks = [check] else: echo_info('{} is not an integration.'.format(check)) return el...
The text option ( - 1 ) is not reliable enough when counters get large. VBE. media_video_prd_services_01 ( 10. 93. 67. 16 8080 ). happy18446744073709551615
def _parse_varnishstat(self, output, varnishstat_format, tags=None): """ The text option (-1) is not reliable enough when counters get large. VBE.media_video_prd_services_01(10.93.67.16,,8080).happy18446744073709551615 2 types of data, "a" for counter ("c" in newer versions of varnish),...
Parse out service checks from varnishadm.
def _parse_varnishadm(self, output, tags): """ Parse out service checks from varnishadm. Example output: Backend b0 is Sick Current states good: 2 threshold: 3 window: 5 Average responsetime of good probes: 0.000000 Oldest ...
Parse the MetricFamily from a valid requests. Response object to provide a MetricFamily object ( see [ 0 ] )
def parse_metric_family(self, response): """ Parse the MetricFamily from a valid requests.Response object to provide a MetricFamily object (see [0]) The text format uses iter_lines() generator. The protobuf format directly parse the response.content property searching for Prometheus me...
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): """ 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: ...
: param messages: dictionary as metric_name: { labels: {} value: 10 }: param _metric: dictionary as { labels: { le: 0. 001 custom: value }}: param _m: str as metric name: param metric_suffix: str must be in ( count or sum ): return: value of the metric_name matched by the labels
def get_metric_value_by_labels(messages, _metric, _m, metric_suffix): """ :param messages: dictionary as metric_name: {labels: {}, value: 10} :param _metric: dictionary as {labels: {le: '0.001', 'custom': 'value'}} :param _m: str as metric name :param metric_suffix: str must be i...
Extracts MetricFamily objects from the maps generated by parsing the strings in _extract_metrics_from_string
def _extract_metric_from_map(self, _m, messages, obj_map, obj_help): """ Extracts MetricFamily objects from the maps generated by parsing the strings in _extract_metrics_from_string """ _obj = metrics_pb2.MetricFamily() _obj.name = _m _obj.type = self.METRIC_TYPES...
Poll the data from prometheus and return the metrics as a generator.
def scrape_metrics(self, endpoint): """ Poll the data from prometheus and return the metrics as a generator. """ response = self.poll(endpoint) try: # no dry run if no label joins if not self.label_joins: self._dry_run = False e...
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, endpoint, **kwargs): """ 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 as additional custom ta...
Handle a prometheus metric message according to the following flow: - search self. 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, message, **kwargs): """ Handle a prometheus metric message according to the following flow: - search self.metrics_mapper for a prometheus.metric <--> datadog.metric mapping - call check method with the same name as the metric - log some info i...
Polls the metrics from the prometheus metrics endpoint provided. Defaults to the protobuf format but can use the formats specified by the PrometheusFormat class. Custom headers can be added to the default headers.
def poll(self, endpoint, pFormat=PrometheusFormat.PROTOBUF, headers=None): """ Polls the metrics from the prometheus metrics endpoint provided. Defaults to the protobuf format, but can use the formats specified by the PrometheusFormat class. Custom headers can be added to the def...
For each metric in the message 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( self, metric_name, message, send_histograms_buckets=True, send_monotonic_counter=False, custom_tags=None, hostname=None, ): """ For each metric in the message, report it as a gauge with all labels as tags except if a labels...
If hostname is None look at label_to_hostname setting
def _get_hostname(self, hostname, metric): """ If hostname is None, look at label_to_hostname setting """ if hostname is None and self.label_to_hostname is not None: for label in metric.label: if label.name == self.label_to_hostname: return...
Extracts metrics from a prometheus summary metric and sends them as gauges
def _submit_gauges_from_summary(self, name, metric, custom_tags=None, hostname=None): """ Extracts metrics from a prometheus summary metric and sends them as gauges """ if custom_tags is None: custom_tags = [] # summaries do not have a value attribute val = ge...
Extracts metrics from a prometheus histogram and sends them as gauges
def _submit_gauges_from_histogram( self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None ): """ Extracts metrics from a prometheus histogram and sends them as gauges """ if custom_tags is None: custom_tags = [] # histograms do n...
See if a personal access token was passed
def get_auth_info(config=None): """ See if a personal access token was passed """ gh_config = (config or {}).get('github', {}) user = gh_config.get('user') or os.getenv('DD_GITHUB_USER') token = gh_config.get('token') or os.getenv('DD_GITHUB_TOKEN') if user and token: return user, to...
Fetch the labels from the PR and process the ones related to the changelog.
def get_changelog_types(pr_payload): """ Fetch the labels from the PR and process the ones related to the changelog. """ changelog_labels = [] for name in get_pr_labels(pr_payload): if name.startswith(CHANGELOG_LABEL_PREFIX): # only add the name, e.g. for `changelog/Added` it's j...
Get the payload for the given PR number. Let exceptions bubble up.
def get_pr(pr_num, config=None, repo=DEFAULT_REPO, raw=False): """ Get the payload for the given PR number. Let exceptions bubble up. """ response = requests.get(PR_ENDPOINT.format(repo, pr_num), auth=get_auth_info(config)) if raw: return response else: response.raise_for_status...
Parse PR numbers from commit messages. At GitHub those have the format:
def parse_pr_numbers(git_log_lines): """ Parse PR numbers from commit messages. At GitHub those have the format: `here is the message (#1234)` being `1234` the PR number. """ prs = [] for line in git_log_lines: pr_number = parse_pr_number(line) if pr_number: ...
Start. Multiple calls have no effect.
def open(self): """Start. Multiple calls have no effect. Not safe to call from multiple threads at once. """ with self._lock: if self._thread_will_exit: # If the background thread has read self._stopped as True # there is a chance that it has ...
For more info see: https:// tox. readthedocs. io/ en/ latest/ plugins. html For an example see: https:// github. com/ tox - dev/ tox - travis
def tox_configure(config): """ For more info, see: https://tox.readthedocs.io/en/latest/plugins.html For an example, see: https://github.com/tox-dev/tox-travis """ sections = config._cfg.sections # Cache these make_envconfig = None reader = None # Default to false so: # 1. we d...
Determine if collect_connection_state is set and can effectively run. If self. _collect_cx_state is True and a custom proc_location is provided the system cannot run ss or netstat over a custom proc_location: param proc_location: str: return: bool
def _is_collect_cx_state_runnable(self, proc_location): """ Determine if collect_connection_state is set and can effectively run. If self._collect_cx_state is True and a custom proc_location is provided, the system cannot run `ss` or `netstat` over a custom proc_location :param ...
_check_linux can be run inside a container and still collects the network metrics from the host For that procfs_path can be set to something like/ host/ proc When a custom procfs_path is set the collect_connection_state option is ignored
def _check_linux(self, instance): """ _check_linux can be run inside a container and still collects the network metrics from the host For that procfs_path can be set to something like "/host/proc" When a custom procfs_path is set, the collect_connection_state option is ignored ""...
Parse the output of conntrack - S Add the parsed metrics
def _add_conntrack_stats_metrics(self, conntrack_path, tags): """ Parse the output of conntrack -S Add the parsed metrics """ try: output, _, _ = get_subprocess_output(["sudo", conntrack_path, "-S"], self.log) # conntrack -S sample: # cpu=0 fou...
Parse the output of the command that retrieves the connection state ( either ss or netstat ) Returns a dict metric_name - > value
def _parse_linux_cx_state(self, lines, tcp_states, state_col, protocol=None, ip_version=None): """ Parse the output of the command that retrieves the connection state (either `ss` or `netstat`) Returns a dict metric_name -> value """ metrics = {} for _, val in iteritems(s...
Return a mapping of network metrics by interface. For example: { interface: { bytes_sent: 0 bytes_rcvd: 0 bytes_rcvd: 0... } }
def _parse_solaris_netstat(self, netstat_output): """ Return a mapping of network metrics by interface. For example: { interface: {'bytes_sent': 0, 'bytes_rcvd': 0, 'bytes_rcvd': 0, ... } } ...
Gather metrics about connections states and interfaces counters using psutil facilities
def _check_psutil(self, instance): """ Gather metrics about connections states and interfaces counters using psutil facilities """ custom_tags = instance.get('tags', []) if self._collect_cx_state: self._cx_state_psutil(tags=custom_tags) self._cx_count...
Collect metrics about connections state using psutil
def _cx_state_psutil(self, tags=None): """ Collect metrics about connections state using psutil """ metrics = defaultdict(int) tags = [] if tags is None else tags for conn in psutil.net_connections(): protocol = self._parse_protocol_psutil(conn) st...
Collect metrics about interfaces counters using psutil
def _cx_counters_psutil(self, tags=None): """ Collect metrics about interfaces counters using psutil """ tags = [] if tags is None else tags for iface, counters in iteritems(psutil.net_io_counters(pernic=True)): metrics = { 'bytes_rcvd': counters.bytes...
Returns a string describing the protocol for the given connection in the form tcp4 udp4 as in self. cx_state_gauge
def _parse_protocol_psutil(self, conn): """ Returns a string describing the protocol for the given connection in the form `tcp4`, 'udp4` as in `self.cx_state_gauge` """ protocol = self.PSUTIL_TYPE_MAPPING.get(conn.type, '') family = self.PSUTIL_FAMILY_MAPPING.get(conn.fam...
Process the work unit or wait for sentinel to exit
def run(self): """Process the work unit, or wait for sentinel to exit""" while True: self.running = True workunit = self._workq.get() if is_sentinel(workunit): # Got sentinel break # Run the job / sequence worku...
Equivalent of the apply () builtin function. It blocks till the result is ready.
def apply(self, func, args=(), kwds=dict()): """Equivalent of the apply() builtin function. It blocks till the result is ready.""" return self.apply_async(func, args, kwds).get()
A parallel equivalent of the map () builtin function. It blocks till the result is ready.
def map(self, func, iterable, chunksize=None): """A parallel equivalent of the map() builtin function. It blocks till the result is ready. This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of the...
An equivalent of itertools. imap ().
def imap(self, func, iterable, chunksize=1): """ An equivalent of itertools.imap(). The chunksize argument is the same as the one used by the map() method. For very long iterables using a large value for chunksize can make make the job complete much faster than using the...
The same as imap () except that the ordering of the results from the returned iterator should be considered arbitrary. ( Only when there is only one worker process is the order guaranteed to be correct. )
def imap_unordered(self, func, iterable, chunksize=1): """The same as imap() except that the ordering of the results from the returned iterator should be considered arbitrary. (Only when there is only one worker process is the order guaranteed to be "correct".)""" collector = Uno...
A variant of the apply () method which returns an ApplyResult object.
def apply_async(self, func, args=(), kwds=dict(), callback=None): """A variant of the apply() method which returns an ApplyResult object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready, callback is applied to ...
A variant of the map () method which returns a ApplyResult object.
def map_async(self, func, iterable, chunksize=None, callback=None): """A variant of the map() method which returns a ApplyResult object. If callback is specified then it should be a callable which accepts a single argument. When the result becomes ready callback is applied to it...
A variant of the imap () method which returns an ApplyResult object that provides an iterator ( next method ( timeout ) available ).
def imap_async(self, func, iterable, chunksize=None, callback=None): """A variant of the imap() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which accepts a single arg...
A variant of the imap_unordered () method which returns an ApplyResult object that provides an iterator ( next method ( timeout ) available ).
def imap_unordered_async(self, func, iterable, chunksize=None, callback=None): """A variant of the imap_unordered() method which returns an ApplyResult object that provides an iterator (next method(timeout) available). If callback is specified then it should be a callable which ...
Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate () will be called immediately.
def terminate(self): """Stops the worker processes immediately without completing outstanding work. When the pool object is garbage collected terminate() will be called immediately.""" self.close() # Clearing the job queue try: while 1: self._...
Create the WorkUnit objects to process and pushes them on the work queue. Each work unit is meant to process a slice of iterable of size chunksize. If collector is specified then the ApplyResult objects associated with the jobs will notify collector when their result becomes ready.
def _create_sequences(self, func, iterable, chunksize, collector=None): """ Create the WorkUnit objects to process and pushes them on the work queue. Each work unit is meant to process a slice of iterable of size chunksize. If collector is specified, then the ApplyResult objects ...
Call the function with the args/ kwds and tell the ApplyResult that its result is ready. Correctly handles the exceptions happening during the execution of the function
def process(self): """ Call the function with the args/kwds and tell the ApplyResult that its result is ready. Correctly handles the exceptions happening during the execution of the function """ try: result = self._func(*self._args, **self._kwds) excep...
Returns the result when it arrives. If timeout is not None and the result does not arrive within timeout seconds then TimeoutError is raised. If the remote call raised an exception then that exception will be reraised by get ().
def get(self, timeout=None): """ Returns the result when it arrives. If timeout is not None and the result does not arrive within timeout seconds then TimeoutError is raised. If the remote call raised an exception then that exception will be reraised by get(). """ ...
Waits until the result is available or until timeout seconds pass.
def wait(self, timeout=None): """Waits until the result is available or until timeout seconds pass.""" self._event.wait(timeout) return self._event.isSet()
Called by a Job object to tell the result is ready and provides the value of this result. The object will become ready and successful. The collector s notify_ready () method will be called and the callback method too
def _set_value(self, value): """Called by a Job object to tell the result is ready, and provides the value of this result. The object will become ready and successful. The collector's notify_ready() method will be called, and the callback method too""" assert not self.ready() ...
Called by a Job object to tell that an exception occured during the processing of the function. The object will become ready but not successful. The collector s notify_ready () method will be called but NOT the callback method
def _set_exception(self): """Called by a Job object to tell that an exception occured during the processing of the function. The object will become ready but not successful. The collector's notify_ready() method will be called, but NOT the callback method""" assert not self.ready...
Return the next result value in the sequence. Raise StopIteration at the end. Can raise the exception raised by the Job
def next(self, timeout=None): """Return the next result value in the sequence. Raise StopIteration at the end. Can raise the exception raised by the Job""" try: apply_result = self._collector._get_result(self._idx, timeout) except IndexError: # Reset for n...
Called by the CollectorIterator object to retrieve the result s values one after another in the order the results have become available. \ param idx The index of the result we want wrt collector s order \ param timeout integer telling how long to wait ( in seconds ) for the result at index idx to be available or None (...
def _get_result(self, idx, timeout=None): """Called by the CollectorIterator object to retrieve the result's values one after another, in the order the results have become available. \param idx The index of the result we want, wrt collector's order \param timeout integer telling ...
Called by the ApplyResult object ( already registered via register_result () ) that it is now ready ( ie. the Job s result is available or an exception has been raised ). \ param apply_result ApplyResult object telling us that the job has been processed
def notify_ready(self, apply_result): """Called by the ApplyResult object (already registered via register_result()) that it is now ready (ie. the Job's result is available or an exception has been raised). \param apply_result ApplyResult object telling us that the job has been p...
Called by the CollectorIterator object to retrieve the result s values one after another ( order defined by the implementation ) \ param idx The index of the result we want wrt collector s order \ param timeout integer telling how long to wait ( in seconds ) for the result at index idx to be available or None ( wait fo...
def _get_result(self, idx, timeout=None): """Called by the CollectorIterator object to retrieve the result's values one after another (order defined by the implementation) \param idx The index of the result we want, wrt collector's order \param timeout integer telling how long to...
Called by the ApplyResult object ( already registered via register_result () ) that it is now ready ( ie. the Job s result is available or an exception has been raised ). \ param apply_result ApplyResult object telling us that the job has been processed
def notify_ready(self, apply_result): """Called by the ApplyResult object (already registered via register_result()) that it is now ready (ie. the Job's result is available or an exception has been raised). \param apply_result ApplyResult object telling us that the job has been p...
Execute a command over the socket or raise socket. error.
def command(sock, dbname, spec, slave_ok, is_mongos, read_preference, codec_options, check=True, allowable_errors=None, address=None, check_keys=False, listeners=None, max_bson_size=None, read_concern=DEFAULT_READ_CONCERN, parse_write_concern_error=False, ...
Receive a raw BSON message or raise socket. error.
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
See: https:// github. com/ python/ cpython/ blob/ 40ee9a3640d702bce127e9877c82a99ce817f0d1/ Lib/ socket. py#L691
def create_connection(self): """See: https://github.com/python/cpython/blob/40ee9a3640d702bce127e9877c82a99ce817f0d1/Lib/socket.py#L691""" err = None try: for res in socket.getaddrinfo(self._server, self._port, 0, self._sock_type): af, socktype, proto, canonname, sa =...
Helper function that wraps: func: json. dumps.
def dumps(obj, *args, **kwargs): """Helper function that wraps :func:`json.dumps`. Recursive function that handles all BSON types including :class:`~bson.binary.Binary` and :class:`~bson.code.Code`. :Parameters: - `json_options`: A :class:`JSONOptions` instance used to modify the encodin...
Helper function that wraps: func: json. loads.
def loads(s, *args, **kwargs): """Helper function that wraps :func:`json.loads`. Automatically passes the object_hook for BSON type conversion. Raises ``TypeError``, ``ValueError``, ``KeyError``, or :exc:`~bson.errors.InvalidId` on invalid MongoDB Extended JSON. :Parameters: - `json_options...
Recursive helper method that converts BSON types so they can be converted into json.
def _json_convert(obj, json_options=DEFAULT_JSON_OPTIONS): """Recursive helper method that converts BSON types so they can be converted into json. """ if hasattr(obj, 'iteritems') or hasattr(obj, 'items'): # PY3 support return SON(((k, _json_convert(v, json_options)) for k, ...
Decode a JSON datetime to python datetime. datetime.
def _parse_canonical_datetime(doc, json_options): """Decode a JSON datetime to python datetime.datetime.""" dtm = doc["$date"] if len(doc) != 1: raise TypeError('Bad $date, extra field(s): %s' % (doc,)) # mongoexport 2.6 and newer if isinstance(dtm, string_type): # Parse offset ...
Decode a JSON symbol to Python string.
def _parse_canonical_symbol(doc): """Decode a JSON symbol to Python string.""" symbol = doc['$symbol'] if len(doc) != 1: raise TypeError('Bad $symbol, extra field(s): %s' % (doc,)) return text_type(symbol)
Decode a JSON code to bson. code. Code.
def _parse_canonical_code(doc): """Decode a JSON code to bson.code.Code.""" for key in doc: if key not in ('$code', '$scope'): raise TypeError('Bad $code, extra field(s): %s' % (doc,)) return Code(doc['$code'], scope=doc.get('$scope'))
Decode a JSON regex to bson. regex. Regex.
def _parse_canonical_regex(doc): """Decode a JSON regex to bson.regex.Regex.""" regex = doc['$regularExpression'] if len(doc) != 1: raise TypeError('Bad $regularExpression, extra field(s): %s' % (doc,)) if len(regex) != 2: raise TypeError('Bad $regularExpression must include only "patter...
Decode a JSON DBRef to bson. dbref. DBRef.
def _parse_canonical_dbref(doc): """Decode a JSON DBRef to bson.dbref.DBRef.""" for key in doc: if key.startswith('$') and key not in _DBREF_KEYS: # Other keys start with $, so dct cannot be parsed as a DBRef. return doc return DBRef(doc.pop('$ref'), doc.pop('$id'), ...
Decode a JSON ( deprecated ) DBPointer to bson. dbref. DBRef.
def _parse_canonical_dbpointer(doc): """Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.""" dbref = doc['$dbPointer'] if len(doc) != 1: raise TypeError('Bad $dbPointer, extra field(s): %s' % (doc,)) if isinstance(dbref, DBRef): dbref_doc = dbref.as_doc() # DBPointer must...
Decode a JSON int32 to python int.
def _parse_canonical_int32(doc): """Decode a JSON int32 to python int.""" i_str = doc['$numberInt'] if len(doc) != 1: raise TypeError('Bad $numberInt, extra field(s): %s' % (doc,)) if not isinstance(i_str, string_type): raise TypeError('$numberInt must be string: %s' % (doc,)) return...
Decode a JSON int64 to bson. int64. Int64.
def _parse_canonical_int64(doc): """Decode a JSON int64 to bson.int64.Int64.""" l_str = doc['$numberLong'] if len(doc) != 1: raise TypeError('Bad $numberLong, extra field(s): %s' % (doc,)) return Int64(l_str)
Decode a JSON double to python float.
def _parse_canonical_double(doc): """Decode a JSON double to python float.""" d_str = doc['$numberDouble'] if len(doc) != 1: raise TypeError('Bad $numberDouble, extra field(s): %s' % (doc,)) if not isinstance(d_str, string_type): raise TypeError('$numberDouble must be string: %s' % (doc,...
Decode a JSON decimal128 to bson. decimal128. Decimal128.
def _parse_canonical_decimal128(doc): """Decode a JSON decimal128 to bson.decimal128.Decimal128.""" d_str = doc['$numberDecimal'] if len(doc) != 1: raise TypeError('Bad $numberDecimal, extra field(s): %s' % (doc,)) if not isinstance(d_str, string_type): raise TypeError('$numberDecimal mu...
Decode a JSON MinKey to bson. min_key. MinKey.
def _parse_canonical_minkey(doc): """Decode a JSON MinKey to bson.min_key.MinKey.""" if doc['$minKey'] is not 1: raise TypeError('$minKey value must be 1: %s' % (doc,)) if len(doc) != 1: raise TypeError('Bad $minKey, extra field(s): %s' % (doc,)) return MinKey()
Decode a JSON MaxKey to bson. max_key. MaxKey.
def _parse_canonical_maxkey(doc): """Decode a JSON MaxKey to bson.max_key.MaxKey.""" if doc['$maxKey'] is not 1: raise TypeError('$maxKey value must be 1: %s', (doc,)) if len(doc) != 1: raise TypeError('Bad $minKey, extra field(s): %s' % (doc,)) return MaxKey()
Parse authentication credentials.
def _parse_credentials(username, password, database, options): """Parse authentication credentials.""" mechanism = options.get('authmechanism', 'DEFAULT') if username is None and mechanism != 'MONGODB-X509': return None source = options.get('authsource', database or 'admin') return _build_cr...
Parse read preference options.
def _parse_read_preference(options): """Parse read preference options.""" if 'read_preference' in options: return options['read_preference'] name = options.get('readpreference', 'primary') mode = read_pref_mode_from_name(name) tags = options.get('readpreferencetags') max_staleness = opt...
Parse connection pool options.
def _parse_pool_options(options): """Parse connection pool options.""" max_pool_size = options.get('maxpoolsize', common.MAX_POOL_SIZE) min_pool_size = options.get('minpoolsize', common.MIN_POOL_SIZE) max_idle_time_ms = options.get('maxidletimems', common.MAX_IDLE_TIME_MS) if max_pool_size is not No...
Validate all service_checks. json files.
def service_checks(): """Validate all `service_checks.json` files.""" root = get_root() echo_info("Validating all service_checks.json files...") failed_checks = 0 ok_checks = 0 for check_name in sorted(os.listdir(root)): service_checks_file = os.path.join(root, check_name, 'service_check...
Convenience wrapper to take a series of date/ time elements and return a WMI time of the form yyyymmddHHMMSS. mmmmmm + UUU. All elements may be int string or omitted altogether. If omitted they will be replaced in the output string by a series of stars of the appropriate length.: param year: The year element of the dat...
def from_time( year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None ): """Convenience wrapper to take a series of date/time elements and return a WMI time of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or omitted altogether. ...
Convenience wrapper to take a WMI datetime string of the form yyyymmddHHMMSS. mmmmmm + UUU and return a 9 - tuple containing the individual elements or None where string contains placeholder stars.
def to_time(wmi_time): """Convenience wrapper to take a WMI datetime string of the form yyyymmddHHMMSS.mmmmmm+UUU and return a 9-tuple containing the individual elements, or None where string contains placeholder stars. :param wmi_time: The WMI datetime string in `yyyymmddHHMMSS.mmmmmm+UUU` format ...
Format tag_query or raise on incorrect parameters.
def _format_tag_query(self, sampler, wmi_obj, tag_query): """ Format `tag_query` or raise on incorrect parameters. """ try: link_source_property = int(wmi_obj[tag_query[0]]) target_class = tag_query[1] link_target_class_property = tag_query[2] ...
Design a query based on the given WMIObject to extract a tag.
def _get_tag_query_tag(self, sampler, wmi_obj, tag_query): """ Design a query based on the given WMIObject to extract a tag. Returns: tag or TagQueryUniquenessFailure exception. """ self.log.debug( u"`tag_queries` parameter found." " wmi_object={wmi_obj} ...
Extract and tag metrics from the WMISampler.
def _extract_metrics(self, wmi_sampler, tag_by, tag_queries, constant_tags): """ Extract and tag metrics from the WMISampler. Raise when multiple WMIObject were returned by the sampler with no `tag_by` specified. Returns: List of WMIMetric ``` [ WMIMetric("f...
Resolve metric names and types and submit it.
def _submit_metrics(self, metrics, metric_name_and_type_by_property): """ Resolve metric names and types and submit it. """ for metric in metrics: if ( metric.name not in metric_name_and_type_by_property and metric.name.lower() not in metric_na...
Return an index key for a given instance. Useful for caching.
def _get_instance_key(self, host, namespace, wmi_class, other=None): """ Return an index key for a given instance. Useful for caching. """ if other: return "{host}:{namespace}:{wmi_class}-{other}".format( host=host, namespace=namespace, wmi_class=wmi_class, ot...
Create and cache a WMISampler for the given ( class properties )
def _get_wmi_sampler(self, instance_key, wmi_class, properties, tag_by="", **kwargs): """ Create and cache a WMISampler for the given (class, properties) """ properties = list(properties) + [tag_by] if tag_by else list(properties) if instance_key not in self.wmi_samplers: ...
Create and cache a ( metric name metric type ) by WMI property map and a property list.
def _get_wmi_properties(self, instance_key, metrics, tag_queries): """ Create and cache a (metric name, metric type) by WMI property map and a property list. """ if instance_key not in self.wmi_props: metric_name_by_property = dict( (wmi_property.lower(), (met...