Example #1
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/visuals/test_plugin.py"
    site.write_text_file(
        path,
        """
from cmk.gui.plugins.visuals import filter_registry
from cmk.gui.plugins.visuals.filters import FilterText
import cmk.gui.legacy_filters as legacy_filters

filter_registry.register(
    FilterText(
        ident="test",
        title="test",
        sort_index=102,
        info="host",
        legacy_filter=legacy_filters.FilterText(
            column="host_test", htmlvar="test", op="~~", negateable=False
        ),
        description="",
        is_show_more=True,
    )
)
""",
    )
    yield path
    site.delete_file(path)
Example #2
0
def configure_service_tags_fixture(site: Site, default_cfg):
    site.openapi.create_host(
        "modes-test-host",
        attributes={
            "ipaddress": "127.0.0.1",
        },
    )
    rule_id = site.openapi.create_rule(
        ruleset_name="service_tag_rules",
        value=[("criticality", "prod")],
        conditions={
            "host_name": {
                "match_on": ["livestatus-test-host"],
                "operator": "one_of",
            },
            "service_description": {
                "match_on": ["CPU load$"],
                "operator": "one_of",
            },
        },
    )
    site.activate_changes_and_wait_for_core_reload()
    yield
    site.openapi.delete_rule(rule_id)
    site.activate_changes_and_wait_for_core_reload()
Example #3
0
def default_cfg_fixture(request, site: Site, web) -> None:
    site.ensure_running()
    print("Applying default config")
    create_linux_test_host(request, site, "livestatus-test-host")
    create_linux_test_host(request, site, "livestatus-test-host.domain")
    web.discover_services("livestatus-test-host")  # Replace with RestAPI call, see CMK-9249
    site.activate_changes_and_wait_for_core_reload()
Example #4
0
def test_host_table_host_equal_filter(site: Site) -> None:
    queries = {
        "nagios":
        "GET hosts\n"
        "Columns: host_name\n"
        "Filter: host_name = livestatus-test-host.domain\n",
        "cmc":
        "GET hosts\n"
        "Columns: host_name\n"
        "Filter: host_name = livestatus-test-host\n",
    }
    results = {
        "nagios": [
            {
                "name": "livestatus-test-host.domain",
            },
        ],
        "cmc": [
            {
                "name": "livestatus-test-host",
            },
        ],
    }

    rows = site.live.query_table_assoc(queries[site.core_name()])
    assert rows == results[site.core_name()]
Example #5
0
def fake_sendmail_fixture(site: Site):
    site.write_text_file(
        "local/bin/sendmail", "#!/bin/bash\n" "set -e\n" 'echo "sendmail called with: $@"\n'
    )
    os.chmod(site.path("local/bin/sendmail"), 0o775)
    yield
    site.delete_file("local/bin/sendmail")
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/visuals/test_plugin.py"
    site.write_text_file(
        path,
        """
from cmk.gui.plugins.visuals import filter_registry
from cmk.gui.plugins.visuals.filters import InputTextFilter
import cmk.gui.query_filters as query_filters

filter_registry.register(
    InputTextFilter(
        title="test",
        sort_index=102,
        info="host",
        query_filter=query_filters.TextQuery(
            ident="test", op="~~", negateable=False, request_var="test", column="host_test"
        ),
        description="",
        is_show_more=True,
    )
)
""",
    )
    yield path
    site.delete_file(path)
def test_child_up_after_parent_recovers(scenario, site: Site, initial_state):
    with WatchLog(site, scenario.log, default_timeout=scenario.log_timeout) as log:
        # - Set parent down, expect DOWN notification
        _send_parent_down(scenario, site, log)
        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
        )

        # - set child down, expect UNREACHABLE notification
        _send_child_down_expect_unreachable(scenario, site, log)

        # - Set parent up, expect UP notification
        _send_parent_recovery(scenario, site, log)

        # - Next service check UP, expect no notification (till next parent check confirms UP)
        site.send_host_check_result("notify-test-child", STATE_UP, "UP")
        log.check_logged("HOST ALERT: notify-test-child;UP;HARD;1;")

        # - Set parent UP, expect UP notification for child
        site.send_host_check_result("notify-test-parent", STATE_UP, "UP")

        if scenario.unreachable_enabled:
            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-child;UP;check-mk-notify;"
            )
        else:
            log.check_not_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-child;UP;check-mk-notify;"
            )
