def test_activate(self):
        check = AgentCheck('test', {}, [{}])

        context = check.get_tls_context()
        assert context == check._tls_context_wrapper.tls_context
        assert isinstance(context, SSLContext)
    def test_fix_case(self):
        check = AgentCheck()
        metric_name = u'Klüft inför på fédéral'
        normalized_metric_name = 'kluft_infor_pa_federal'

        assert check.normalize(metric_name, fix_case=True) == normalized_metric_name
    def test_underscores_at_ends(self):
        check = AgentCheck()
        metric_name = u'_some_underscores_'
        normalized_metric_name = 'some_underscores'

        assert check.normalize(metric_name) == normalized_metric_name
def test_check_version():
    check = AgentCheck()

    assert check.check_version == base_package_version
def test_log_critical_error():
    check = AgentCheck()

    with pytest.raises(NotImplementedError):
        check.log.critical('test')
 def __init__(self, *args, **kwargs):
     AgentCheck.__init__(self, *args, **kwargs)
     self.instance_cache = {}
 def test_non_float_metric(self, aggregator):
     check = AgentCheck()
     metric_name = 'test_metric'
     with pytest.raises(ValueError):
         check.gauge(metric_name, '85k')
     aggregator.assert_metric(metric_name, count=0)
    def test_default(self):
        check = AgentCheck('test', {}, [{}])

        assert check._metadata_manager is None
    def test_no_check_id_error(self):
        check = AgentCheck('test', {}, [{}])

        with mock.patch('datadog_checks.base.checks.base.using_stub_aggregator', False):
            with pytest.raises(RuntimeError):
                check.set_metadata('foo', 'bar')
Exemple #10
0
 def __init__(self, name, init_config, agentConfig, instances=None):
     AgentCheck.__init__(self, name, init_config, agentConfig, instances=instances)
     if instances is not None and len(instances) > 1:
         raise Exception("BTRFS check only supports one configured instance.")
Exemple #11
0
    def __init__(self, name, init_config, agentConfig, instances=None):
        AgentCheck.__init__(self, name, init_config, agentConfig, instances)
        self.nagios_tails = {}
        check_freq = init_config.get("check_freq", 15)

        if instances is not None:
            for instance in instances:
                tailers = []
                nagios_conf = {}
                instance_key = None
                custom_tag = instance.get('tags', [])

                if 'nagios_conf' in instance:  # conf.d check
                    conf_path = instance['nagios_conf']
                    nagios_conf = self.parse_nagios_config(conf_path)
                    instance_key = conf_path
                # Retrocompatibility Code
                elif 'nagios_perf_cfg' in instance:
                    conf_path = instance['nagios_perf_cfg']
                    nagios_conf = self.parse_nagios_config(conf_path)
                    instance["collect_host_performance_data"] = True
                    instance["collect_service_performance_data"] = True
                    instance_key = conf_path
                if 'nagios_log' in instance:
                    nagios_conf["log_file"] = instance['nagios_log']
                    if instance_key is None:
                        instance_key = instance['nagios_log']
                # End of retrocompatibility code
                if not nagios_conf:
                    self.log.warning("Missing path to nagios_conf")
                    continue

                if 'log_file' in nagios_conf and instance.get('collect_events', True):
                    self.log.debug("Starting to tail the event log")
                    tailers.append(
                        NagiosEventLogTailer(
                            log_path=nagios_conf['log_file'],
                            file_template=None,
                            logger=self.log,
                            hostname=self.hostname,
                            tags=custom_tag,
                            event_func=self.event,
                            gauge_func=self.gauge,
                            freq=check_freq,
                            passive_checks=instance.get('passive_checks_events', False),
                        )
                    )
                if (
                    'host_perfdata_file' in nagios_conf
                    and 'host_perfdata_file_template' in nagios_conf
                    and instance.get('collect_host_performance_data', False)
                ):
                    self.log.debug("Starting to tail the host_perfdata file")
                    tailers.append(
                        NagiosHostPerfDataTailer(
                            log_path=nagios_conf['host_perfdata_file'],
                            file_template=nagios_conf['host_perfdata_file_template'],
                            logger=self.log,
                            hostname=self.hostname,
                            event_func=self.event,
                            gauge_func=self.gauge,
                            freq=check_freq,
                            tags=custom_tag,
                        )
                    )
                if (
                    'service_perfdata_file' in nagios_conf
                    and 'service_perfdata_file_template' in nagios_conf
                    and instance.get('collect_service_performance_data', False)
                ):
                    self.log.debug("Starting to tail the service_perfdata file")
                    tailers.append(
                        NagiosServicePerfDataTailer(
                            log_path=nagios_conf['service_perfdata_file'],
                            file_template=nagios_conf['service_perfdata_file_template'],
                            logger=self.log,
                            hostname=self.hostname,
                            event_func=self.event,
                            gauge_func=self.gauge,
                            freq=check_freq,
                            tags=custom_tag,
                        )
                    )

                self.nagios_tails[instance_key] = tailers
