Beispiel #1
0
def test_active_check_execution(
    test_cfg, site, web
):  # noqa: F811 # pylint: disable=redefined-outer-name
    try:
        web.set_ruleset(
            "custom_checks",
            {
                "ruleset": {
                    # Main folder
                    "": [
                        {
                            "value": {
                                "service_description": "\xc4ctive-Check",
                                "command_line": 'echo "123"',
                            },
                            "condition": {},
                            "options": {},
                        },
                    ],
                }
            },
        )
        web.activate_changes()

        site.schedule_check("test-host", "\xc4ctive-Check", 0)

        result = site.live.query_row(
            "GET services\nColumns: host_name description state plugin_output has_been_checked\nFilter: host_name = test-host\nFilter: description = \xc4ctive-Check"
        )
        print("Result: %r" % result)
        assert result[4] == 1
        assert result[0] == "test-host"
        assert result[1] == "\xc4ctive-Check"
        assert result[2] == 0
        assert result[3] == "123"
    finally:
        web.set_ruleset(
            "custom_checks",
            {
                "ruleset": {
                    "": [],  # -> folder
                }
            },
        )
        web.activate_changes()
Beispiel #2
0
def test_log_fixture(
    request, web, site: Site, fake_sendmail
):  # noqa: F811 # pylint: disable=redefined-outer-name
    core, log = request.param
    site.set_config("CORE", core, with_restart=True)

    users = {
        "hh": {
            "alias": "Harry Hirsch",
            "password": "******",
            "email": "%s@localhost" % web.site.id,
            "contactgroups": ["all"],
        },
    }

    expected_users = set(["cmkadmin", "automation"] + list(users.keys()))
    web.add_htpasswd_users(users)
    all_users = web.get_all_users()
    assert not expected_users - set(all_users.keys())

    site.live.command("[%d] STOP_EXECUTING_HOST_CHECKS" % time.time())
    site.live.command("[%d] STOP_EXECUTING_SVC_CHECKS" % time.time())

    web.add_host(
        "notify-test",
        attributes={
            "ipaddress": "127.0.0.1",
        },
    )
    web.activate_changes()

    with WatchLog(site, log, default_timeout=20) as l:
        yield l

    site.live.command("[%d] START_EXECUTING_HOST_CHECKS" % time.time())
    site.live.command("[%d] START_EXECUTING_SVC_CHECKS" % time.time())

    web.delete_host("notify-test")
    web.delete_htpasswd_users(list(users.keys()))
    web.activate_changes()
Beispiel #3
0
def test_cfg_fixture(request, web, site):  # noqa: F811 # pylint: disable=redefined-outer-name
    config = DefaultConfig(core=request.param)
    site.set_config("CORE", config.core, with_restart=True)

    print("Applying default config")
    web.add_host(
        "test-host",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_agent": "no-agent",
        },
    )

    web.activate_changes()
    yield config

    #
    # Cleanup code
    #
    print("Cleaning up test config")

    web.delete_host("test-host")
def test_test_check_1_all_rule(request, site, web):  # noqa: F811 # pylint: disable=redefined-outer-name

    host_name = "disco-params-test-host"

    create_linux_test_host(request, web, site, host_name)
    site.write_file("var/check_mk/agent_output/disco-params-test-host",
                    "<<<test_check_2>>>\n1 2\n")

    test_check_path = "local/lib/check_mk/base/plugins/agent_based/test_check_2.py"

    def cleanup():
        if site.file_exists("etc/check_mk/conf.d/test_check_2.mk"):
            site.delete_file("etc/check_mk/conf.d/test_check_2.mk")

        site.delete_file(test_check_path)

    request.addfinalizer(cleanup)

    site.write_file(
        test_check_path,
        """
import pprint

from .agent_based_api.v1 import register, Service


def discover(params, section):
    yield Service(item=pprint.pformat(params))


def check(item, section):
    return
    yield


register.check_plugin(
    name="test_check_2",
    discovery_function=discover,
    discovery_ruleset_name="discover_test_check_2",
    discovery_ruleset_type=register.RuleSetType.ALL,
    discovery_default_parameters={"default": 42},
    check_function=check,
    service_name="Foo %s",
)
""",
    )

    web.activate_changes()

    web.discover_services(host_name)

    # Verify that the discovery worked as expected
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)

    for service in services:
        if str(service.check_plugin_name) == "test_check_2":
            assert service.item == "[Parameters({'default': 42})]"
            break
    else:
        raise AssertionError('"test_check_2" not discovered')

    # And now overwrite the setting in the config
    site.write_file(
        "etc/check_mk/conf.d/test_check_2.mk",
        "discover_test_check_2 = [{'value': {'levels': (1, 2)}, 'condition': {}}]\n",
    )

    # rediscover with the setting in the config
    site.delete_file(f"var/check_mk/autochecks/{host_name}.mk")
    web.discover_services(host_name)
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)
    for service in services:
        if str(service.check_plugin_name) == "test_check_2":
            assert service.item == ("[Parameters({'levels': (1, 2)}),"
                                    " Parameters({'default': 42})]")
            break
    else:
        raise AssertionError('"test_check_2" not discovered')
