示例#1
0
def test_cluster_ignores_nodes_parameters(monkeypatch: MonkeyPatch) -> None:

    node = HostName("node")
    cluster = HostName("cluster")

    service_id = CheckPluginName("smart_temp"), "auto-clustered"

    ts = Scenario()
    ts.add_host("node")
    ts.add_cluster("cluster", nodes=["node"])
    ts.set_ruleset(
        "clustered_services",
        [([], ["node"], ["Temperature SMART auto-clustered$"])],
    )
    ts.set_autochecks("node", [AutocheckEntry(*service_id, {}, {})])
    ts.apply(monkeypatch)

    # a rule for the node:
    monkeypatch.setattr(
        config,
        "_get_configured_parameters",
        lambda host, plugin, item:
        (TimespecificParameters((TimespecificParameterSet.from_parameters(
            {"levels_for_node": (1, 2)}), ))
         if host == node else TimespecificParameters()),
    )

    clustered_service = check_table.get_check_table(cluster)[service_id]
    assert clustered_service.parameters.entries == (
        TimespecificParameterSet.from_parameters({"levels": (35, 40)}), )
示例#2
0
def _get_static_check_entries(
    config_cache: config.ConfigCache,
    host_config: config.HostConfig,
) -> Iterator[Service]:
    entries: List[Service] = []
    for _checkgroup_name, check_plugin_name_str, item, params in host_config.static_checks:
        # TODO (mo): centralize maincheckify: CMK-4295
        # in this case: move it to the transform of the static services rule.
        check_plugin_name = CheckPluginName(maincheckify(check_plugin_name_str))

        descr = config.service_description(host_config.hostname, check_plugin_name, item)
        new_parameters = config.compute_check_parameters(
            config_cache.host_of_clustered_service(host_config.hostname, descr),
            check_plugin_name,
            item,
            {},
            configured_parameters=TimespecificParameters((params,)),
        )

        entries.append(Service(check_plugin_name, item, descr, new_parameters))

    # Note: We need to reverse the order of the static_checks. This is
    # because users assume that earlier rules have precedence over later
    # ones. For static checks that is important if there are two rules for
    # a host with the same combination of check type and item.
    return reversed(entries)
示例#3
0
def test_get_cmk_passive_service_attributes(monkeypatch, hostname, result):
    ts = Scenario()
    ts.add_host("localhost")
    ts.add_host("blub")
    ts.set_option(
        "extra_service_conf",
        {
            "contact_groups": [
                ("ding", ["localhost"], ["CPU load$"]),
            ],
            "check_interval": [
                (40.0, ["blub"], ["Check_MK$"]),
                (33.0, ["localhost"], ["CPU load$"]),
            ],
        },
    )
    config_cache = ts.apply(monkeypatch)
    host_config = config_cache.get_host_config(hostname)
    check_mk_attrs = core_config.get_service_attributes(
        hostname, "Check_MK", config_cache)

    service = ConfiguredService(
        check_plugin_name=CheckPluginName("cpu_loads"),
        item=None,
        description="CPU load",
        parameters=TimespecificParameters(),
        discovered_parameters={},
        service_labels={},
    )
    service_spec = core_config.get_cmk_passive_service_attributes(
        config_cache, host_config, service, check_mk_attrs)
    assert service_spec == result
示例#4
0
def _get_static_check_entries(
    config_cache: config.ConfigCache,
    host_config: config.HostConfig,
) -> Iterator[ConfiguredService]:
    entries = []
    for _checkgroup_name, check_plugin_name, item, params in host_config.static_checks:

        descr = config.service_description(host_config.hostname, check_plugin_name, item)
        entries.append(
            ConfiguredService(
                check_plugin_name=check_plugin_name,
                item=item,
                description=descr,
                parameters=config.compute_check_parameters(
                    config_cache.host_of_clustered_service(host_config.hostname, descr),
                    check_plugin_name,
                    item,
                    {},
                    configured_parameters=TimespecificParameters((params,)),
                ),
                discovered_parameters=None,
                service_labels={},
            )
        )

    # Note: We need to reverse the order of the static_checks. This is
    # because users assume that earlier rules have precedence over later
    # ones. For static checks that is important if there are two rules for
    # a host with the same combination of check type and item.
    return reversed(entries)
示例#5
0
 def test_first_tuple_wins(self):
     tuple_1: List[Tuple[str, LegacyCheckParameters]] = [("tp3", (1, 1))]
     tuple_2: List[Tuple[str, LegacyCheckParameters]] = [("tp3", (2, 2))]
     assert (TimespecificParameters((
         TimespecificParameterSet(_default(), _tp_values()),
         TimespecificParameterSet(_default(),
                                  _tp_values() + tuple_1),
         TimespecificParameterSet(_default(), tuple_2 + _tp_values()),
     )).evaluate(lambda x: True) == (1, 1))