Exemple #12
0
 def __init__(self, name, init_config, agentConfig, instances=None):
     AgentCheck.__init__(self, name, init_config, agentConfig, instances)
     # Host status needs to persist across all checks
     self.cluster_status = {}
    def test__build_similar_elements__histogram_buckets(self, aggregator):
        check = AgentCheck()

        check.submit_histogram_bucket('histogram.bucket3', 1, 0.0, 10.0, True, "hostname", ["tag2"])
        check.submit_histogram_bucket('histogram.bucket2', 1, 125.0, 312.0, True, "hostname", ["tag1"])
        check.submit_histogram_bucket('histogram.bucket1', 1, 0.0, 10.0, True, "hostname", ["tag1"])
        check.submit_histogram_bucket('histogram.bucket4', 1, 125.0, 312.0, True, "hostname2", ["tag1"])
        check.submit_histogram_bucket('histogram.bucket5', 1, 125.0, 312.0, True, "hostname2", ["tag2"])
        check.submit_histogram_bucket('histogram.bucket0', 2, 125.0, 312.0, False, "hostname2", ["tag2"])

        expected_histogram_bucket = HistogramBucketStub('histogram.bucket', 1, 0.0, 10.0, True, "hostname", ["tag1"])
        similar_histogram_bucket = similar._build_similar_elements(
            expected_histogram_bucket, aggregator._histogram_buckets
        )

        # expect buckets in closest similarity order
        assert similar_histogram_bucket[0][1].name == 'histogram.bucket1'  # exact match (except name)
        assert similar_histogram_bucket[1][1].name == 'histogram.bucket3'  # value/upper/lower/monotonic/host match
        assert similar_histogram_bucket[2][1].name == 'histogram.bucket2'  # value/monotonic/host/tag match
        assert similar_histogram_bucket[3][1].name == 'histogram.bucket4'  # value/monotonic/tag match
        assert similar_histogram_bucket[4][1].name == 'histogram.bucket5'  # value/monotonic match
        assert similar_histogram_bucket[5][1].name == 'histogram.bucket0'  # no match
    def test_refresh(self):
        check = AgentCheck('test', {}, [{}])

        context = check.get_tls_context()
        assert context == check.get_tls_context()
        assert context != check.get_tls_context(refresh=True)
Exemple #15
0
    def __init__(self, name, init_config, agentConfig, instances=None):
        AgentCheck.__init__(self, name, init_config, agentConfig, instances)

        self._instance_states = defaultdict(lambda: ConsulCheckInstanceState())
Exemple #16
0
    def test_default(self):
        check = AgentCheck('test', {}, [{}])

        assert check._http is None
Exemple #17
0
 def __init__(self, name, init_config, agentConfig, instances=None):
     AgentCheck.__init__(self, name, init_config, agentConfig, instances)
     self.already_alerted = []
     self.cached_vhosts = {}  # this is used to send CRITICAL rabbitmq.aliveness check if the server goes down
Exemple #18
0
    def test_activate(self):
        check = AgentCheck('test', {}, [{}])

        assert check.http == check._http
        assert isinstance(check.http, RequestsWrapper)
    def test_underscores_and_dots(self):
        check = AgentCheck()
        metric_name = u'some_.dots._and_._underscores'
        normalized_metric_name = 'some.dots.and.underscores'

        assert check.normalize(metric_name) == normalized_metric_name
 def __init__(self, name, init_config, agentConfig, instances=None):
     AgentCheck.__init__(self, name, init_config, agentConfig, instances)
     self.connections = {}
     self.last_timestamp_seen = defaultdict(int)
    def test_namespace_override(self, aggregator):
        check = AgentCheck()
        check.__NAMESPACE__ = 'test'

        check.service_check('service_check', AgentCheck.OK, raw=True)
        aggregator.assert_service_check('service_check', status=AgentCheck.OK)
    with pytest.raises(TypeError):
        check.warning("not enough arguments: %s %s", "a")

    with pytest.raises(TypeError):
        check.warning("too many arguments: %s %s", "a", "b", "c")

    assert ["should not raise error: %s"] == check.warnings