Beispiel #5
0
def test_cfg_fixture(web, site):  # noqa: F811  # pylint: disable=redefined-outer-name
    site.ensure_running()

    print("Applying default config")
    web.add_host(
        "modes-test-host",
        attributes={
            "ipaddress": "127.0.0.1",
        },
    )
    web.add_host(
        "modes-test-host2",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "test",
        },
    )
    web.add_host(
        "modes-test-host3",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "test",
        },
    )
    web.add_host(
        "modes-test-host4",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "offline",
        },
    )

    site.write_file(
        "etc/check_mk/conf.d/modes-test-host.mk",
        "datasource_programs.append(('cat ~/var/check_mk/agent_output/<HOST>', [], ALL_HOSTS))\n",
    )

    site.makedirs("var/check_mk/agent_output/")
    site.write_file("var/check_mk/agent_output/modes-test-host", get_standard_linux_agent_output())
    site.write_file("var/check_mk/agent_output/modes-test-host2", get_standard_linux_agent_output())
    site.write_file("var/check_mk/agent_output/modes-test-host3", get_standard_linux_agent_output())

    web.discover_services("modes-test-host")
    web.discover_services("modes-test-host2")
    web.discover_services("modes-test-host3")

    try:
        web.activate_changes()
        yield None
    finally:
        #
        # Cleanup code
        #
        print("Cleaning up test config")

        site.delete_dir("var/check_mk/agent_output")

        site.delete_file("etc/check_mk/conf.d/modes-test-host.mk")

        web.delete_host("modes-test-host")
        web.delete_host("modes-test-host2")
        web.delete_host("modes-test-host3")
        web.delete_host("modes-test-host4")
        web.activate_changes()
Beispiel #6
0
def test_active_check_macros(
    test_cfg, site, web
):  # noqa: F811 # pylint: disable=redefined-outer-name
    macros = {
        "$HOSTADDRESS$": "127.0.0.1",
        "$HOSTNAME$": "test-host",
        "$_HOSTTAGS$": " ".join(
            sorted(
                [
                    "/wato/",
                    "auto-piggyback",
                    "ip-v4",
                    "ip-v4-only",
                    "lan",
                    "no-agent",
                    "no-snmp",
                    "ping",
                    "prod",
                    "site:%s" % site.id,
                ]
            )
        ),
        "$_HOSTADDRESS_4$": "127.0.0.1",
        "$_HOSTADDRESS_6$": "",
        "$_HOSTADDRESS_FAMILY$": "4",
        "$USER1$": "/omd/sites/%s/lib/nagios/plugins" % site.id,
        "$USER2$": "/omd/sites/%s/local/lib/nagios/plugins" % site.id,
        "$USER3$": site.id,
        "$USER4$": site.root,
    }

    def descr(var):
        return "Macro %s" % var.strip("$")

    ruleset = []
    for var, value in macros.items():
        ruleset.append(
            {
                "value": {
                    "service_description": descr(var),
                    "command_line": 'echo "Output: %s"' % var,
                },
                "condition": {},
            }
        )

    try:
        web.set_ruleset(
            "custom_checks",
            {
                "ruleset": {
                    # Main folder
                    "": ruleset,
                }
            },
        )
        web.activate_changes()

        for var, value in macros.items():
            description = descr(var)
            logger.info(description)
            site.schedule_check("test-host", description, 0)

            logger.info("Get service row")
            row = site.live.query_row(
                "GET services\n"
                "Columns: host_name description state plugin_output has_been_checked\n"
                "Filter: host_name = test-host\n"
                "Filter: description = %s\n" % description
            )

            logger.info(row)
            name, description, state, plugin_output, has_been_checked = row

            assert name == "test-host"
            assert has_been_checked == 1
            assert state == 0

            expected_output = "Output: %s" % value
            # TODO: Cleanup difference between nagios/cmc
            if test_cfg.core == "nagios":
                expected_output = expected_output.strip()
                if var == "$_HOSTTAGS$":
                    splitted_output = plugin_output.split(" ")
                    plugin_output = splitted_output[0] + " " + " ".join(sorted(splitted_output[1:]))

            assert (
                expected_output == plugin_output
            ), "Macro %s has wrong value (%r instead of %r)" % (var, plugin_output, expected_output)

    finally:
        web.set_ruleset(
            "custom_checks",
            {
                "ruleset": {
                    "": [],  # -> folder
                }
            },
        )
        web.activate_changes()
