Пример #1
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)
Пример #2
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)
Пример #3
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)
Пример #4
0
def test_automation_update_dns_cache(test_cfg, site: Site):
    cache_path = "var/check_mk/ipaddresses.cache"

    if site.file_exists(cache_path):
        site.delete_file(cache_path)

    try:
        site.openapi.create_host("update-dns-cache-host")
        site.openapi.create_host("localhost")

        site.write_text_file(cache_path, "{('bla', 4): '127.0.0.1'}")

        result = _execute_automation(site, "update-dns-cache")
        assert isinstance(result, results.UpdateDNSCacheResult)

        assert result.n_updated > 0
        assert result.failed_hosts == ["update-dns-cache-host"]

        assert site.file_exists(cache_path)

        cache = eval(site.read_file(cache_path))  # pylint:disable=eval-used
        assert isinstance(cache, dict)
        assert cache[("localhost", 4)] == "127.0.0.1"
        assert ("bla", 4) not in cache

    finally:
        site.openapi.delete_host("localhost")
        site.openapi.delete_host("update-dns-cache-host")
Пример #5
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)
Пример #6
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 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)
Пример #7
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")
Пример #8
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")
Пример #9
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)
Пример #10
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.metrics.utils import metric_info
print("test" in metric_info)
    """,
    )
    yield path
    site.delete_file(path)
Пример #11
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)
Пример #12
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)
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)
Пример #14
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.openapi
print(cmk.gui.openapi.x)
    """,
    )
    yield path
    site.delete_file(path)
Пример #15
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)
Пример #16
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)
Пример #17
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)
Пример #18
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)
Пример #19
0
def test_automation_get_configuration(test_cfg, site: Site):
    variable_names = [
        "agent_port",
    ]

    automation_result = _execute_automation(
        site,
        "get-configuration",
        stdin=repr(variable_names),
    )
    assert isinstance(automation_result, results.GetConfigurationResult)
    assert automation_result.result["agent_port"] == 6556

    try:
        site.write_text_file("etc/check_mk/main.mk", "agent_port = 6558")

        result = _execute_automation(site,
                                     "get-configuration",
                                     stdin=repr(variable_names)).result
        assert result["agent_port"] == 6558

        site.write_text_file("etc/check_mk/conf.d/agent-port.mk",
                             "agent_port = 1234")

        result = _execute_automation(site,
                                     "get-configuration",
                                     stdin=repr(variable_names)).result
        assert result["agent_port"] == 6558

        site.write_text_file("etc/check_mk/main.mk", "")

        result = _execute_automation(site,
                                     "get-configuration",
                                     stdin=repr(variable_names)).result
        assert result["agent_port"] == 6556

        site.delete_file("etc/check_mk/conf.d/agent-port.mk")

        result = _execute_automation(site,
                                     "get-configuration",
                                     stdin=repr(variable_names)).result
        assert result["agent_port"] == 6556
    finally:
        if site.file_exists("etc/check_mk/conf.d/agent-port.mk"):
            site.delete_file("etc/check_mk/conf.d/agent-port.mk")

        site.write_text_file("etc/check_mk/main.mk", "")
Пример #20
0
def cfg_setup_fixture(request, web, site: Site):
    hostname = "test-prediction"

    # Enforce use of the pre-created RRD file from the git. The restart of the core
    # is needed to make it renew it's internal RRD file cache
    site.makedirs("var/check_mk/rrd/test-prediction")
    with open(site.path("var/check_mk/rrd/test-prediction/CPU_load.rrd"), "wb") as f:
        f.write(
            Path(
                repo_path(), "tests", "integration", "cmk", "base", "test-files", "CPU_load.rrd"
            ).read_bytes()
        )

    site.write_text_file(
        "var/check_mk/rrd/test-prediction/CPU_load.info",
        Path(
            repo_path(), "tests", "integration", "cmk", "base", "test-files", "CPU_load.info"
        ).read_text(),
    )

    site.restart_core()

    create_linux_test_host(request, site, "test-prediction")

    site.write_text_file(
        "etc/check_mk/conf.d/linux_test_host_%s_cpu_load.mk" % hostname,
        """
globals().setdefault('custom_checks', [])

custom_checks = [
    ( {'service_description': u'CPU load', 'has_perfdata': True}, [], ALL_HOSTS, {} ),
] + custom_checks
""",
    )

    site.activate_changes_and_wait_for_core_reload()

    yield

    # Cleanup
    site.delete_file("etc/check_mk/conf.d/linux_test_host_%s_cpu_load.mk" % hostname)
    site.activate_changes_and_wait_for_core_reload()
    site.delete_dir("var/check_mk/rrd")