@pytest.mark.parametrize(
    'case_name, check, expected_attributes',
    [
        (
            'agent 5 signature: only args',
            AgentCheck('check_name', {'init_conf1': 'init_value1'},
                       {'agent_conf1': 'agent_value1'}, [{
                           'foo': 'bar'
                       }]),
            {
                'name': 'check_name',
                'init_config': {
                    'init_conf1': 'init_value1'
                },
                'agentConfig': {
                    'agent_conf1': 'agent_value1'
                },
                'instance': {
                    'foo': 'bar'
                },
            },
        ),
        (
def test_load_config():
    assert AgentCheck.load_config("raw_foo: bar") == {'raw_foo': 'bar'}
    def test_invalid_chars_and_underscore(self):
        check = AgentCheck()
        metric_name = u'metric.hello++aaa$$_bbb'
        normalized_metric_name = 'metric.hello_aaa_bbb'

        assert check.normalize(metric_name) == normalized_metric_name
    def test_default(self):
        check = AgentCheck()
        metric_name = u'Klüft inför på fédéral'
        normalized_metric_name = 'Kluft_infor_pa_federal'

        assert check.normalize(metric_name) == normalized_metric_name
    def test_default(self):
        check = AgentCheck('test', {}, [{}])

        assert not hasattr(check, '_metadata_manager')
    def test_underscores_redundant(self):
        check = AgentCheck()
        metric_name = u'a_few__redundant___underscores'
        normalized_metric_name = 'a_few_redundant_underscores'

        assert check.normalize(metric_name) == normalized_metric_name
Exemple #28
0
    def __init__(self, name, init_config, instances):
        AgentCheck.__init__(self, name, init_config, instances)
        self.nagios_tails = {}

        instance = self.instances[0]
        tailers = []
        nagios_conf = {}
        instance_key = None
        custom_tag = instance.get('tags', [])

        if 'nagios_conf' in instance:  # conf.d check
            conf_path = instance['nagios_conf']
            nagios_conf = self.parse_nagios_config(conf_path)
            instance_key = conf_path
        # Retrocompatibility Code
        elif 'nagios_perf_cfg' in instance:
            conf_path = instance['nagios_perf_cfg']
            nagios_conf = self.parse_nagios_config(conf_path)
            instance["collect_host_performance_data"] = True
            instance["collect_service_performance_data"] = True
            instance_key = conf_path
        if 'nagios_log' in instance:
            nagios_conf["log_file"] = instance['nagios_log']
            if instance_key is None:
                instance_key = instance['nagios_log']
        # End of retrocompatibility code
        if not nagios_conf:
            self.log.warning("Missing path to nagios_conf")
            return

        if 'log_file' in nagios_conf and instance.get('collect_events', True):
            self.log.debug("Starting to tail the event log")
            tailers.append(
                NagiosEventLogTailer(
                    log_path=nagios_conf['log_file'],
                    logger=self.log,
                    hostname=self.hostname,
                    event_func=self.event,
                    tags=custom_tag,
                    passive_checks=instance.get('passive_checks_events',
                                                False),
                ))
        if ('host_perfdata_file' in nagios_conf
                and 'host_perfdata_file_template' in nagios_conf
                and instance.get('collect_host_performance_data', False)):
            self.log.debug("Starting to tail the host_perfdata file")
            tailers.append(
                NagiosPerfDataTailer(
                    log_path=nagios_conf['host_perfdata_file'],
                    file_template=nagios_conf['host_perfdata_file_template'],
                    logger=self.log,
                    hostname=self.hostname,
                    gauge_func=self.gauge,
                    tags=custom_tag,
                    perfdata_field='HOSTPERFDATA',
                    metric_prefix=_get_host_metric_prefix,
                ))
        if ('service_perfdata_file' in nagios_conf
                and 'service_perfdata_file_template' in nagios_conf
                and instance.get('collect_service_performance_data', False)):
            self.log.debug("Starting to tail the service_perfdata file")
            tailers.append(
                NagiosPerfDataTailer(
                    log_path=nagios_conf['service_perfdata_file'],
                    file_template=nagios_conf[
                        'service_perfdata_file_template'],
                    logger=self.log,
                    hostname=self.hostname,
                    gauge_func=self.gauge,
                    tags=custom_tag,
                    perfdata_field='SERVICEPERFDATA',
                    metric_prefix=_get_service_metric_prefix,
                ))

        self.nagios_tails[instance_key] = tailers
Exemple #29
0
    def __init__(self, name, init_config, instances):
        AgentCheck.__init__(self, name, init_config, instances)

        self.gunicorn_cmd = self.instance.get(
            'gunicorn', init_config.get('gunicorn', 'gunicorn'))
 def test_ca_cert_expand_user(self):
     instance = {'tls_ca_cert': '~/foo'}
     check = AgentCheck('test', {}, [instance])
     with patch('ssl.SSLContext'), patch('os.path') as mock_path:
         check.get_tls_context()
         mock_path.expanduser.assert_called_with('~/foo')