示例#6
0
def _service(plugin: str, item: Optional[str]) -> ConfiguredService:
    return ConfiguredService(
        check_plugin_name=CheckPluginName(plugin),
        item=item,
        description=f"test description {plugin}/{item}",
        parameters=TimespecificParameters(),
        discovered_parameters={},
        service_labels={},
    )
示例#7
0
 def test_first_key_wins(self):
     assert (TimespecificParameters((
         TimespecificParameterSet(
             {"key": "I am only default, but the most specific rule!"}, ()),
         TimespecificParameterSet(
             {"key": "default"},
             [(
                 "active_tp",
                 {
                     "key":
                     "I am a specificly time-matching value, but from a more general rule!"
                 },
             )],
         ),
     )).evaluate(lambda x: True) == {
         "key": "I am only default, but the most specific rule!"
     })
示例#8
0
from pathlib import Path
from typing import Dict, Optional, Sequence

import pytest

from tests.testlib.base import Scenario

import cmk.utils.paths
from cmk.utils.parameters import TimespecificParameters
from cmk.utils.type_defs import CheckPluginName, HostName

import cmk.base.autochecks as autochecks
import cmk.base.config as config
from cmk.base.check_utils import ConfiguredService

_COMPUTED_PARAMETERS_SENTINEL = TimespecificParameters(())


@pytest.fixture(autouse=True)
def autochecks_dir(monkeypatch, tmp_path):
    monkeypatch.setattr(cmk.utils.paths, "autochecks_dir", str(tmp_path))


@pytest.fixture()
def test_config(monkeypatch) -> config.ConfigCache:
    ts = Scenario()
    ts.add_host("host")
    return ts.apply(monkeypatch)


@pytest.mark.usefixtures("fix_register")
示例#9
0
def test_check_table__get_static_check_entries(
        monkeypatch: MonkeyPatch,
        check_group_parameters: LegacyCheckParameters) -> None:
    hostname = HostName("hostname")

    static_parameters_default = {"levels": (1, 2, 3, 4)}
    static_checks: Dict[str, List] = {
        "ps":
        [(("ps", "item", static_parameters_default), [], [hostname], {})],
    }

    ts = Scenario()
    ts.add_host(hostname)
    ts.set_option("static_checks", static_checks)

    ts.set_ruleset(
        "checkgroup_parameters",
        {
            "ps": [(check_group_parameters, [hostname], [], {})],
        },
    )

    config_cache = ts.apply(monkeypatch)

    monkeypatch.setattr(
        agent_based_register,
        "get_check_plugin",
        lambda cpn: CheckPlugin(
            CheckPluginName("ps"),
            [],
            "Process item",
            lambda: [],
            None,
            None,
            "merged",
            lambda: [],
            {},
            RuleSetName("ps"),
            None,
            None,
        ),
    )

    host_config = config_cache.get_host_config(hostname)
    static_check_parameters = [
        service.parameters
        for service in check_table._get_static_check_entries(
            config_cache, host_config)
    ]

    entries = config._get_checkgroup_parameters(
        config_cache,
        hostname,
        "ps",
        "item",
        "Process item",
    )

    assert len(entries) == 1
    assert entries[0] == check_group_parameters

    assert len(static_check_parameters) == 1
    static_check_parameter = static_check_parameters[0]
    assert static_check_parameter == TimespecificParameters((
        TimespecificParameterSet(static_parameters_default, ()),
        TimespecificParameterSet({}, ()),
    ))
示例#10
0
@pytest.mark.parametrize(
    "hostname_str,expected_result",
    [
        ("empty-host", {}),
        # Skip the autochecks automatically for ping hosts
        ("ping-host", {}),
        (
            "no-autochecks",
            {
                (CheckPluginName("smart_temp"), "/dev/sda"):
                ConfiguredService(
                    check_plugin_name=CheckPluginName("smart_temp"),
                    item="/dev/sda",
                    description="Temperature SMART /dev/sda",
                    parameters=TimespecificParameters((
                        TimespecificParameterSet({}, ()),
                        TimespecificParameterSet({"levels": (35, 40)}, ()),
                    )),
                    discovered_parameters=None,
                    service_labels={},
                ),
            },
        ),
        # Static checks overwrite the autocheck definitions
        (
            "autocheck-overwrite",
            {
                (CheckPluginName("smart_temp"), "/dev/sda"):
                ConfiguredService(
                    check_plugin_name=CheckPluginName("smart_temp"),
                    item="/dev/sda",
                    description="Temperature SMART /dev/sda",
示例#11
0
def make_timespecific_params_list(
    entries: Iterable[LegacyCheckParameters],
) -> TimespecificParameters:
    return TimespecificParameters([TimespecificParameterSet.from_parameters(e) for e in entries])
示例#12
0
def test_time_resolved_check_parameters(
    monkeypatch, rules: TimespecificParameters, active_timeperiods, expected_result
):
    assert expected_result == rules.evaluate(lambda tp: tp in active_timeperiods)