Пример #21
0
def cfg_setup_fixture(request, web, site: Site):  # noqa: F811 # pylint: disable=redefined-outer-name
    hostname = "test-prediction"

    # Enforce use of the pre-created RRD file from the git. The restart of the core
    # is needed to make it renew it's internal RRD file cache
    site.makedirs("var/check_mk/rrd/test-prediction")
    with open(site.path("var/check_mk/rrd/test-prediction/CPU_load.rrd"),
              "wb") as f:
        f.write(
            open(
                "%s/tests/integration/cmk/base/test-files/CPU_load.rrd" %
                repo_path(), "rb").read())

    site.write_text_file(
        "var/check_mk/rrd/test-prediction/CPU_load.info",
        open("%s/tests/integration/cmk/base/test-files/CPU_load.info" %
             repo_path()).read(),
    )

    site.restart_core()

    create_linux_test_host(request, web, site, "test-prediction")

    site.write_text_file(
        "etc/check_mk/conf.d/linux_test_host_%s_cpu_load.mk" % hostname,
        """
globals().setdefault('custom_checks', [])

custom_checks = [
    ( {'service_description': u'CPU load', 'has_perfdata': True}, [], ALL_HOSTS, {} ),
] + custom_checks
""",
    )

    web.activate_changes()

    yield

    # Cleanup
    site.delete_file("etc/check_mk/conf.d/linux_test_host_%s_cpu_load.mk" %
                     hostname)
    site.delete_dir("var/check_mk/rrd")
def initial_state_fixture(site: Site, scenario):
    # Before each test: Set to initial state: Both UP
    site.send_host_check_result("notify-test-child", 0, "UP")
    site.send_host_check_result("notify-test-parent", 0, "UP")

    # Before each test: Clear logs
    if scenario.core == "cmc":
        # The command is processed asynchronously -> Wait for completion
        inode_before = os.stat(site.path("var/check_mk/core/history")).st_ino
        site.live.command("[%d] ROTATE_LOGFILE" % time.time())

        def rotated_log():
            try:
                return inode_before != os.stat(site.path("var/check_mk/core/history")).st_ino
            except OSError as e:
                if e.errno == errno.ENOENT:
                    return False
                raise e

        wait_until(rotated_log, timeout=10)
    else:
        site.delete_file("var/nagios/nagios.log")