Example #8
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/wato/test_plugin.py"
    site.write_text_file(
        path,
        """
from cmk.gui.plugins.wato import rulespec_registry, HostRulespec
from cmk.gui.plugins.wato.check_mk_configuration import RulespecGroupHostsMonitoringRulesVarious
from cmk.gui.valuespec import Dictionary

def _valuespec_host_groups():
    return Dictionary()


rulespec_registry.register(
    HostRulespec(
        group=RulespecGroupHostsMonitoringRulesVarious,
        match_type="dict",
        name="test",
        valuespec=_valuespec_host_groups,
    )
)
""",
    )
    yield path
    site.delete_file(path)
Example #9
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/dashboard/test_plugin.py"
    site.write_text_file(
        path,
        """
from cmk.gui.plugins.dashboard import Dashlet, dashlet_registry

@dashlet_registry.register
class TestDashlet(Dashlet):
    @classmethod
    def type_name(cls):
        return "test"

    @classmethod
    def title(cls):
        return "test"

    @classmethod
    def description(cls):
        return "test"

    @classmethod
    def sort_index(cls):
        return 0

    @classmethod
    def is_selectable(cls):
        return False

    def show(self):
        pass
""",
    )
    yield path
    site.delete_file(path)
Example #10
0
def test_child_down_and_up_while_not_reachable(unreachable_enabled, site: Site,
                                               initial_state):
    with WatchLog(site) as log:
        # - Set parent down, expect DOWN notification
        _send_parent_down(site, log)
        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
        )

        # - set child down, expect UNREACHABLE notification
        _send_child_down_expect_unreachable(unreachable_enabled, site, log)

        # - Set child up, expect no notification
        site.send_host_check_result("notify-test-child", STATE_UP, "UP")
        log.check_logged("HOST ALERT: notify-test-child;UP;HARD;1;")

        if unreachable_enabled:
            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-child;UP;check-mk-notify;"
            )
        else:
            log.check_not_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-child;UP")

        # - Set parent up, expect UP notification
        _send_parent_recovery(site, log)
Example #11
0
def test_child_down_after_parent_recovers(unreachable_enabled, site: Site,
                                          initial_state):
    with WatchLog(site) as log:
        # - Set parent down, expect DOWN notification
        _send_parent_down(site, log)
        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
        )

        # - set child down, expect UNREACHABLE notification
        _send_child_down_expect_unreachable(unreachable_enabled, site, log)

        # - Set parent up, expect UP notification
        _send_parent_recovery(site, log)

        # - Next child check DOWN, expect no notification (till next parent check confirms UP)
        site.send_host_check_result("notify-test-child", STATE_DOWN, "DOWN")
        log.check_logged("HOST ALERT: notify-test-child;DOWN;HARD;1;")

        if site.core_name() == "cmc":
            # - Set parent UP (again), expect DOWN notification for child
            site.send_host_check_result("notify-test-parent", STATE_UP, "UP")

        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-child;DOWN;check-mk-notify;"
        )