def test_test_check_1(request, site, web):  # noqa: F811 # pylint: disable=redefined-outer-name

    host_name = "check-variables-test-host"

    create_linux_test_host(request, web, site, host_name)
    site.write_file(f"var/check_mk/agent_output/{host_name}",
                    "<<<test_check_1>>>\n1 2\n")

    test_check_path = "local/share/check_mk/checks/test_check_1"

    def cleanup():
        if site.file_exists("etc/check_mk/conf.d/test_check_1.mk"):
            site.delete_file("etc/check_mk/conf.d/test_check_1.mk")

        site.delete_file(test_check_path)

    request.addfinalizer(cleanup)

    site.write_file(
        test_check_path,
        """

test_check_1_default_levels = 10.0, 20.0

def inventory(info):
    return [(None, "test_check_1_default_levels")]

def check(item, params, info):
    return 0, "OK - %r" % (test_check_1_default_levels, )

check_info["test_check_1"] = {
    "check_function"          : check,
    "inventory_function"      : inventory,
    "service_description"     : "Testcheck 1",
#    "default_levels_variable" : "test_check_1_default_levels"
}
""",
    )

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])
    config.load(with_conf_d=False)
    web.activate_changes()

    # Verify that the default variable is in the check context and
    # not in the global checks module context.
    assert "test_check_1_default_levels" not in config.__dict__
    assert "test_check_1" in config._check_contexts
    assert "test_check_1_default_levels" in config._check_contexts[
        "test_check_1"]
    assert config._check_contexts["test_check_1"][
        "test_check_1_default_levels"] == (10.0, 20.0)

    web.discover_services(host_name)

    # Verify that the discovery worked as expected
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)
    assert str(services[0].check_plugin_name) == "test_check_1"
    assert services[0].item is None
    assert services[0].parameters == (10.0, 20.0)
    assert services[0].service_labels.to_dict() == {}

    # Now execute the check function to verify the variable is available
    p = site.execute(["cmk", "-nv", host_name],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    assert "OK - (10.0, 20.0)" in stdout
    assert stderr == ""
    assert p.returncode == 0

    # And now overwrite the setting in the config
    site.write_file("etc/check_mk/conf.d/test_check_1.mk",
                    "test_check_1_default_levels = 5.0, 30.1\n")

    p = site.execute(["cmk", "-nv", host_name],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    assert "OK - (10.0, 20.0)" not in stdout
    assert "OK - (5.0, 30.1)" in stdout
    assert stderr == ""
    assert p.returncode == 0

    # rediscover with the setting in the config
    site.delete_file(f"var/check_mk/autochecks/{host_name}.mk")
    web.discover_services(host_name)
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)
    assert services[0].parameters == (5.0, 30.1)
def test_check_factory_settings(request, site, web):  # noqa: F811 # pylint: disable=redefined-outer-name

    host_name = "check-variables-test-host"

    create_linux_test_host(request, web, site, host_name)
    site.write_file(f"var/check_mk/agent_output/{host_name}",
                    "<<<test_check_3>>>\n1 2\n")

    test_check_path = "local/share/check_mk/checks/test_check_3"

    def cleanup():
        if site.file_exists("etc/check_mk/conf.d/test_check_3.mk"):
            site.delete_file("etc/check_mk/conf.d/test_check_3.mk")

        site.delete_file(test_check_path)

    request.addfinalizer(cleanup)

    site.write_file(
        test_check_path,
        """

factory_settings["test_check_3_default_levels"] = {
    "param1": 123,
}

def inventory(info):
    return [(None, {})]

def check(item, params, info):
    return 0, "OK - %r" % (params, )

check_info["test_check_3"] = {
    "check_function"          : check,
    "inventory_function"      : inventory,
    "service_description"     : "Testcheck 3",
    "group"                   : "asd",
    "default_levels_variable" : "test_check_3_default_levels",
}
""",
    )

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])
    config.load(with_conf_d=False)
    web.activate_changes()

    # Verify that the default variable is in the check context and
    # not in the global checks module context
    assert "test_check_3_default_levels" not in config.__dict__
    assert "test_check_3" in config._check_contexts
    assert "test_check_3_default_levels" in config._check_contexts[
        "test_check_3"]

    web.discover_services(host_name)

    # Verify that the discovery worked as expected
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)
    assert str(services[0].check_plugin_name) == "test_check_3"
    assert services[0].item is None
    assert services[0].parameters == {}
    assert services[0].service_labels.to_dict() == {}

    # Now execute the check function to verify the variable is available
    p = site.execute(["cmk", "-nv", host_name],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    assert "OK - {'param1': 123}\n" in stdout, stdout
    assert stderr == ""
    assert p.returncode == 0

    # And now overwrite the setting in the config
    site.write_file(
        "etc/check_mk/conf.d/test_check_3.mk",
        """
checkgroup_parameters.setdefault('asd', [])

checkgroup_parameters['asd'] = [
    ( {'param2': 'xxx'}, [], ALL_HOSTS, {} ),
] + checkgroup_parameters['asd']
""",
    )

    # And execute the check again to check for the parameters
    p = site.execute(["cmk", "-nv", host_name],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    assert "'param1': 123" in stdout
    assert "'param2': 'xxx'" in stdout
    assert stderr == ""
    assert p.returncode == 0
def test_test_check_2(request, site, web):  # noqa: F811 # pylint: disable=redefined-outer-name

    host_name = "check-variables-test-host"

    create_linux_test_host(request, web, site, host_name)
    site.write_file(f"var/check_mk/agent_output/{host_name}",
                    "<<<test_check_2>>>\n1 2\n")

    test_check_path = "local/share/check_mk/checks/test_check_2"

    def cleanup():
        if site.file_exists("etc/check_mk/conf.d/test_check_2.mk"):
            site.delete_file("etc/check_mk/conf.d/test_check_2.mk")

        site.delete_file(test_check_path)

    request.addfinalizer(cleanup)

    site.write_file(
        test_check_path,
        """

discover_service = False

def inventory(info):
    if discover_service:
        return [(None, {})]

def check(item, params, info):
    return 0, "OK, discovered!"

check_info["test_check_2"] = {
    "check_function"      : check,
    "inventory_function"  : inventory,
    "service_description" : "Testcheck 2",
}
""",
    )

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])
    config.load(with_conf_d=False)
    web.activate_changes()

    # Verify that the default variable is in the check context and
    # not in the global checks module context
    assert "discover_service" not in config.__dict__
    assert "test_check_2" in config._check_contexts
    assert "discover_service" in config._check_contexts["test_check_2"]

    web.discover_services(host_name)

    # Should have discovered nothing so far
    assert site.read_file(
        f"var/check_mk/autochecks/{host_name}.mk") == "[\n]\n"

    web.discover_services(host_name)

    # And now overwrite the setting in the config
    site.write_file("etc/check_mk/conf.d/test_check_2.mk",
                    "discover_service = True\n")

    web.discover_services(host_name)

    # Verify that the discovery worked as expected
    services = autochecks.parse_autochecks_file(HostName(host_name),
                                                config.service_description)
    assert str(services[0].check_plugin_name) == "test_check_2"
    assert services[0].item is None
    assert services[0].parameters == {}
    assert services[0].service_labels.to_dict() == {}