Пример #23
0
def test_cfg_fixture(web, site: Site, backup_path):
    site.ensure_running()

    cfg = {
        "jobs": {
            "testjob": {
                "compress": False,
                "encrypt": None,
                "schedule": None,
                "target": "test-target",
                "title": "T\xe4stjob",
            },
            "testjob-no-history": {
                "no_history": True,
                "compress": False,
                "encrypt": None,
                "schedule": None,
                "target": "test-target",
                "title": "T\xe4stjob no history",
            },
            "testjob-compressed": {
                "compress": True,
                "encrypt": None,
                "schedule": None,
                "target": "test-target",
                "title": "T\xe4stjob",
            },
            "testjob-encrypted": {
                "compress": False,
                "encrypt": "C0:4E:D4:4B:B4:AB:8B:3F:B4:09:32:CE:7D:A6:CF:76",
                "schedule": None,
                "target": "test-target",
                "title": "T\xe4stjob",
            },
        },
        "targets": {
            "test-target": {
                "remote": ("local", {
                    "is_mountpoint": False,
                    "path": backup_path
                }),
                "title": "t\xe4rget",
            },
        },
    }
    site.write_text_file("etc/check_mk/backup.mk", pformat(cfg))

    keys = {
        1: {
            "alias":
            "lala",
            "certificate":
            "-----BEGIN CERTIFICATE-----\nMIIC1jCCAb4CAQEwDQYJKoZIhvcNAQEFBQAwMTEcMBoGA1UECgwTQ2hlY2tfTUsg\nU2l0ZSBoZXV0ZTERMA8GA1UEAwwIY21rYWRtaW4wHhcNMTcwODEzMjA1MDQ3WhcN\nNDcwODA2MjA1MDQ3WjAxMRwwGgYDVQQKDBNDaGVja19NSyBTaXRlIGhldXRlMREw\nDwYDVQQDDAhjbWthZG1pbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nAMLj3TeBAC8/I1iK1MfGW7OjxEUNsM8u3LV80wMlzosgNbszoGWsAwvJzCctZKia\n6C9I4gcEr7y3gwdKWX8ic9qJ/ymG2xD9FAfe2BjqCifKzV3YXmyaHLTngIDSDc5C\nDTLlEV/ncGKheUbvaTQHi2MxOtdouKFaFEYwVFR0TViiNgSA91ERzrz79ABemMDW\nzysK5CMKDj5DhaYlNxz+Rs7qRUY3w3iz0sKWK7yvxNnJCkrVVfp/jlt4RMf6Jr1g\nINFn9MgZZVJUvC6u2zU0q9/g/pa/U5Ae9iW5WI1QnrtDq+sl55EmjVOfMb5V2TEX\ntdMeKLHCxO+uwBBeLy/uwlUCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAMiK6T6sY\nXehjEA3hcB8X3sada35nG9bZll5IJj1JXLR3iwyStVNeq7ZRWvv/QtWJWSFitf2Q\nBfuNBSgwoZFvMPMv9JXqJG3TYi78kUA0Vx+87TFOSRu93wcvm3etlRdO4OGpIbsk\njBBQ6MnHvR2zUyv6SL144mEcBYYof2NeYtAv+5+OQwyMwLmNTCS/Lz7+TO7vnBmx\nSqlPKXenUj+2sHU/5WjHLzlxWLIr7PpanUr1KmkF7oRAgHQb1tsamqK2KERq68+J\nDIQBtcrEd/kz9N+RW2gnqcjmmhQYP9XP5ZLCTC582EgrhrjBgf2UCIzZJVFz+Jfj\nitd0Om685s7wNg==\n-----END CERTIFICATE-----\n",  # noqa: E501
            "date":
            1502657447.534146,
            "not_downloaded":
            True,
            "owner":
            "cmkadmin",
            "private_key":
            "-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFHzBJBgkqhkiG9w0BBQ0wPDAbBgkqhkiG9w0BBQwwDgQIbwWAeEGqIF4CAggA\nMB0GCWCGSAFlAwQBKgQQZdkJLaEpboSu9Gb+yxb9AgSCBNCrLSgQvQC5cv5wiv3r\nDyGZ3pYhDXVPLvtedpvf/PVeBJ9750li6HzH9oH7hyWkXRBBCRcXzcE/VFkIezuV\nBBfkIIibKVh7MePmAsgc9gSTZadpuNx4PHiauJpicj4n3ie0WtpdQrJjSMQRppg/\nA/jzDuJkLCnFVWrhPuD635dsfpjOwhuOlVyYtTUwp4F5/jtmLbhq2fhSEDX43uHH\nHHM4NDu3EbwE8Uzbc0rsx0Qyo5Pk4/dAp30UKtMN/Iv37Z/EjPYk2jKnGHD62Xal\nHwnSkPD39o66BdxVBNc7YCR7BPGp6XNmOPDoRRT0bU1TrlH4sK2KsRyQWwb8njdF\n8jawAXD3RQPyyq7eq+sb6g9c81zD6bwBbVcz26oqGS9oNzliKWfJ/yVLhUXYNYO5\naV1MhpAvApgIpqSPPFlhCl1FnULrY1wl/57GS2/EqDUdhzQDlr1F3Ym+yMlcf1gm\noy72GnDLH66x3NYxo+ylPQa/XrTAyYbr12IPGFONuBrVuSH+b4kV1Rs8ikFTYdgt\nDBmRRQvBxh8dKD+vurfLX2XY2gO3WEAWgD7+HPOoW8PClc9/Nf6giZMOWQvqvcEk\nC18Yv87lLi5lcrhDs9ZgtUUgaW4eue7AVLKAKq74KKDnSFajF7fJmUU2Mbf69cAF\nDtwUjEbocVw/UUUpVH+B42wq+DRhrg++r4JoSn2ZvQ6ltSAkPUuR8Vctp1zTYlZJ\nl7CN3Ua+LFSMDwI9nn275FxbWnMV69TrT7gu5UrFMRsOWpPSApeTTYgPazRbuw/O\ndrOfjTlmWU1FdVSkptwMB+3nQ/8EiXMrBVipSULShGEoJ8focqHRTH5EdSPBC9e0\ne5InVX7b0ARRgCC1TuLL/cmoiOvKqRetRdzaaoaOxt40Kg4u4RFFX7HgzKQ5uIvx\nnMKLVH64lU+IeZAztY7ypjZU8xY5Cgn4JVIbSmMm573uw0uvULp7cW4R3nyeHg1T\n3ZQy609C5WwkGjgH3tV2IdxwHVzZrMv8hiEPT3nuq8fxCcipa9Q1CzoibLj909pQ\ng4upWRPvuTYyOWqCHGhUVaLXGFuFlCXwMFVUlqLbEFeKDejRhQxacCmpyYljiKCQ\nonbUVrzqE8N+Tj0W9GsmKRQUBAbDtEnU2YvDdXzG6noyS+fyrnDkF8/yt7Tdrm4a\ntSKIusvZ3xFloCLBISG+1Cm67qLxaUuol9teiKpx2IzEQycj5ZA63FQ2wFZ+kfk3\nNAhaUfXToKLksx8pojldFo4g1tiX3oGPdblgQ10xgF+eiXzcNiRbce1X2Sfg/urk\nXTN8d5WZuHA4xj0hLH/Xz1CAJjtoEpafiEWB3nmZC4/0poA6MRX1EhCQM5MgeHwo\niaNvgptDQ113MW9FnbdLn5sAoiJ6RWmK8TIW8BJSfnnKyl0lBJG0n5my7rP6ZO1r\nTGkV8cdwy7AoCWQTlfKY7QKHCZMXlyJVSVxuPEnityS+AKKxCYSL3zbPgyXvoFcB\n0XQYTpmEtPM9sJO7VbRYPijjVDLwfe6zPnqw585Fa4W1VtzxW+Y4oKgu6Cn/oGZm\npZ1+gORJtMMD2841ut3QbihY/JYKcCstzFIBzlzAkWHwRI+/wXc9QGtwk1GWriUo\nNcilHP9yv0aXGu8kZ77cd0K18w==\n-----END ENCRYPTED PRIVATE KEY-----\n",  # noqa: E501
        }
    }

    site.write_text_file("etc/check_mk/backup_keys.mk",
                         "keys.update(%s)" % pformat(keys))

    yield None

    #
    # Cleanup code
    #
    site.delete_file("etc/check_mk/backup_keys.mk")
    site.delete_file("etc/check_mk/backup.mk")

    site.ensure_running()