Example #12
0
def test_restore(request, site: Site, execute):
    # TODO: main.mk cannot be restored.
    def cleanup():
        if site.file_exists("etc/check_mk.sav"):
            site.delete_dir("etc/check_mk.sav")
        if site.file_exists("etc/check_mk/final.mk"):
            site.delete_file("etc/check_mk/final.mk")
        site.delete_file("x.tgz")

    request.addfinalizer(cleanup)

    # Add `final.mk` to the site, delete it, and restore it from a backup.
    assert (execute(["cp", "etc/check_mk/main.mk", "etc/check_mk/final.mk"],
                    cwd=site.root).returncode == 0)
    assert execute(["cp", "-pr", "etc/check_mk", "etc/check_mk.sav"],
                   cwd=site.root).returncode == 0
    _create_cmk_backup(site, execute)

    site.delete_file("etc/check_mk/final.mk")
    p = execute(["cmk", "--restore", "x.tgz"], cwd=site.root)
    assert p.returncode == 0, on_failure(p)
    assert p.stderr == ""
    assert p.stdout == ""

    p = execute(["diff", "-ur", "etc/check_mk", "etc/check_mk.sav"],
                cwd=site.root)
    assert p.returncode == 0, on_failure(p)
Example #13
0
def test_automation_notification_analyse(test_cfg, site: Site):
    site.write_text_file(
        "var/check_mk/notify/backlog.mk",
        "[{'SERVICEACKCOMMENT': '', 'SERVICE_EC_CONTACT': '', 'PREVIOUSSERVICEHARDSTATEID': '0', 'HOST_ADDRESS_6': '', 'NOTIFICATIONAUTHORNAME': '', 'LASTSERVICESTATECHANGE': '1502452826', 'HOSTGROUPNAMES': 'check_mk', 'HOSTTAGS': '/wato/ cmk-agent ip-v4 ip-v4-only lan prod site:heute tcp wato', 'LONGSERVICEOUTPUT': '', 'LASTHOSTPROBLEMID': '0', 'HOSTPROBLEMID': '0', 'HOSTNOTIFICATIONNUMBER': '0', 'SERVICE_SL': '', 'HOSTSTATE': 'PENDING', 'HOSTACKCOMMENT': '', 'LONGHOSTOUTPUT': '', 'LASTHOSTSTATECHANGE': '0', 'HOSTOUTPUT': '', 'HOSTNOTESURL': '', 'HOSTATTEMPT': '1', 'SERVICEDOWNTIME': '0', 'LASTSERVICESTATE': 'OK', 'SERVICEDESC': 'Temperature Zone 0', 'NOTIFICATIONAUTHOR': '', 'HOSTALIAS': 'localhost', 'PREVIOUSHOSTHARDSTATEID': '0', 'SERVICENOTES': '', 'HOSTPERFDATA': '', 'SERVICEACKAUTHOR': '', 'SERVICEATTEMPT': '1', 'LASTHOSTSTATEID': '0', 'SERVICENOTESURL': '', 'NOTIFICATIONCOMMENT': '', 'HOST_ADDRESS_FAMILY': '4', 'LASTHOSTUP': '0', 'PREVIOUSHOSTHARDSTATE': 'PENDING', 'LASTSERVICESTATEID': '0', 'LASTSERVICEOK': '0', 'HOSTDOWNTIME': '0', 'SERVICECHECKCOMMAND': 'check_mk-lnx_thermal', 'SERVICEPROBLEMID': '138', 'HOST_SL': '', 'HOSTCHECKCOMMAND': 'check-mk-host-smart', 'SERVICESTATE': 'WARNING', 'HOSTACKAUTHOR': '', 'SERVICEPERFDATA': 'temp=75;70;80;;', 'NOTIFICATIONAUTHORALIAS': '', 'HOST_ADDRESS_4': '127.0.0.1', 'HOSTSTATEID': '0', 'MICROTIME': '1502452826145843', 'SERVICEOUTPUT': 'WARN - 75.0 \xc2\xb0C (warn/crit at 70/80 \xc2\xb0C)', 'HOSTCONTACTGROUPNAMES': 'all', 'HOST_EC_CONTACT': '', 'SERVICECONTACTGROUPNAMES': 'all', 'MAXSERVICEATTEMPTS': '1', 'LASTSERVICEPROBLEMID': '138', 'HOST_FILENAME': '/wato/hosts.mk', 'PREVIOUSSERVICEHARDSTATE': 'OK', 'CONTACTS': '', 'SERVICEDISPLAYNAME': 'Temperature Zone 0', 'HOSTNAME': 'localhost', 'HOST_TAGS': '/wato/ cmk-agent ip-v4 ip-v4-only lan prod site:heute tcp wato', 'NOTIFICATIONTYPE': 'PROBLEM', 'SVC_SL': '', 'SERVICESTATEID': '1', 'LASTHOSTSTATE': 'PENDING', 'SERVICEGROUPNAMES': '', 'HOSTNOTES': '', 'HOSTADDRESS': '127.0.0.1', 'SERVICENOTIFICATIONNUMBER': '1', 'MAXHOSTATTEMPTS': '1'}, {'SERVICEACKCOMMENT': '', 'HOSTPERFDATA': '', 'SERVICEDOWNTIME': '0', 'PREVIOUSSERVICEHARDSTATEID': '0', 'LASTSERVICESTATECHANGE': '1502452826', 'HOSTGROUPNAMES': 'check_mk', 'LASTSERVICESTATE': 'OK', 'LONGSERVICEOUTPUT': '', 'NOTIFICATIONTYPE': 'PROBLEM', 'HOSTPROBLEMID': '0', 'HOSTNOTIFICATIONNUMBER': '0', 'SERVICE_SL': '', 'HOSTSTATE': 'PENDING', 'HOSTACKCOMMENT': '', 'LONGHOSTOUTPUT': '', 'LASTHOSTSTATECHANGE': '0', 'HOSTOUTPUT': '', 'HOSTNOTESURL': '', 'HOSTATTEMPT': '1', 'HOSTNAME': 'localhost', 'NOTIFICATIONAUTHORNAME': '', 'SERVICEDESC': 'Check_MK Agent', 'NOTIFICATIONAUTHOR': '', 'HOSTALIAS': 'localhost', 'PREVIOUSHOSTHARDSTATEID': '0', 'SERVICECONTACTGROUPNAMES': 'all', 'SERVICE_EC_CONTACT': '', 'SERVICEACKAUTHOR': '', 'SERVICEATTEMPT': '1', 'HOSTTAGS': '/wato/ cmk-agent ip-v4 ip-v4-only lan prod site:heute tcp wato', 'SERVICEGROUPNAMES': '', 'HOSTNOTES': '', 'NOTIFICATIONCOMMENT': '', 'HOST_ADDRESS_FAMILY': '4', 'MICROTIME': '1502452826145283', 'LASTHOSTUP': '0', 'PREVIOUSHOSTHARDSTATE': 'PENDING', 'LASTHOSTSTATEID': '0', 'LASTSERVICEOK': '0', 'HOSTADDRESS': '127.0.0.1', 'SERVICEPROBLEMID': '137', 'HOST_SL': '', 'LASTSERVICESTATEID': '0', 'HOSTCHECKCOMMAND': 'check-mk-host-smart', 'HOSTACKAUTHOR': '', 'SERVICEPERFDATA': '', 'HOST_ADDRESS_4': '127.0.0.1', 'HOSTSTATEID': '0', 'HOST_ADDRESS_6': '', 'SERVICEOUTPUT': 'WARN - error: This host is not registered for deployment(!), last update check: 2017-05-22 10:28:43 (warn at 2 days)(!), last agent update: 2017-05-22 09:28:24', 'HOSTCONTACTGROUPNAMES': 'all', 'HOST_EC_CONTACT': '', 'SERVICENOTES': '', 'MAXSERVICEATTEMPTS': '1', 'LASTSERVICEPROBLEMID': '137', 'HOST_FILENAME': '/wato/hosts.mk', 'LASTHOSTSTATE': 'PENDING', 'PREVIOUSSERVICEHARDSTATE': 'OK', 'SERVICECHECKCOMMAND': 'check_mk-check_mk.agent_update', 'SERVICEDISPLAYNAME': 'Check_MK Agent', 'CONTACTS': '', 'HOST_TAGS': '/wato/ cmk-agent ip-v4 ip-v4-only lan prod site:heute tcp wato', 'LASTHOSTPROBLEMID': '0', 'SVC_SL': '', 'SERVICESTATEID': '1', 'SERVICESTATE': 'WARNING', 'NOTIFICATIONAUTHORALIAS': '', 'SERVICENOTESURL': '', 'HOSTDOWNTIME': '0', 'SERVICENOTIFICATIONNUMBER': '1', 'MAXHOSTATTEMPTS': '1'}]",  # noqa: E501
    )
    assert isinstance(
        _execute_automation(site, "notification-analyse", args=["0"]),
        results.NotificationAnalyseResult,
    )
