desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test get_check_tpls'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch.object(AbstractConfigStore, 'client_read', side_effect=client_read) def test_get_check_tpls(self, *args):
valid_config = ['image_0', 'image_1', 'image_2'] invalid_config = ['bad_image_0', 'bad_image_1'] config_store = get_config_store(self.auto_conf_agentConfig) for image in valid_config: tpl = self.mock_raw_templates.get(image)[1] self.assertEquals(tpl, config_store.get_check_tpls(image)) ...
'Test get_check_tpls for kubernetes annotations'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch.object(AbstractConfigStore, 'client_read', side_effect=client_read) def test_get_check_tpls_kube(self, *args):
valid_config = ['image_0', 'image_1', 'image_2', 'image_3', 'image_4'] invalid_config = ['bad_image_0'] config_store = get_config_store(self.auto_conf_agentConfig) for image in (valid_config + invalid_config): tpl = self.mock_raw_templates.get(image)[1] tpl = [(CONFIG_FROM_KUBE, t[1]) fo...
'Test get_check_tpls from docker labesl'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch.object(AbstractConfigStore, 'client_read', side_effect=client_read) def test_get_check_tpls_labels(self, *args):
valid_config = ['image_0', 'image_1', 'image_2', 'image_3', 'image_4'] invalid_config = ['bad_image_0'] config_store = get_config_store(self.auto_conf_agentConfig) for image in (valid_config + invalid_config): tpl = self.mock_raw_templates.get(image)[1] tpl = [(CONFIG_FROM_LABELS, t[1]) ...
'Test get_config_id'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) def test_get_config_id(self, mock_get_auto_confd_path):
with mock.patch('utils.dockerutil.DockerUtil.client', return_value=None): for (c_ins, _, _, _, expected_ident, _) in self.container_inspects: sd_backend = get_sd_backend(agentConfig=self.auto_conf_agentConfig) self.assertEqual(sd_backend.get_config_id(DockerUtil().image_name_extracto...
'Test read_config_from_store'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch.object(_TemplateCache, '_issue_read', side_effect=issue_read) def test_read_config_from_store(self, *args):
valid_idents = [('nginx', 'nginx'), ('nginx:latest', 'nginx:latest'), ('custom-nginx', 'custom-nginx'), ('custom-nginx:latest', 'custom-nginx'), ('repo/custom-nginx:latest', 'custom-nginx'), ('repo/dir:5000/custom-nginx:latest', 'repo/dir:5000/custom-nginx:latest')] invalid_idents = ['foo'] config_store = g...
'Test JMX configs are read and converted to YAML'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch('utils.dockerutil.DockerUtil.client', return_value=None) @mock.patch.object(SDDockerBackend, 'get_configs', return_value=jmx_sd_configs) def test_read_jmx_config_from_store(self, *args):
jmx_configs = generate_jmx_configs(self.auto_conf_agentConfig, 'jmxhost') valid_configs = {'solr_0': "init_config: {}\ninstances:\n- host: localhost\n password: bar\n port: '9999'\n username: foo\n- host: remotehost\n password: bar\n port: '5555'\...
'test _populate_auto_conf'
@mock.patch('utils.service_discovery.abstract_config_store.get_auto_conf_images') def test_populate_auto_conf(self, mock_get_auto_conf_images):
auto_tpls = {'foo': [['check0', 'check1'], [{}, {}], [{}, {}]], 'bar': [['check2', 'check3', 'check3'], [{}, {}, {}], [{}, {'foo': 'bar'}, {'bar': 'foo'}]]} cache = _TemplateCache(issue_read, '') cache.auto_conf_templates = defaultdict((lambda : ([[]] * 3))) mock_get_auto_conf_images.return_value = auto...
'test get_templates'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) @mock.patch.object(_TemplateCache, '_issue_read', return_value=None) def test_get_templates(self, *args):
kv_tpls = {'foo': [['check0', 'check1'], [{}, {}], [{}, {}]], 'bar': [['check2', 'check3'], [{}, {}], [{}, {}]]} auto_tpls = {'foo': [['check3', 'check5'], [{}, {}], [{}, {}]], 'bar': [['check2', 'check6'], [{}, {}], [{}, {}]], 'foobar': [['check4'], [{}], [{}]]} cache = _TemplateCache(issue_read, '') c...
'Test get_check_names'
@mock.patch('config.get_auto_confd_path', return_value=os.path.join(os.path.dirname(__file__), 'fixtures/auto_conf/')) def test_get_check_names(self, mock_get_auto_confd_path):
kv_tpls = {'foo': [['check0', 'check1'], [{}, {}], [{}, {}]], 'bar': [['check2', 'check3'], [{}, {}], [{}, {}]]} auto_tpls = {'foo': [['check4', 'check5'], [{}, {}], [{}, {}]], 'bar': [['check2', 'check6'], [{}, {}], [{}, {}]], 'foobar': None} cache = _TemplateCache(issue_read, '') cache.kv_templates = ...
'Test pickle file location on win32'
@mock.patch('os.path.isdir', return_value=True) @mock.patch('checks.check_status._windows_commondata_path', return_value='C:\\Windows\\App Data') @mock.patch('utils.platform.Platform.is_win32', return_value=True) def test_agent_status_pickle_file_win32(self, *mocks):
expected_path = os.path.join('C:\\Windows\\App Data', 'Datadog', 'AgentStatus.pickle') self.assertEqual(AgentStatus._get_pickle_path(), expected_path)
'Test pickle file location when running a Mac DMG install'
@mock.patch('utils.pidfile.PidFile.get_dir', return_value=_mac_run_dir) @mock.patch('utils.platform.Platform.is_win32', return_value=False) @mock.patch('utils.platform.Platform.is_mac', return_value=True) def test_agent_status_pickle_file_mac_dmg(self, *mocks):
expected_path = os.path.join(self._mac_run_dir, 'AgentStatus.pickle') self.assertEqual(AgentStatus._get_pickle_path(), expected_path)
'Test pickle file location when running a Mac source install'
@mock.patch('utils.pidfile.tempfile.gettempdir', return_value='/a/test/tmp/dir') @mock.patch('utils.pidfile.PidFile.get_dir', return_value='') @mock.patch('utils.platform.Platform.is_win32', return_value=False) @mock.patch('utils.platform.Platform.is_mac', return_value=True) def test_agent_status_pickle_file_mac_source...
expected_path = os.path.join('/a/test/tmp/dir', 'AgentStatus.pickle') self.assertEqual(AgentStatus._get_pickle_path(), expected_path)
'Test pickle file location when running on Linux'
@mock.patch('os.path.isdir', return_value=True) @mock.patch('utils.pidfile.PidFile.get_dir', return_value=_linux_run_dir) @mock.patch('utils.platform.Platform.is_win32', return_value=False) @mock.patch('utils.platform.Platform.is_mac', return_value=False) def test_agent_status_pickle_file_linux(self, *mocks):
expected_path = os.path.join('/opt/datadog-agent/run', 'AgentStatus.pickle') self.assertEqual(AgentStatus._get_pickle_path(), expected_path)
'Runs the passed func twice and checks that the number of handles held by the process hasn\'t increased between the first and the second run'
def _checkHandleLeak(self, func, *args, **kwargs):
proc = psutil.Process() func(*args, **kwargs) middle = proc.num_handles() func(*args, **kwargs) end = proc.num_handles() self.assertEquals((end - middle), 0)
'Loop on `self.check.method` until `self.check.attribute >= count`. Raise after'
def wait_for_async(self, method, attribute, count, results_timeout):
initial_values = getattr(self, attribute) i = 0 while (i < results_timeout): self.check._process_results() if ((len(getattr(self.check, attribute)) + len(initial_values)) >= count): return (getattr(self.check, method)() + initial_values) time.sleep(1.1) i += 1 ...
'Retrieve a class with the given name among the check module.'
def load_class(self, name):
return load_class(self.CHECK_NAME, name)
'Get disk space/inode stats'
def check(self, instance):
if self._psutil(): if Platform.is_linux(): procfs_path = self.agentConfig.get('procfs_path', '/proc').rstrip('/') psutil.PROCFS_PATH = procfs_path self.collect_metrics_psutil() else: self.collect_metrics_manually()
'Return True for disks we don\'t want or that match regex in the config file'
def _exclude_disk(self, name, filesystem, mountpoint):
name_empty = ((not name) or (name == 'none')) if (name_empty and (not self._all_partitions)): return True elif ((not name_empty) and (name in self._excluded_disks)): return True elif ((not name_empty) and self._excluded_disk_re.match(name)): return True elif self._excluded_mo...
'Given raw output for the df command, transform it into a normalized list devices. A \'device\' is a list with fields corresponding to the output of df output on each platform.'
def _list_devices(self, df_output):
all_devices = [l.strip().split() for l in df_output.splitlines()] raw_devices = [l for l in all_devices[1:] if l] flattened_devices = self._flatten_devices(raw_devices) return [d for d in flattened_devices if self._keep_device(d)]
'Run the server.'
def start(self):
ipv4_only = False try: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) self.socket.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0) if (self.so_rcvbuf is not None): self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, int(self.so_rcvbuf)) except Exception: ...
'Handles SIGTERM and SIGINT, which gracefully stops the agent.'
def _handle_sigterm(self, signum, frame):
log.debug('Caught sigterm. Stopping run loop.') self.run_forever = False if self.collector: self.collector.stop() log.debug('Collector is stopped.')
'Handles SIGUSR1, which signals an exit with an autorestart.'
def _handle_sigusr1(self, signum, frame):
self._handle_sigterm(signum, frame) self._do_restart()
'Handles SIGHUP, which signals a configuration reload.'
def _handle_sighup(self, signum, frame):
log.info('SIGHUP caught! Scheduling configuration reload before next collection run.') self.reload_configs_flag = True
'Reload the agent configuration and checksd configurations. Can also reload only an explicit set of checks.'
def reload_configs(self, checks_to_reload=set()):
log.info('Attempting a configuration reload...') hostname = get_hostname(self._agentConfig) jmx_sd_configs = None if (not checks_to_reload): log.debug('No check list was passed, reloading every check') for check in self._checksd.get('initialized_checks', [])...
'take a set of checks and for each of them: - remove it from the init_failed_checks if it was there - load a fresh config for it - replace its old config with the new one in initialized_checks if there was one - disable the check if no new config was found - otherwise, append it to initialized_checks'
def refresh_specific_checks(self, hostname, checksd, checks):
for check_name in checks: idx = None for (num, check) in enumerate(checksd['initialized_checks']): if (check.name == check_name): idx = num check.stop() if ((not idx) and (check_name in checksd['init_failed_checks'])): checksd['init_fai...
'Main loop of the collector'
def run(self, config=None):
signal.signal(signal.SIGTERM, self._handle_sigterm) if (not Platform.is_windows()): signal.signal(signal.SIGUSR1, self._handle_sigusr1) signal.signal(signal.SIGINT, self._handle_sigterm) signal.signal(signal.SIGHUP, self._handle_sighup) else: sdk_integrations = get_sdk_integr...
'Safely remove transaction from list'
def _remove(self, tr):
try: self._transactions.remove(tr) except ValueError: log.warn('Tried to remove transaction %s from queue but it was not in the queue anymore.', tr.get_id()) else: self._total_count -= 1 self._total_size -= tr.get_size()
'Add a point to the given metric.'
def sample(self, value, sample_rate, timestamp=None):
raise NotImplementedError()
'Flush all metrics up to the given timestamp.'
def flush(self, timestamp, interval):
raise NotImplementedError()
'Schema of a dogstatsd packet: <name>:<value>|<metric_type>|@<sample_rate>|#<tag1_name>:<tag1_value>,<tag2_name>:<tag2_value>:<value>|<metric_type>...'
def parse_metric_packet(self, packet):
parsed_packets = [] name_and_metadata = packet.split(':', 1) if (len(name_and_metadata) != 2): raise Exception((u'Unparseable metric packet: %s' % packet)) name = name_and_metadata[0] broken_split = name_and_metadata[1].split(':') data = [] partial_datum = None for token...
'Magic tags (host, device) override metric hostname and device_name attributes'
def _extract_magic_tags(self, tags):
hostname = None device_name = None if tags: tags_to_remove = [] for tag in tags: if tag.startswith('host:'): hostname = tag[5:] tags_to_remove.append(tag) elif tag.startswith('device:'): device_name = tag[7:] ...
'Add a metric to be aggregated'
def submit_metric(self, name, value, mtype, tags=None, hostname=None, device_name=None, timestamp=None, sample_rate=1):
raise NotImplementedError()
'Flush aggregated metrics'
def flush(self):
raise NotImplementedError()
'Read the message and forward it to the intake'
def post(self):
msg = self.request.body headers = self.request.headers msg_type = self._MSG_TYPE if (msg is not None): tr = MetricTransaction(msg, headers, msg_type) else: raise tornado.web.HTTPError(500) self.write(('Transaction: %s' % tr.get_id()))
'Read the message and forward it to the intake'
def post(self):
msg = self.request.body headers = self.request.headers if (msg is not None): APIMetricTransaction(msg, headers) else: raise tornado.web.HTTPError(500)
'Override the tornado logging method. If everything goes well, log level is DEBUG. Otherwise it\'s WARNING or ERROR depending on the response code.'
def log_request(self, handler):
if (handler.get_status() < 400): log_method = log.debug elif (handler.get_status() < 500): log_method = log.warning else: log_method = log.error request_time = (1000.0 * handler.request.request_time()) log_method(u'%d %s %.2fms', handler.get_status(), handler._request_s...
'Graphite does not impose a particular metric structure. So this is where you can insert logic to extract various bits out of the graphite metric name. For instance, if the hostname is in 4th position, you could use: host = components[3]'
def _parseMetric(self, metric):
try: components = metric.split('.') host = self.hostname metric = metric device = 'N/A' return (metric, host, device) except Exception: log.exception(('Unparsable metric: %s' % metric)) return (None, None, None)
'Parse the metric name to fetch (host, metric, device) and send the datapoint to datadog'
def _processMetric(self, metric, datapoint):
log.debug(('New metric: %s, values: %s' % (metric, datapoint))) (metric, host, device) = self._parseMetric(metric) if (metric is not None): self._postMetric(metric, host, device, datapoint) log.info(('Posted metric: %s, host: %s, device: %s' % (metric, host, dev...
'Turn a metric into a well-formed metric name prefix.b.c'
def normalize(self, metric, prefix=None):
name = re.sub('[,\\+\\*\\-/()\\[\\]{}\\s]', '_', metric) name = re.sub('__+', '_', name) name = re.sub('^_', '', name) name = re.sub('_$', '', name) name = re.sub('\\._', '.', name) name = re.sub('_\\.', '.', name) if (prefix is not None): return ((prefix + '.') + name) else: ...
'Treats the metric as a counter, i.e. computes its per second derivative ACHTUNG: Resets previous values associated with this metric.'
def counter(self, metric):
self._counters[metric] = True self._sample_store[metric] = {}
'Is this metric a counter?'
def is_counter(self, metric):
return (metric in self._counters)
'Treats the metric as a gauge, i.e. keep the data as is ACHTUNG: Resets previous values associated with this metric.'
def gauge(self, metric):
self._sample_store[metric] = {}
'Get all metric names'
def get_metric_names(self):
return self._sample_store.keys()
'Save a gauge value.'
def save_gauge(self, metric, value, timestamp=None, tags=None, hostname=None, device_name=None):
if (not self.is_gauge(metric)): self.gauge(metric) self.save_sample(metric, value, timestamp, tags, hostname, device_name)
'Save a simple sample, evict old values if needed'
def save_sample(self, metric, value, timestamp=None, tags=None, hostname=None, device_name=None):
from util import cast_metric_val if (timestamp is None): timestamp = time.time() if (metric not in self._sample_store): raise CheckException(('Saving a sample for an undefined metric: %s' % metric)) try: value = cast_metric_val(value) except ValueError as...
'Simple rate'
@classmethod def _rate(cls, sample1, sample2):
try: interval = (sample2[0] - sample1[0]) if (interval == 0): raise Infinity() delta = (sample2[1] - sample1[1]) if (delta < 0): raise UnknownValue() return (sample2[0], (delta / interval), sample2[2], sample2[3]) except Infinity: raise ...
'Get (timestamp-epoch-style, value)'
def get_sample_with_timestamp(self, metric, tags=None, device_name=None, expire=True):
if ((tags is not None) and isinstance(tags, ListType)): tags.sort() tags = tuple(tags) key = (tags, device_name) if (metric not in self._sample_store): raise UnknownValue() elif (self.is_counter(metric) and (len(self._sample_store[metric][key]) < 2)): raise UnknownValue()...
'Return the last value for that metric'
def get_sample(self, metric, tags=None, device_name=None, expire=True):
x = self.get_sample_with_timestamp(metric, tags, device_name, expire) assert (isinstance(x, TupleType) and (len(x) == 4)), x return x[1]
'Return all values {metric: (ts, value)} for non-tagged metrics'
def get_samples_with_timestamps(self, expire=True):
values = {} for m in self._sample_store: try: values[m] = self.get_sample_with_timestamp(m, expire=expire) except Exception: pass return values
'Return all values {metric: value} for non-tagged metrics'
def get_samples(self, expire=True):
values = {} for m in self._sample_store: try: values[m] = self.get_sample_with_timestamp(m, expire=expire)[1] except Exception: pass return values
'Get all metrics, including the ones that are tagged. This is the preferred method to retrieve metrics @return the list of samples @rtype [(metric_name, timestamp, value, {"tags": ["tag1", "tag2"]}), ...]'
def get_metrics(self, expire=True):
metrics = [] for m in self._sample_store: try: for key in self._sample_store[m]: (tags, device_name) = key try: (ts, val, hostname, device_name) = self.get_sample_with_timestamp(m, tags, device_name, expire) except UnknownVa...
'Initialize a new check. :param name: The name of the check :param init_config: The config for initializing the check :param agentConfig: The global configuration for the agent :param instances: A list of configuration objects for each instance.'
def __init__(self, name, init_config, agentConfig, instances=None):
from aggregator import MetricsAggregator self._enabled_checks.append(name) self._enabled_checks = list(set(self._enabled_checks)) self.name = name self.init_config = (init_config or {}) self.agentConfig = agentConfig self.in_developer_mode = (agentConfig.get('developer_mode') and psutil) ...
'Return the number of instances that are configured for this check.'
def instance_count(self):
return len(self.instances)
'Record the value of a gauge, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value of the gauge :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (opt...
def gauge(self, metric, value, tags=None, hostname=None, device_name=None, timestamp=None):
self.aggregator.gauge(metric, value, tags, hostname, device_name, timestamp)
'Increment a counter with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to increment by :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional)...
def increment(self, metric, value=1, tags=None, hostname=None, device_name=None):
self.aggregator.increment(metric, value, tags, hostname, device_name)
'Increment a counter with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to decrement by :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional)...
def decrement(self, metric, value=(-1), tags=None, hostname=None, device_name=None):
self.aggregator.decrement(metric, value, tags, hostname, device_name)
'Submit a raw count with optional tags, hostname and device name :param metric: The name of the metric :param value: The value :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The device name f...
def count(self, metric, value=0, tags=None, hostname=None, device_name=None):
self.aggregator.submit_count(metric, value, tags, hostname, device_name)
'Submits a raw count with optional tags, hostname and device name based on increasing counter values. E.g. 1, 3, 5, 7 will submit 6 on flush. Note that reset counters are skipped. :param metric: The name of the metric :param value: The value of the rate :param tags: (optional) A list of tags for this metric :param host...
def monotonic_count(self, metric, value=0, tags=None, hostname=None, device_name=None):
self.aggregator.count_from_counter(metric, value, tags, hostname, device_name)
'Submit a point for a metric that will be calculated as a rate on flush. Values will persist across each call to `check` if there is not enough point to generate a rate on the flush. :param metric: The name of the metric :param value: The value of the rate :param tags: (optional) A list of tags for this metric :param h...
def rate(self, metric, value, tags=None, hostname=None, device_name=None):
self.aggregator.rate(metric, value, tags, hostname, device_name)
'Sample a histogram value, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value to sample for the histogram :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param devic...
def histogram(self, metric, value, tags=None, hostname=None, device_name=None):
self.aggregator.histogram(metric, value, tags, hostname, device_name)
'Function to create a histogram metric for "rate" like metrics. Warning this doesn\'t use the harmonic mean, beware of what it means when using it. :param metric: The name of the metric :param value: The value to sample for the histogram :param excluding_tags: A list of tags that will be removed when computing the hist...
def historate(self, metric, value, excluding_tags, tags=None, hostname=None, device_name=None):
tags = list(tags) context = [metric] if (tags is not None): context.append('-'.join(sorted(tags))) if (hostname is not None): context.append(('host:' + hostname)) if (device_name is not None): context.append(('device:' + device_name)) now = time.time() context = tuple...
'Sample a set value, with optional tags, hostname and device name. :param metric: The name of the metric :param value: The value for the set :param tags: (optional) A list of tags for this metric :param hostname: (optional) A hostname for this metric. Defaults to the current hostname. :param device_name: (optional) The...
def set(self, metric, value, tags=None, hostname=None, device_name=None):
self.warning(('Deprecation notice: the `set` method of `AgentCheck` is deprecated and will be removed ' + 'in the next major version of the Agent, please compute aggregates in your check and use `gauge` instead')) self.agg...
'Save an event. :param event: The event payload as a dictionary. Has the following structure: "timestamp": int, the epoch timestamp for the event, "event_type": string, the event time name, "msg_title": string, the title of the event, "msg_text": string, the text body of the event, "alert_type": (optional) string, one ...
def event(self, event):
self.events.append(event)
'Save a service check. :param check_name: string, name of the service check :param status: int, describing the status. 0 for success, 1 for warning, 2 for failure :param tags: (optional) list of strings, a list of tags for this run :param timestamp: (optional) float, unix timestamp for when the run occurred :param host...
def service_check(self, check_name, status, tags=None, timestamp=None, hostname=None, check_run_id=None, message=None):
if (hostname is None): hostname = self.hostname if (message is not None): message = unicode(message) self.service_checks.append(create_service_check(check_name, status, tags, timestamp, hostname, check_run_id, message))
'Save metadata. :param meta_name: metadata key name :type meta_name: string :param value: metadata value :type value: string'
def service_metadata(self, meta_name, value):
self._instance_metadata.append((meta_name, unicode(value)))
'Check whether the check has saved any events @return whether or not the check has saved any events @rtype boolean'
def has_events(self):
return (len(self.events) > 0)
'Get all metrics, including the ones that are tagged. @return the list of samples @rtype [(metric_name, timestamp, value, {"tags": ["tag1", "tag2"]}), ...]'
def get_metrics(self):
return self.aggregator.flush()
'Return a list of the events saved by the check, if any @return the list of events saved by this check @rtype list of event dictionaries'
def get_events(self):
events = self.events self.events = [] return events
'Return a list of the service checks saved by the check, if any and clears them out of the instance\'s service_checks list @return the list of service checks saved by this check @rtype list of service check dicts'
def get_service_checks(self):
service_checks = self.service_checks self.service_checks = [] return service_checks
'Concatenate and flush instance metadata.'
def _roll_up_instance_metadata(self):
self.svc_metadata.append(dict(((k, v) for (k, v) in self._instance_metadata))) self._instance_metadata = []
'Return a list of the metadata dictionaries saved by the check -if any- and clears them out of the instance\'s service_checks list @return the list of metadata saved by this check @rtype list of metadata dicts'
def get_service_metadata(self):
if self._instance_metadata: self._roll_up_instance_metadata() service_metadata = self.svc_metadata self.svc_metadata = [] return service_metadata
'Check whether the instance run created any warnings'
def has_warnings(self):
return (len(self.warnings) > 0)
'Add a warning message that will be printed in the info page :param warning_message: String. Warning message to be displayed'
def warning(self, warning_message):
warning_message = str(warning_message) self.log.warning(warning_message) self.warnings.append(warning_message)
'Should return a string that shows which version of the needed libraries are used'
def get_library_versions(self):
raise NotImplementedError
'Return the list of warnings messages to be displayed in the info page'
def get_warnings(self):
warnings = self.warnings self.warnings = [] return warnings
'If in developer mode, return a dictionary of statistics about the check run'
def _get_internal_profiling_stats(self):
stats = None if self.allow_profiling: stats = self._internal_profiling_stats self._internal_profiling_stats = None return stats
'Run all instances.'
def run(self):
(before, after) = (None, None) if (self.in_developer_mode and (self.name != AGENT_METRICS_CHECK_NAME)): try: before = AgentCheck._collect_internal_stats() except Exception: self.log.debug('Failed to collect Agent Stats before check {0}'.format(self.na...
'Overriden by the check class. This will be called to run the check. :param instance: A dict with the instance information. This will vary depending on your config structure.'
def check(self, instance):
raise NotImplementedError()
'To be executed when the agent is being stopped to clean ressources'
def stop(self):
pass
'A method used for testing your check without running the agent.'
@classmethod def from_yaml(cls, path_to_yaml=None, agentConfig=None, yaml_text=None, check_name=None):
if path_to_yaml: check_name = os.path.basename(path_to_yaml).split('.')[0] try: f = open(path_to_yaml) except IOError: raise Exception(('Unable to open yaml config: %s' % path_to_yaml)) yaml_text = f.read() f.close() config = yaml.lo...
'Turn a metric into a well-formed metric name prefix.b.c :param metric The metric name to normalize :param prefix A prefix to to add to the normalized name, default None :param fix_case A boolean, indicating whether to make sure that the metric name returned is in underscore_case'
def normalize(self, metric, prefix=None, fix_case=False):
if isinstance(metric, unicode): metric_name = unicodedata.normalize('NFKD', metric).encode('ascii', 'ignore') else: metric_name = metric if fix_case: name = self.convert_to_underscore_separated(metric_name) if (prefix is not None): prefix = self.convert_to_undersc...
'Convert from CamelCase to camel_case And substitute illegal metric characters'
def convert_to_underscore_separated(self, name):
metric_name = self.FIRST_CAP_RE.sub('\\1_\\2', name) metric_name = self.ALL_CAP_RE.sub('\\1_\\2', metric_name).lower() metric_name = self.METRIC_REPLACEMENT.sub('_', metric_name) return self.DOT_UNDERSCORE_CLEANUP.sub('.', metric_name).strip('_')
'stylize the text.'
@classmethod def stylize(cls, text, *styles):
if (not cls.ENABLED): return text fmt = '\x1b[%dm%s' for style in (styles or []): text = (fmt % (cls.STYLES[style], text)) return (text + (fmt % (0, '')))
'Support `Enum` style `contains`.'
def __contains__(cls, provider):
return (provider in cls._AVAILABLE_PROVIDER_ARCHITECTURES)
'Return the WMI provider.'
@property def provider(self):
return self._provider
'Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`'
@provider.setter def provider(self, value):
result = None defaulted_value = (value or ProviderArchitecture.DEFAULT) try: parsed_value = int(defaulted_value) except ValueError: pass else: if (parsed_value in ProviderArchitecture): result = parsed_value if (result is None): self.logger.error(u"Inv...
'A property to retrieve the sampler connection information.'
@property def connection(self):
return {'host': self.host, 'namespace': self.namespace, 'username': self.username, 'password': self.password}
'Return an index key used to cache the sampler connection.'
@property def connection_key(self):
return '{host}:{namespace}:{username}'.format(host=self.host, namespace=self.namespace, username=self.username)
'Cache and return filters as a comprehensive WQL clause.'
@property def formatted_filters(self):
if (not self._formatted_filters): filters = deepcopy(self.filters) self._formatted_filters = self._format_filter(filters, self._and_props) return self._formatted_filters
'Compute new samples.'
def sample(self):
self._sampling = True try: if (self.is_raw_perf_class and (not self._previous_sample)): self._current_sample = self._query() self._previous_sample = self._current_sample self._current_sample = self._query() except TimeoutException: self.logger.debug(u'Query tim...
'Return the number of WMI Objects in the current sample.'
def __len__(self):
if self._sampling: raise TypeError(u'Sampling `WMISampler` object has no len()') return len(self._current_sample)
'Iterate on the current sample\'s WMI Objects and format the property values.'
def __iter__(self):
if self._sampling: raise TypeError(u'Sampling `WMISampler` object is not iterable') if self.is_raw_perf_class: for (previous_wmi_object, current_wmi_object) in izip(self._previous_sample, self._current_sample): formatted_wmi_object = self._format_property_values(previo...
'Get the specified formatted WMI Object from the current sample.'
def __getitem__(self, index):
if self.is_raw_perf_class: previous_wmi_object = self._previous_sample[index] current_wmi_object = self._current_sample[index] formatted_wmi_object = self._format_property_values(previous_wmi_object, current_wmi_object) return formatted_wmi_object else: return self._curre...
'Equality operator is based on the current sample.'
def __eq__(self, other):
return (self._current_sample == other)
'Stringify the current sample\'s WMI Objects.'
def __str__(self):
return str(self._current_sample)
'Return the calculator for the given `counter_type`. Fallback with `get_raw`.'
def _get_property_calculator(self, counter_type):
calculator = get_raw try: calculator = get_calculator(counter_type) except UndefinedCalculator: self.logger.warning(u'Undefined WMI calculator for counter_type {counter_type}. Values are reported as RAW.'.format(counter_type=counter_type)) return calculator
'Format WMI Object\'s RAW data based on the previous sample. Do not override the original WMI Object !'
def _format_property_values(self, previous, current):
formatted_wmi_object = CaseInsensitiveDict() for (property_name, property_raw_value) in current.iteritems(): counter_type = self._property_counter_types.get(property_name) property_formatted_value = property_raw_value if counter_type: calculator = self._get_property_calculato...
'Create a new WMI connection'
def get_connection(self):
self.logger.debug(u'Connecting to WMI server (host={host}, namespace={namespace}, provider={provider}, username={username}).'.format(host=self.host, namespace=self.namespace, provider=self.provider, username=self.username)) additional_args = [] pythoncom.CoInitialize() if (self.prov...
'Transform filters to a comprehensive WQL `WHERE` clause. Builds filter from a filter list. - filters: expects a list of dicts, typically: - [{\'Property\': value},...] or - [{\'Property\': (comparison_op, value)},...] NOTE: If we just provide a value we defailt to \'=\' comparison operator. Otherwise, specify the oper...
@staticmethod def _format_filter(filters, and_props=[]):
def build_where_clause(fltr): f = fltr.pop() wql = '' while f: (prop, value) = f.popitem() if isinstance(value, tuple): oper = value[0] value = value[1] elif (isinstance(value, basestring) and ('%' in value)): ...
'Query WMI using WMI Query Language (WQL) & parse the results. Returns: List of WMI objects or `TimeoutException`.'
def _query(self):
formated_property_names = ','.join(self.property_names) wql = 'Select {property_names} from {class_name}{filters}'.format(property_names=formated_property_names, class_name=self.class_name, filters=self.formatted_filters) self.logger.debug(u'Querying WMI: {0}'.format(wql)) try: fl...