desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Parse WMI query results in a more comprehensive form.
Returns: List of WMI objects
\'freemegabytes\': 19742.0,
\'name\': \'C:\',
\'avgdiskbytesperwrite\': 1536.0
\'freemegabytes\': 19742.0,
\'name\': \'D:\',
\'avgdiskbytesperwrite\': 1536.0'
| def _parse_results(self, raw_results, includes_qualifiers):
| results = []
for res in raw_results:
item = CaseInsensitiveDict()
for prop_name in self.property_names:
item[prop_name] = None
for wmi_property in res.Properties_:
should_get_qualifier_type = (includes_qualifiers and (wmi_property.Name not in self._property_counte... |
'\param workq: Queue object to consume the work units from'
| def __init__(self, workq, *args, **kwds):
| threading.Thread.__init__(self, *args, **kwds)
self._workq = workq
self.running = False
|
'Process the work unit, or wait for sentinel to exit'
| def run(self):
| while 1:
self.running = True
workunit = self._workq.get()
if is_sentinel(workunit):
break
workunit.process()
self.running = False
|
'\param nworkers (integer) number of worker threads to start
\param name (string) prefix for the worker threads\' name'
| def __init__(self, nworkers, name='Pool'):
| self._workq = Queue.Queue()
self._closed = False
self._workers = []
for idx in xrange(nworkers):
thr = PoolWorker(self._workq, name=('Worker-%s-%d' % (name, idx)))
try:
thr.start()
except:
self.terminate()
raise
else:
self._... |
'Equivalent of the apply() builtin function. It blocks till
the result is ready.'
| def apply(self, func, args=(), kwds=dict()):
| return self.apply_async(func, args, kwds).get()
|
'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 these chunks can be specified by setting
chunksize to a positive integer.'
| def map(self, func, iterable, chunksize=None):
| return self.map_async(func, iterable, chunksize).get()
|
'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 default value of 1.
Also if chunksize is 1 then the next() method of the iterator
returned by th... | def imap(self, func, iterable, chunksize=1):
| collector = OrderedResultCollector(as_iterator=True)
self._create_sequences(func, iterable, chunksize, collector)
return iter(collector)
|
'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):
| collector = UnorderedResultCollector()
self._create_sequences(func, iterable, chunksize, collector)
return iter(collector)
|
'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 it (unless the call failed). callback
should complete immediately since otherwise the thread which
handles th... | def apply_async(self, func, args=(), kwds=dict(), callback=None):
| assert (not self._closed)
apply_result = ApplyResult(callback=callback)
job = Job(func, args, kwds, apply_result)
self._workq.put(job)
return apply_result
|
'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 (unless the call failed). callback
should complete immediately since otherwise the thread which
handles the re... | def map_async(self, func, iterable, chunksize=None, callback=None):
| apply_result = ApplyResult(callback=callback)
collector = OrderedResultCollector(apply_result, as_iterator=False)
self._create_sequences(func, iterable, chunksize, collector)
return apply_result
|
'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 argument. When the resulting iterator becomes
ready, callback is applied to it (unless the call
failed). callback s... | def imap_async(self, func, iterable, chunksize=None, callback=None):
| apply_result = ApplyResult(callback=callback)
collector = OrderedResultCollector(apply_result, as_iterator=True)
self._create_sequences(func, iterable, chunksize, collector)
return apply_result
|
'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
accepts a single argument. When the resulting iterator becomes
ready, callback is applied to it (unless the call
failed). ... | def imap_unordered_async(self, func, iterable, chunksize=None, callback=None):
| apply_result = ApplyResult(callback=callback)
collector = UnorderedResultCollector(apply_result)
self._create_sequences(func, iterable, chunksize, collector)
return apply_result
|
'Prevents any more tasks from being submitted to the
pool. Once all the tasks have been completed the worker
processes will exit.'
| def close(self):
| self._closed = True
|
'Stops the worker processes immediately without completing
outstanding work. When the pool object is garbage collected
terminate() will be called immediately.'
| def terminate(self):
| self.close()
try:
while 1:
self._workq.get_nowait()
except Queue.Empty:
pass
for thr in self._workers:
self._workq.put(SENTINEL)
|
'Wait for the worker processes to exit. One must call
close() or terminate() before using join().'
| def join(self):
| for thr in self._workers:
thr.join()
|
'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.
eturn the list of WorkUnit objects ... | def _create_sequences(self, func, iterable, chunksize, collector=None):
| assert (not self._closed)
sequences = []
results = []
it_ = iter(iterable)
exit_loop = False
while (not exit_loop):
seq = []
for i in xrange((chunksize or 1)):
try:
arg = it_.next()
except StopIteration:
exit_loop = True
... |
'Do the work. Shouldn\'t raise any exception'
| def process(self):
| raise NotImplementedError('Children must override Process')
|
'\param func/args/kwds used to call the function
\param apply_result ApplyResult object that holds the result
of the function call'
| def __init__(self, func, args, kwds, apply_result):
| WorkUnit.__init__(self)
self._func = func
self._args = args
self._kwds = kwds
self._result = apply_result
|
'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):
| try:
result = self._func(*self._args, **self._kwds)
except:
self._result._set_exception()
else:
self._result._set_value(result)
|
'Call process() on all the Job objects that have been specified'
| def process(self):
| for job in self._jobs:
job.process()
|
'\param collector when not None, the notify_ready() method of
the collector will be called when the result from the Job is
ready
\param callback when not None, function to call when the
result becomes available (this is the paramater passed to the
Pool::*_async() methods.'
| def __init__(self, collector=None, callback=None):
| self._success = False
self._event = threading.Event()
self._data = None
self._collector = None
self._callback = callback
if (collector is not None):
collector.register_result(self)
self._collector = collector
|
'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):
| if (not self.wait(timeout)):
raise TimeoutError(('Result not available within %fs' % timeout))
if self._success:
return self._data
raise self._data[0], self._data[1], self._data[2]
|
'Waits until the result is available or until timeout
seconds pass.'
| def wait(self, timeout=None):
| self._event.wait(timeout)
return self._event.isSet()
|
'Returns whether the call has completed.'
| def ready(self):
| return self._event.isSet()
|
'Returns whether the call completed without raising an
exception. Will raise AssertionError if the result is not
ready.'
| def successful(self):
| assert self.ready()
return self._success
|
'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):
| assert (not self.ready())
self._data = value
self._success = True
self._event.set()
if (self._collector is not None):
self._collector.notify_ready(self)
if (self._callback is not None):
try:
self._callback(value)
except:
traceback.print_exc()
|
'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):
| assert (not self.ready())
self._data = sys.exc_info()
self._success = False
self._event.set()
if (self._collector is not None):
self._collector.notify_ready(self)
|
'\param to_notify ApplyResult object to notify when all the
results we\'re waiting for become available. Can be None.'
| def __init__(self, to_notify):
| self._to_notify = to_notify
|
'Used to identify which results we\'re waiting for. Will
always be called BEFORE the Jobs get submitted to the work
queue, and BEFORE the __iter__ and _get_result() methods can
be called
\param apply_result ApplyResult object to add in our collection'
| def register_result(self, apply_result):
| raise NotImplementedError('Children classes must implement it')
|
'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):
| raise NotImplementedError('Children classes must implement it')
|
'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
fore... | def _get_result(self, idx, timeout=None):
| raise NotImplementedError('Children classes must implement it')
|
'Return a new CollectorIterator object for this collector'
| def __iter__(self):
| return CollectorIterator(self)
|
'\param AbstractResultCollector instance'
| def __init__(self, collector):
| self._collector = collector
self._idx = 0
|
'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):
| try:
apply_result = self._collector._get_result(self._idx, timeout)
except IndexError:
self._idx = 0
raise StopIteration
except:
self._idx = 0
raise
self._idx += 1
assert apply_result.ready()
return apply_result.get(0)
|
'\param to_notify ApplyResult object to notify when all the
results we\'re waiting for become available. Can be None.'
| def __init__(self, to_notify=None):
| AbstractResultCollector.__init__(self, to_notify)
self._cond = threading.Condition()
self._collection = []
self._expected = 0
|
'Used to identify which results we\'re waiting for. Will
always be called BEFORE the Jobs get submitted to the work
queue, and BEFORE the __iter__ and _get_result() methods can
be called
\param apply_result ApplyResult object to add in our collection'
| def register_result(self, apply_result):
| self._expected += 1
|
'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):
| self._cond.acquire()
try:
if (idx >= self._expected):
raise IndexError
elif (idx < len(self._collection)):
return self._collection[idx]
elif (idx != len(self._collection)):
raise IndexError()
else:
self._cond.wait(timeout=timeout)
... |
'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):
| first_item = False
self._cond.acquire()
try:
self._collection.append(apply_result)
first_item = (len(self._collection) == 1)
self._cond.notifyAll()
finally:
self._cond.release()
if (first_item and (self._to_notify is not None)):
self._to_notify._set_value(iter... |
'\param to_notify ApplyResult object to notify when all the
results we\'re waiting for become available. Can be None.
\param as_iterator boolean telling whether the result value
set on to_notify should be an iterator (available as soon as 1
result arrived) or a list (available only after the last
result arrived)'
| def __init__(self, to_notify=None, as_iterator=True):
| AbstractResultCollector.__init__(self, to_notify)
self._results = []
self._lock = threading.Lock()
self._remaining = 0
self._as_iterator = as_iterator
|
'Used to identify which results we\'re waiting for. Will
always be called BEFORE the Jobs get submitted to the work
queue, and BEFORE the __iter__ and _get_result() methods can
be called
\param apply_result ApplyResult object to add in our collection'
| def register_result(self, apply_result):
| self._results.append(apply_result)
self._remaining += 1
|
'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
fore... | def _get_result(self, idx, timeout=None):
| res = self._results[idx]
res.wait(timeout)
return res
|
'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):
| got_first = False
got_last = False
self._lock.acquire()
try:
assert (self._remaining > 0)
got_first = (len(self._results) == self._remaining)
self._remaining -= 1
got_last = (self._remaining == 0)
finally:
self._lock.release()
if (self._to_notify is not No... |
'This function should be implemented by inherited classes'
| def _check(self, instance):
| raise NotImplementedError
|
'Format `tag_query` or raise on incorrect parameters.'
| def _format_tag_query(self, sampler, wmi_obj, tag_query):
| try:
link_source_property = int(wmi_obj[tag_query[0]])
target_class = tag_query[1]
link_target_class_property = tag_query[2]
target_property = tag_query[3]
except IndexError:
self.log.error(u'Wrong `tag_queries` parameter format. Please refer to the ... |
''
| def _raise_on_invalid_tag_query_result(self, sampler, wmi_obj, tag_query):
| target_property = sampler.property_names[0]
target_class = sampler.class_name
if (len(sampler) != 1):
message = 'no result was returned'
if len(sampler):
message = 'multiple results returned (one expected)'
self.log.warning(u'Failed to extract ... |
'Design a query based on the given WMIObject to extract a tag.
Returns: tag or TagQueryUniquenessFailure exception.'
| def _get_tag_query_tag(self, sampler, wmi_obj, tag_query):
| self.log.debug(u'`tag_queries` parameter found. wmi_object={wmi_obj} - query={tag_query}'.format(wmi_obj=wmi_obj, tag_query=tag_query))
(target_class, target_property, filters) = self._format_tag_query(sampler, wmi_obj, tag_query)
tag_query_sampler = WMISampler(self.log, target_class, [target... |
'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("freemegabytes", 19742, ["name:_total"]),
WMIMetric("avgdiskbytesperwrite", 1536, ["name:c:"]),'
| def _extract_metrics(self, wmi_sampler, tag_by, tag_queries, constant_tags):
| if ((len(wmi_sampler) > 1) and (not tag_by)):
raise MissingTagBy(u'WMI query returned multiple rows but no `tag_by` value was given. class={wmi_class} - properties={wmi_properties} - filters={filters}'.format(wmi_class=wmi_sampler.class_name, wmi_properties=wmi_s... |
'Resolve metric names and types and submit it.'
| def _submit_metrics(self, metrics, metric_name_and_type_by_property):
| for metric in metrics:
if (metric.name not in metric_name_and_type_by_property):
continue
(metric_name, metric_type) = metric_name_and_type_by_property[metric.name]
try:
func = getattr(self, metric_type.lower())
except AttributeError:
raise Excepti... |
'Return an index key for a given instance. Useful for caching.'
| def _get_instance_key(self, host, namespace, wmi_class, other=None):
| if other:
return '{host}:{namespace}:{wmi_class}-{other}'.format(host=host, namespace=namespace, wmi_class=wmi_class, other=other)
return '{host}:{namespace}:{wmi_class}'.format(host=host, namespace=namespace, wmi_class=wmi_class)
|
'Create and cache a WMISampler for the given (class, properties)'
| def _get_wmi_sampler(self, instance_key, wmi_class, properties, tag_by='', **kwargs):
| properties = ((properties + [tag_by]) if tag_by else properties)
if (instance_key not in self.wmi_samplers):
wmi_sampler = WMISampler(self.log, wmi_class, properties, **kwargs)
self.wmi_samplers[instance_key] = wmi_sampler
return self.wmi_samplers[instance_key]
|
'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):
| if (instance_key not in self.wmi_props):
metric_name_by_property = dict(((wmi_property.lower(), (metric_name, metric_type)) for (wmi_property, metric_name, metric_type) in metrics))
properties = map((lambda x: x[0]), (metrics + tag_queries))
self.wmi_props[instance_key] = (metric_name_by_pro... |
'Expecting dogstreams config value to look like:
<dogstream value>, <dog stream value>, ...
Where <dogstream value> looks like:
<log path>
or
<log path>:<module>:<parser function>'
| @classmethod
def _instantiate_dogstreams(cls, logger, config, dogstreams_config):
| dogstreams = []
for config_item in dogstreams_config.split(','):
try:
config_item = config_item.strip()
parts = windows_friendly_colon_split(config_item)
if (len(parts) == 2):
logger.warn(('Invalid dogstream: %s' % ':'.join(parts)))
... |
'Paths may include wildcard *\'s and ?\'s.'
| @classmethod
def _get_dogstream_log_paths(cls, path):
| if ('*' not in path):
return [path]
return glob.glob(path)
|
'Aggregate values down to the second and store as:
"dogstream": [(metric, timestamp, value, {key: val})]
If there are many values per second for a metric, take the median'
| def _aggregate(self, values):
| output = []
values.sort(key=point_sorter)
for ((timestamp, metric, host_name, device_name), val_attrs) in groupby(values, key=point_sorter):
attributes = {}
vals = []
for (_metric, _timestamp, v, a) in val_attrs:
try:
v = float(v)
vals.appe... |
'Single payload with the content of data and metadata payloads.'
| @property
def payload(self):
| res = self.data_payload.copy()
res.update(self.meta_payload)
return res
|
'Send payloads via the emitters.
:param merge_payloads: merge data and metadata payloads in a single payload and submit it
to the common endpoint
:type merge_payloads: boolean'
| def emit(self, log, config, emitters, continue_running, merge_payloads=True):
| statuses = []
def _emit_payload(payload, endpoint):
' Send the payload via the emitters. '
statuses = []
for emitter in emitters:
if (not continue_running):
return statuses
name = emitter.__name__
emitter_status = E... |
'Tell the collector to stop at the next logical point.'
| def stop(self):
| self.continue_running = False
for check in self.initialized_checks_d:
check.stop()
|
'Collect data from each check and submit their data.'
| @log_exceptions(log)
def run(self, checksd=None, start_event=True, configs_reloaded=False):
| log.debug('Found {num_checks} checks'.format(num_checks=len(checksd['initialized_checks'])))
timer = Timer()
if (not Platform.is_windows()):
cpu_clock = time.clock()
self.run_count += 1
log.debug(('Starting collection run #%s' % self.run_count))
if checksd:
self.in... |
'Send the payload via the emitters.'
| def _emit(self, payload):
| statuses = []
for emitter in self.emitters:
if (not self.continue_running):
return statuses
name = emitter.__name__
emitter_status = EmitterStatus(name)
try:
emitter(payload, log, self.agentConfig)
except Exception as e:
log.exception((... |
'Build the payload skeleton, so it contains all of the generic payload data.'
| def _build_payload(self, payload):
| now = time.time()
payload['collection_timestamp'] = now
payload['os'] = self.os
payload['python'] = sys.version
payload['agentVersion'] = self.agentConfig['version']
payload['apiKey'] = self.agentConfig['api_key']
payload['events'] = {}
payload['metrics'] = []
payload['service_checks... |
'Periodically populate the payload with metadata related to the system, host, and/or checks.'
| def _populate_payload_metadata(self, payload, check_statuses, start_event=True):
| now = time.time()
if (start_event and self._is_first_run()):
payload['systemStats'] = self.agentConfig.get('system_stats', {})
payload['events']['System'] = [{'api_key': self.agentConfig['api_key'], 'host': self.hostname, 'timestamp': now, 'event_type': 'Agent Startup', 'msg_text': ('Version ... |
'Returns a dictionnary that contains hostname metadata.'
| def _get_hostname_metadata(self):
| metadata = EC2.get_metadata(self.agentConfig)
if metadata.get('hostname'):
metadata['ec2-hostname'] = metadata.get('hostname')
del metadata['hostname']
if self.agentConfig.get('hostname'):
metadata['agent-hostname'] = self.agentConfig.get('hostname')
else:
try:
... |
'On Windows, decodes the timezone from the system-preferred encoding'
| @staticmethod
def _decode_tzname(tzname):
| if Platform.is_windows():
try:
decoded_tzname = map((lambda tz: tz.decode(locale.getpreferredencoding())), tzname)
except Exception:
log.exception('Failed decoding timezone with encoding %s', locale.getpreferredencoding())
return ('', '')
re... |
'Standardize on linux metric names'
| def xlate(self, metric_name, os_name):
| if (os_name == 'sunos'):
names = {'wait': 'await', 'svc_t': 'svctm', '%b': '%util', 'kr/s': 'rkB/s', 'kw/s': 'wkB/s', 'actv': 'avgqu-sz'}
elif (os_name == 'freebsd'):
names = {'svc_t': 'await', '%b': '%util', 'kr/s': 'rkB/s', 'kw/s': 'wkB/s', 'wait': 'avgqu-sz'}
return names.get(metric_name,... |
'Capture io stats.
@rtype dict
@return {"device": {"metric": value, "metric": value}, ...}'
| def check(self, agentConfig):
| io = {}
try:
if Platform.is_linux():
(stdout, _, _) = get_subprocess_output(['iostat', '-d', '1', '2', '-x', '-k'], self.logger)
io.update(self._parse_linux2(stdout))
elif (sys.platform == 'sunos5'):
(output, _, _) = get_subprocess_output(['iostat', '-x', '-d'... |
'Return an aggregate of CPU stats across all CPUs
When figures are not available, False is sent back.'
| def check(self, agentConfig):
| def format_results(us, sy, wa, idle, st, guest=None):
data = {'cpuUser': us, 'cpuSystem': sy, 'cpuWait': wa, 'cpuIdle': idle, 'cpuStolen': st, 'cpuGuest': guest}
return dict(((k, v) for (k, v) in data.iteritems() if (v is not None)))
def get_value(legend, data, name, filter_value=None):
... |
'check should take care of getting the url and other params
from the instance and using the utils to process messages and submit metrics.'
| def check(self, instance):
| raise NotImplementedError()
|
'Example method'
| def prometheus_metric_name(self, message, **kwargs):
| pass
|
'Gets the output data from a prometheus endpoint response along with its
Content-type header and parses it into Prometheus classes (see [0])
Parse the binary buffer in input, searching for Prometheus messages
of type MetricFamily [0] delimited by a varint32 [1] when the
content-type is a `application/vnd.google.protobu... | def parse_metric_family(self, buf, content_type):
| if ('application/vnd.google.protobuf' in content_type):
n = 0
while (n < len(buf)):
(msg_len, new_pos) = _DecodeVarint32(buf, n)
n = new_pos
msg_buf = buf[n:(n + msg_len)]
n += msg_len
message = metrics_pb2.MetricFamily()
messag... |
'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):
| _obj = metrics_pb2.MetricFamily()
_obj.name = _m
_obj.type = self.METRIC_TYPES.index(obj_map[_m])
if (_m in obj_help):
_obj.help = obj_help[_m]
_newlbl = _m
if (obj_map[_m] == 'histogram'):
_newlbl = '{}_bucket'.format(_m)
for _metric in messages[_newlbl]:
if ((obj_ma... |
'Extracts the metrics from a line of metric and update the given
dictionnaries (we take advantage of the reference of the dictionary here)'
| def _extract_metrics_from_string(self, line, messages, obj_map, obj_help):
| if line.startswith('# TYPE'):
metric = line.split(' ')
if (len(metric) == 4):
obj_map[metric[2]] = metric[3]
elif line.startswith('# HELP'):
_h = line.split(' ', 3)
if (len(_h) == 4):
obj_help[_h[2]] = _h[3]
elif (not line.startswith('#')):... |
'Extracts the labels from a string that looks like:
{label_name_1="value 1", label_name_2="value 2"}'
| def _extract_labels_from_string(self, labels):
| lbls = {}
labels = labels.lstrip('{').rstrip('}')
_lbls = self.lbl_pattern.findall(labels)
for _lbl in _lbls:
lbls[_lbl[0]] = _lbl[1]
return lbls
|
'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 additionnal custom tags and added to the metrics'
| def process(self, endpoint, send_histograms_buckets=True, instance=None):
| (content_type, data) = self.poll(endpoint)
tags = []
if (instance is not None):
tags = instance.get('tags', [])
for metric in self.parse_metric_family(data, content_type):
self.process_metric(metric, send_histograms_buckets=send_histograms_buckets, custom_tags=tags, instance=instance)
|
'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
`send_histograms_buckets` is used to specify if yes or no you want to sen... | def process_metric(self, message, send_histograms_buckets=True, custom_tags=None, **kwargs):
| try:
if (message.name in self.ignore_metrics):
return
if (message.name in self.metrics_mapper):
self._submit_metric(self.metrics_mapper[message.name], message, send_histograms_buckets, custom_tags)
else:
getattr(self, message.name)(message, **kwargs)
e... |
'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.
Returns the content-type of the response and the content of the reponse itself.'
| def poll(self, endpoint, pFormat=PrometheusFormat.PROTOBUF, headers={}):
| if ('accept-encoding' not in headers):
headers['accept-encoding'] = 'gzip'
if (pFormat == PrometheusFormat.PROTOBUF):
headers['accept'] = 'application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited'
req = requests.get(endpoint, headers=headers)
req... |
'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\'}).
Histograms generate a set of values instead of a unique metric.
send_histograms... | def _submit_metric(self, metric_name, message, send_histograms_buckets=True, custom_tags=None):
| if (message.type < len(self.METRIC_TYPES)):
for metric in message.metric:
if (message.type == 4):
self._submit_gauges_from_histogram(metric_name, metric, send_histograms_buckets, custom_tags)
elif (message.type == 2):
self._submit_gauges_from_summary(m... |
'Submit a metric as a gauge, additional tags provided will be added to
the ones from the label provided via the metrics object.
`custom_tags` is an array of \'tag:value\' that will be added to the
metric when sending the gauge to Datadog.'
| def _submit_gauge(self, metric_name, val, metric, custom_tags=None):
| _tags = []
if (custom_tags is not None):
_tags += custom_tags
for label in metric.label:
if ((self.exclude_labels is None) or (label.name not in self.exclude_labels)):
tag_name = label.name
if ((self.labels_mapper is not None) and (label.name in self.labels_mapper)):
... |
'Extracts metrics from a prometheus summary metric and sends them as gauges'
| def _submit_gauges_from_summary(self, name, metric, custom_tags=None):
| if (custom_tags is None):
custom_tags = []
val = getattr(metric, self.METRIC_TYPES[2]).sample_count
self._submit_gauge('{}.count'.format(name), val, metric, custom_tags)
val = getattr(metric, self.METRIC_TYPES[2]).sample_sum
self._submit_gauge('{}.sum'.format(name), val, metric, custom_tags)... |
'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):
| if (custom_tags is None):
custom_tags = []
val = getattr(metric, self.METRIC_TYPES[4]).sample_count
self._submit_gauge('{}.count'.format(name), val, metric, custom_tags)
val = getattr(metric, self.METRIC_TYPES[4]).sample_sum
self._submit_gauge('{}.sum'.format(name), val, metric, custom_tags)... |
'Override `stop` method to properly exit JMXFetch.'
| def stop(self):
| if ((self._proc is not None) and self._proc.is_running()):
JMXFiles.write_exit_file()
try:
self._proc.wait(timeout=self._JMX_STOP_TIMEOUT)
except psutil.TimeoutExpired:
log.debug("JMXFetch process didn't stop after %ss, killing it", self._JMX_STOP... |
'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):
| try:
self._open_file(move_end=move_end)
while True:
pos = self._f.tell()
line = self._f.readline()
if line:
line = line.strip(chr(0))
if self._callback(line.rstrip('\n')):
if line_by_line:
... |
'Enable the profiler'
| def enable_profiling(self):
| if (not self._profiler):
self._profiler = cProfile.Profile()
self._profiler.enable()
log.debug('Agent profiling is enabled')
|
'Disable the profiler, and if necessary dump a truncated pstats output'
| def disable_profiling(self):
| self._profiler.disable()
s = StringIO()
ps = pstats.Stats(self._profiler, stream=s).sort_stats('cumulative')
ps.print_stats(self.PSTATS_LIMIT)
log.debug(s.getvalue())
log.debug('Agent profiling is disabled')
if self.DUMP_TO_FILE:
try:
ps.dump_stats(self.STATS_DUM... |
'Wraps the function call in a cProfile run, processing and logging the output with pstats.Stats
Useful for profiling individual checks.
:param func: The function to profile'
| @staticmethod
def wrap_profiling(func):
| def wrapped_func(*args, **kwargs):
try:
profiler = cProfile.Profile()
profiler.enable()
log.debug('Agent profiling is enabled')
except Exception:
log.warn('Cannot enable profiler')
ret_val = func(*args, **kwargs)
try:
... |
'Extract settings from a config object'
| def _extract_settings(self, config):
| settings = {'host': config.get('sd_backend_host', DEFAULT_ZK_HOST), 'port': int(config.get('sd_backend_port', DEFAULT_ZK_PORT))}
return settings
|
'Retrieve a value from a Zookeeper key.'
| def client_read(self, path, **kwargs):
| try:
if kwargs.get('watch', False):
return self.recursive_mtime(path)
elif kwargs.get('all', False):
results = []
self.recursive_list(path, results)
return results
else:
(res, stats) = self.client.get(path)
return res.de... |
'Recursively walks the children from the given path and build a list of key/value tuples'
| def recursive_list(self, path, results):
| try:
(data, stat) = self.client.get(path)
if data:
node_as_string = data.decode('utf-8')
if (not node_as_string):
results.append((path.decode('utf-8'), node_as_string))
children = self.client.get_children(path)
if (children is not None):
... |
'Recursively walks the children from the given path to find the maximum modification time'
| def recursive_mtime(self, path):
| try:
(data, stat) = self.client.get(path)
children = self.client.get_children(path)
if ((children is not None) and (len(children) > 0)):
for child in children:
new_path = '/'.join([path.rstrip('/'), child])
return max(stat.mtime, self.recursive_mtime(n... |
'Return a dict made of all image names and their corresponding check info'
| def dump_directory(self, path, **kwargs):
| templates = {}
paths = []
self.recursive_list(path, paths)
for pair in paths:
splits = pair[0].split('/')
image = splits[(-2)]
param = splits[(-1)]
value = pair[1]
if (image not in templates):
templates[image] = {}
templates[image][param] = val... |
'Clear out the KV cache'
| def invalidate(self):
| log.debug('Clearing the cache for configuration templates.')
self.kv_templates = defaultdict((lambda : ([[]] * 3)))
|
'Retrieve auto_conf templates'
| def _populate_auto_conf(self):
| raw_templates = get_auto_conf_images(full_tpl=True)
for (image, tpls) in raw_templates.iteritems():
for (check_name, init_tpl, instance_tpl) in zip(*tpls):
if (image in self.auto_conf_templates):
if (check_name in self.auto_conf_templates[image][0]):
log.w... |
'Perform a read against the KV store'
| def _issue_read(self, identifier):
| try:
check_names = json.loads(self.read_func(path.join(self.root_path, identifier, CHECK_NAMES).lstrip('/')))
init_config_tpls = json.loads(self.read_func(path.join(self.root_path, identifier, INIT_CONFIGS).lstrip('/')))
instance_tpls = json.loads(self.read_func(path.join(self.root_path, ide... |
'Return a dict of templates coming from the config store and
the auto_conf folder and their source for a given identifier.
Templates from kv_templates take precedence.'
| def get_templates(self, identifier):
| templates = {CONFIG_FROM_TEMPLATE: None, CONFIG_FROM_AUTOCONF: None}
if (identifier not in self.kv_templates):
try:
tpls = self._issue_read(identifier)
except NotImplementedError:
tpls = None
except Exception:
tpls = None
log.exception(('Fa... |
'Return a set of all check names associated with an identifier'
| def get_check_names(self, identifier):
| check_names = set()
if ((identifier not in self.kv_templates) and (identifier not in self.auto_conf_templates)):
tpls = self.get_templates(identifier)
if (not tpls):
return check_names
auto_conf = tpls[CONFIG_FROM_AUTOCONF]
if auto_conf:
check_names.update... |
'Drop the config store instance. This is only used for testing.'
| @classmethod
def _drop(cls):
| if (cls in cls._instances):
del cls._instances[cls]
|
'Looks for autodiscovery configuration in a given source_dict (either docker labels
or kubernetes annotations) and returns it if found.'
| def _extract_template(self, identifier, key_prefix, source_dict):
| try:
check_names = json.loads(source_dict[(key_prefix + CHECK_NAMES)])
init_config_tpls = json.loads(source_dict[(key_prefix + INIT_CONFIGS)])
instance_tpls = json.loads(source_dict[(key_prefix + INSTANCES)])
return [check_names, init_config_tpls, instance_tpls]
except KeyError:
... |
'Retrieve template configs for an identifier from the config_store or auto configuration.'
| def get_check_tpls(self, identifier, **kwargs):
| if (kwargs.get('auto_conf') is True):
kube_annotations = kwargs.get(KUBE_ANNOTATIONS)
kube_container_name = kwargs.get(KUBE_CONTAINER_NAME)
docker_labels = kwargs.get(DOCKER_LABELS)
source = ''
config = None
if kube_annotations:
config = self._get_kube_con... |
'Query templates from the cache. Fallback to canonical identifier for auto-config.'
| def read_config_from_store(self, identifier):
| try:
res = self.template_cache.get_templates(identifier)
if (not res):
log.debug('No template found for {}, trying with auto-config...'.format(identifier))
image_ident = self._get_image_ident(identifier)
res = self.template_cache.get_templates... |
'Extract an identifier from the image'
| def _get_image_ident(self, ident):
| if (not ident):
return ''
if ('@' in ident):
return ident.split('@')[0].split('/')[(-1)]
elif (ident.count(':') > 1):
return ident.split(':')[1].split('/')[(-1)]
else:
return ident.split(':')[0].split('/')[(-1)]
|
'Return whether or not configuration templates have changed since the previous crawl'
| def crawl_config_template(self):
| try:
config_index = self.client_read(self.sd_template_dir.lstrip('/'), recursive=True, watch=True)
except KeyNotFound:
log.debug('No config template found (expected if running on auto-config alone). Not Triggering a config reload.')
return False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.