Example #14
0
def test_simple_check_mkevents_call(site: Site, args):
    p = site.execute(
        ["./check_mkevents"] + args + ["somehost"],
        stdout=subprocess.PIPE,
        cwd=site.path("lib/nagios/plugins"),
    )
    output = p.stdout.read() if p.stdout else "<NO STDOUT>"
    assert output == "OK - no events for somehost\n"
    assert p.wait() == 0
Example #15
0
def test_simple_rbn_service_notification(test_log, site: Site):
    site.send_service_check_result("notify-test", "PING", 2, "FAKE CRIT")

    # NOTE: "] " is necessary to get the actual log line and not the external command execution
    test_log.check_logged(
        "] SERVICE NOTIFICATION: check-mk-notify;notify-test;PING;CRITICAL;check-mk-notify;FAKE CRIT"
    )
    test_log.check_logged("] SERVICE NOTIFICATION: hh;notify-test;PING;CRITICAL;mail;FAKE CRIT")
    test_log.check_logged(
        "] SERVICE NOTIFICATION RESULT: hh;notify-test;PING;OK;mail;Spooled mail to local mail transmission agent;"
    )
Example #16
0
def test_simple_rbn_host_notification(test_log, site: Site):
    site.send_host_check_result("notify-test", 1, "FAKE DOWN", expected_state=1)

    # NOTE: "] " is necessary to get the actual log line and not the external command execution
    test_log.check_logged(
        "] HOST NOTIFICATION: check-mk-notify;notify-test;DOWN;check-mk-notify;FAKE DOWN"
    )
    test_log.check_logged("] HOST NOTIFICATION: hh;notify-test;DOWN;mail;FAKE DOWN")
    test_log.check_logged(
        "] HOST NOTIFICATION RESULT: hh;notify-test;OK;mail;Spooled mail to local mail transmission agent;"
    )
