예제 #1
0
def test_ruleset_matcher_get_service_ruleset_values_labels(
        monkeypatch, hostname, service_description, expected_result):
    ts = Scenario()

    ts.add_host("host1")
    ts.set_autochecks("host1", [
        Service("cpu.load",
                None,
                "CPU load",
                "{}",
                service_labels=DiscoveredServiceLabels(
                    ServiceLabel(u"os", u"linux"),
                    ServiceLabel(u"abc", u"xä"),
                    ServiceLabel(u"hu", u"ha"),
                ))
    ])

    ts.add_host("host2")
    ts.set_autochecks("host2", [
        Service("cpu.load",
                None,
                "CPU load",
                "{}",
                service_labels=DiscoveredServiceLabels()),
    ])

    config_cache = ts.apply(monkeypatch)
    matcher = config_cache.ruleset_matcher

    assert list(
        matcher.get_service_ruleset_values(
            config_cache.ruleset_match_object_of_service(
                hostname, service_description),
            ruleset=service_label_ruleset,
            is_binary=False)) == expected_result
예제 #2
0
def test_host_ruleset_match_object_of_service(monkeypatch):
    ts = Scenario()
    ts.add_host("xyz")
    ts.add_host("test-host", tags={"agent": "no-agent"})
    ts.set_autochecks("test-host", [
        Service("cpu.load",
                None,
                "CPU load",
                "{}",
                service_labels=DiscoveredServiceLabels(ServiceLabel(u"abc", u"xä"),))
    ])
    config_cache = ts.apply(monkeypatch)

    obj = config_cache.ruleset_match_object_of_service("xyz", "bla blä")
    assert isinstance(obj, RulesetMatchObject)
    assert obj.to_dict() == {
        "host_name": "xyz",
        "service_description": "bla blä",
        "service_labels": {},
        "service_cache_id": ('bla bl\xc3\xa4', None),
    }

    obj = config_cache.ruleset_match_object_of_service("test-host", "CPU load")
    service_labels = {u"abc": u"xä"}
    assert isinstance(obj, RulesetMatchObject)
    assert obj.to_dict() == {
        "host_name": "test-host",
        "service_description": "CPU load",
        "service_labels": service_labels,
        "service_cache_id": ('CPU load', obj._generate_hash(service_labels)),
    }
예제 #3
0
def _parse_discovered_service_label_from_ast(ast_service_labels):
    # type: (ast.Dict) -> DiscoveredServiceLabels
    labels = DiscoveredServiceLabels()

    # mypy does not get the types of the ast objects here
    if not hasattr(ast_service_labels, "keys"):  # # type: ignore
        return labels

    for key, value in zip(ast_service_labels.keys, ast_service_labels.values):
        # mypy does not get the types of the ast objects here
        labels.add_label(ServiceLabel(key.s, value.s))  # type: ignore

    return labels
예제 #4
0
    def _read_raw_autochecks_of(self, hostname):
        # type: (str) -> List[Service]
        """Read automatically discovered checks of one host"""
        basedir = cmk.utils.paths.autochecks_dir
        filepath = basedir + '/' + hostname + '.mk'

        result = []  # type: List[Service]
        if not os.path.exists(filepath):
            return result

        check_config = config.get_check_variables()
        try:
            cmk_base.console.vverbose("Loading autochecks from %s\n", filepath)
            autochecks_raw = eval(
                file(filepath).read().decode("utf-8"), check_config,
                check_config)  # type: List[Dict]
        except SyntaxError as e:
            cmk_base.console.verbose("Syntax error in file %s: %s\n",
                                     filepath,
                                     e,
                                     stream=sys.stderr)
            if cmk.utils.debug.enabled():
                raise
            return result
        except Exception as e:
            cmk_base.console.verbose("Error in file %s:\n%s\n",
                                     filepath,
                                     e,
                                     stream=sys.stderr)
            if cmk.utils.debug.enabled():
                raise
            return result

        for entry in autochecks_raw:
            labels = DiscoveredServiceLabels()
            for label_id, label_value in entry["service_labels"].items():
                labels.add_label(ServiceLabel(label_id, label_value))

            # With Check_MK 1.2.7i3 items are now defined to be unicode strings. Convert
            # items from existing autocheck files for compatibility. TODO remove this one day
            item = entry["item"]
            if isinstance(item, str):
                item = config.decode_incoming_string(item)

            if not isinstance(entry["check_plugin_name"], six.string_types):
                raise MKGeneralException(
                    "Invalid entry '%r' in check table of host '%s': "
                    "The check type must be a string." % (entry, hostname))

            try:
                description = config.service_description(
                    hostname, entry["check_plugin_name"], item)
            except Exception:
                continue  # ignore

            result.append(
                Service(
                    check_plugin_name=str(entry["check_plugin_name"]),
                    item=item,
                    description=description,
                    parameters=entry["parameters"],
                    service_labels=labels,
                ))

        return result
예제 #5
0

def test_remove_autochecks_file():
    assert autochecks.has_autochecks("host") is False
    autochecks.save_autochecks_file("host", [])
    assert autochecks.has_autochecks("host") is True
    autochecks.remove_autochecks_file("host")
    assert autochecks.has_autochecks("host") is False


@pytest.mark.parametrize("items,expected_content", [
    ([], "[\n]\n"),
    ([
        discovery.DiscoveredService(
            'df', u'/xyz', u"Filesystem /xyz", "None",
            DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))),
        discovery.DiscoveredService(
            'df', u'/', u"Filesystem /", "{}",
            DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))),
        discovery.DiscoveredService(
            'cpu.loads', None, "CPU load", "cpuload_default_levels",
            DiscoveredServiceLabels(ServiceLabel(u"x", u"y"))),
    ], """[
  {'check_plugin_name': 'cpu.loads', 'item': None, 'parameters': cpuload_default_levels, 'service_labels': {u'x': u'y'}},
  {'check_plugin_name': 'df', 'item': u'/', 'parameters': {}, 'service_labels': {u'x': u'y'}},
  {'check_plugin_name': 'df', 'item': u'/xyz', 'parameters': None, 'service_labels': {u'x': u'y'}},
]\n"""),
])
def test_save_autochecks_file(items, expected_content):
    autochecks.save_autochecks_file("host", items)