Пример #24
0
def plugin_path(site: Site) -> Iterator[str]:
    path = "local/lib/check_mk/gui/plugins/openapi/test_plugin.py"
    site.write_text_file(path, test_plugin_code)
    yield path
    site.delete_file(path)
Пример #25
0
def test_cfg_fixture(site: Site, web):
    print("Applying default config")
    site.openapi.create_host(
        "modes-test-host",
        attributes={
            "ipaddress": "127.0.0.1",
        },
    )
    site.openapi.create_host(
        "modes-test-host2",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "test",
        },
    )
    site.openapi.create_host(
        "modes-test-host3",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "test",
        },
    )
    site.openapi.create_host(
        "modes-test-host4",
        attributes={
            "ipaddress": "127.0.0.1",
            "tag_criticality": "offline",
        },
    )

    site.write_text_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_text_file("var/check_mk/agent_output/modes-test-host",
                         get_standard_linux_agent_output())
    site.write_text_file("var/check_mk/agent_output/modes-test-host2",
                         get_standard_linux_agent_output())
    site.write_text_file("var/check_mk/agent_output/modes-test-host3",
                         get_standard_linux_agent_output())

    web.discover_services(
        "modes-test-host")  # Replace with RestAPI call, see CMK-9249
    web.discover_services(
        "modes-test-host2")  # Replace with RestAPI call, see CMK-9249
    web.discover_services(
        "modes-test-host3")  # Replace with RestAPI call, see CMK-9249

    try:
        site.activate_changes_and_wait_for_core_reload()
        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")

        site.openapi.delete_host("modes-test-host")
        site.openapi.delete_host("modes-test-host2")
        site.openapi.delete_host("modes-test-host3")
        site.openapi.delete_host("modes-test-host4")

        site.activate_changes_and_wait_for_core_reload()
Пример #26
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/config/test_plugin.py"
    site.write_text_file(path, 'x = "legacy"\n')
    yield path
    site.delete_file(path)
Пример #27
0
def plugin_path(site: Site) -> Iterator[str]:
    path = "local/lib/check_mk/gui/plugins/config/test_plugin.py"
    site.write_text_file(path, 'x = "yo"\n')
    yield path
    site.delete_file(path)
Пример #28
0
def test_test_check_1_all_rule(
    request, site: 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_text_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_text_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
    entries = autochecks.AutochecksStore(HostName(host_name)).read()

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

    # And now overwrite the setting in the config
    site.write_text_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)
    entries = autochecks.AutochecksStore(HostName(host_name)).read()
    for entry in entries:
        if str(entry.check_plugin_name) == "test_check_2":
            assert entry.item == (
                "[Parameters({'levels': (1, 2)})," " Parameters({'default': 42})]"
            )
            break
    else:
        raise AssertionError('"test_check_2" not discovered')
Пример #29
0
def legacy_plugin_path(site: Site) -> Iterator[str]:
    path = "local/share/check_mk/web/plugins/sidebar/test_plugin.py"
    site.write_text_file(path, test_plugin_code)
    yield path
    site.delete_file(path)
def plugin_path(site: Site) -> Iterator[str]:
    path = "local/lib/check_mk/post_rename_site/plugins/actions/test_plugin.py"
    site.write_text_file(path, test_plugin_code)
    yield path
    site.delete_file(path)