def _send_child_down(scenario, site: Site, log):
    # - Set child down, expect DOWN notification
    site.send_host_check_result("notify-test-child", STATE_DOWN, "DOWN")
    log.check_logged("HOST ALERT: notify-test-child;DOWN;HARD;1;DOWN")

    if scenario.core == "cmc":
        # CMC: Send a new check result for the parent to make the CMC create the host notification
        # for the child
        site.send_host_check_result("notify-test-parent", STATE_UP, "UP")

    log.check_logged("HOST NOTIFICATION: check-mk-notify;notify-test-child;DOWN;check-mk-notify;")
def test_down_child_becomes_unreachable_and_down_again(
    unreachable_enabled, site: Site, initial_state
):
    with WatchLog(site) as log:
        # - Set child down, expect DOWN notification
        _send_child_down(site, log)

        # - Set parent down, expect DOWN notification for parent and UNREACHABLE notification for child
        _send_parent_down(site, log)

        # Difference beween nagios/cmc: when sending DOWN via PROCESS_HOST_CHECK_RESULT
        # the nagios core needs another child down check result to report it as unreachable.
        if site.core_name() == "cmc":
            log.check_logged("HOST ALERT: notify-test-child;UNREACHABLE;HARD;1;")

            if unreachable_enabled:
                log.check_logged(
                    "HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;"
                )
            # TODO: Can not test this because it drains too many entries from the log. WatchLog could deal
            # with this by readding the read lines after succeeded test or similar
            # else:
            #    log.check_not_logged("HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;")

            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
            )

        elif site.core_name() == "nagios":
            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
            )

            site.send_host_check_result(
                "notify-test-child", STATE_DOWN, "DOWN", expected_state=STATE_UNREACHABLE
            )
            log.check_logged("HOST ALERT: notify-test-child;UNREACHABLE;HARD;1;")

            if unreachable_enabled:
                log.check_logged(
                    "HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;"
                )

        # - Set parent up, expect UP notification
        _send_parent_recovery(site, log)

        # - Next child check DOWN
        #   cmc: expect no notification (till next parent check confirms UP)
        #   nagios: expect notification without
        site.send_host_check_result("notify-test-child", STATE_DOWN, "DOWN")
        log.check_logged("HOST ALERT: notify-test-child;DOWN;HARD;1;")

        if site.core_name() == "cmc":
            # - Set parent UP (again), expect DOWN notification for child
            site.send_host_check_result("notify-test-parent", STATE_UP, "UP")

        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-child;DOWN;check-mk-notify;"
        )
Example #19
0
def test_www_dir(site: Site):
    web = CMKWebSession(site)

    # unauthenticated = denied
    web.get("/%s/testfile" % site.id, expected_code=401)

    try:
        site.write_text_file("var/www/testfile.html", "123")
        assert web.get("/%s/testfile.html" % site.id,
                       auth=("cmkadmin", "cmk")).text == "123"
    finally:
        site.delete_file("var/www/testfile.html")
Example #20
0
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
from cmk.gui import main_modules
main_modules.load_plugins()
import cmk.gui.cron as cron
print("x" in [ f.__name__ for f in cron.multisite_cronjobs])
    """,
    )
    yield path
    site.delete_file(path)
Example #21
0
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
from cmk.gui import main_modules
main_modules.load_plugins()
from cmk.gui.plugins.wato.utils import rulespec_registry
print("test" in rulespec_registry)
    """,
    )
    yield path
    site.delete_file(path)
Example #22
0
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
import cmk.gui.modules
cmk.gui.modules.load_plugins()
from cmk.gui.plugins.sidebar.utils import snapin_registry
print("test" in snapin_registry)
    """,
    )
    yield path
    site.delete_file(path)
Example #23
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/cron/test_plugin.py"
    site.write_text_file(
        path,
        """
from cmk.gui.plugins.cron import register_job
def x():
    pass
register_job(x)
""",
    )
    yield path
    site.delete_file(path)
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
from cmk.post_rename_site.main import load_plugins
load_plugins()
from cmk.post_rename_site.registry import rename_action_registry
print("test" in rename_action_registry)
    """,
    )
    yield path
    site.delete_file(path)
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
from cmk.gui import main_modules
main_modules.load_plugins()
from cmk.gui.plugins.metrics.utils import metric_info
print("test" in metric_info)
    """,
    )
    yield path
    site.delete_file(path)
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
from cmk.gui import main_modules
main_modules.load_plugins()
import cmk.gui.openapi
print(cmk.gui.openapi.x)
    """,
    )
    yield path
    site.delete_file(path)
Example #27
0
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
import cmk.gui.modules
cmk.gui.modules.load_plugins()
from cmk.gui.plugins.webapi.utils import api_call_collection_registry
print("TestCollection" in api_call_collection_registry)
    """,
    )
    yield path
    site.delete_file(path)
Example #28
0
def fixture_test_script(site: Site) -> Iterator[str]:
    path = "test_script"
    site.write_text_file(
        path,
        """
import cmk.gui.modules
cmk.gui.modules.load_plugins()
import cmk.gui.config as config
print(config.get_default_config()["x"])
    """,
    )
    yield path
    site.delete_file(path)
Example #29
0
def test_automation_set_autochecks(test_cfg, site: Site):
    hostname = HostName("blablahost")
    new_items: SetAutochecksTable = {
        ("df", "xxx"): ("Filesystem xxx", {}, {
            "xyz": "123"
        }, [hostname]),
        ("uptime", None): ("Uptime", None, {}, [hostname]),
    }

    try:
        assert isinstance(
            _execute_automation(
                site,
                "set-autochecks",
                args=[hostname],
                stdin=repr(new_items),
            ),
            results.SetAutochecksResult,
        )

        autochecks_file = "%s/%s.mk" % (cmk.utils.paths.autochecks_dir,
                                        hostname)
        assert os.path.exists(autochecks_file)

        data = autochecks.AutochecksStore(hostname).read()
        services = [(
            (str(s.check_plugin_name), s.item),
            s.parameters,
            s.service_labels,
        ) for s in data]
        assert sorted(services) == [
            (
                ("df", "xxx"),
                {},
                {
                    "xyz": "123"
                },
            ),
            (
                ("uptime", None),
                None,
                {},
            ),
        ]

        assert site.file_exists("var/check_mk/autochecks/%s.mk" % hostname)
    finally:
        if site.file_exists("var/check_mk/autochecks/%s.mk" % hostname):
            site.delete_file("var/check_mk/autochecks/%s.mk" % hostname)
def test_down_child_becomes_unreachable_then_up(scenario, site: Site, initial_state):
    with WatchLog(site, scenario.log, default_timeout=scenario.log_timeout) as log:
        # - Set child down, expect DOWN notification
        site.send_host_check_result("notify-test-child", STATE_DOWN, "DOWN")
        log.check_logged("HOST ALERT: notify-test-child;DOWN;HARD;1;DOWN")

        if scenario.core == "cmc":
            # CMC: Send a new check result for the parent to make the CMC create the host notification
            # for the child
            site.send_host_check_result("notify-test-parent", STATE_UP, "UP")

        log.check_logged(
            "HOST NOTIFICATION: check-mk-notify;notify-test-child;DOWN;check-mk-notify;"
        )

        # - Set parent down, expect DOWN notification for parent and UNREACHABLE notification for child
        site.send_host_check_result("notify-test-parent", STATE_DOWN, "DOWN")
        log.check_logged("HOST ALERT: notify-test-parent;DOWN;HARD;1;DOWN")

        # Difference beween nagios/cmc: when sending DOWN via PROCESS_HOST_CHECK_RESULT
        # the nagios core needs another child down check result to report it as unreachable.
        if scenario.core == "cmc":
            log.check_logged("HOST ALERT: notify-test-child;UNREACHABLE;HARD;1;")

            if scenario.unreachable_enabled:
                log.check_logged(
                    "HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;"
                )
            # TODO: Can not test this because it drains too many entries from the log. WatchLog could deal
            # with this by readding the read lines after succeeded test or similar
            # else:
            #    log.check_not_logged("HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;")

            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
            )

        elif scenario.core == "nagios":
            log.check_logged(
                "HOST NOTIFICATION: check-mk-notify;notify-test-parent;DOWN;check-mk-notify;"
            )

            site.send_host_check_result(
                "notify-test-child", STATE_DOWN, "DOWN", expected_state=STATE_UNREACHABLE
            )
            log.check_logged("HOST ALERT: notify-test-child;UNREACHABLE;HARD;1;")

            if scenario.unreachable_enabled:
                log.check_logged(
                    "HOST NOTIFICATION: check-mk-notify;notify-test-child;UNREACHABLE;check-mk-notify;"
                )

        # - Set child up, expect:
        #   cmc: pending UP notification, and sent up notification after next parent check
        #   nagios: UP notification
        _send_child_recovery(scenario, site, log)

        # - Set parent up, expect UP notification
        _send_parent_recovery(scenario, site, log)