def test_check_crash_report_read_snmp_info(monkeypatch):
    Scenario().apply(monkeypatch)
    config.load_checks(check_api.get_check_api_context, [
        "%s/uptime" % cmk.utils.paths.checks_dir,
        "%s/snmp_uptime" % cmk.utils.paths.checks_dir
    ])

    cache_path = Path(cmk.utils.paths.data_source_cache_dir, "snmp",
                      "testhost")
    cache_path.parent.mkdir(parents=True, exist_ok=True)  # pylint: disable=no-member
    with cache_path.open("w", encoding="utf-8") as f:
        f.write(u"[]\n")

    try:
        raise Exception("DING")
    except Exception:
        crash = crash_reporting.CheckCrashReport.from_exception_and_context(
            hostname="testhost",
            check_plugin_name="snmp_uptime",
            item=None,
            is_manual_check=False,
            params=None,
            description=u"Uptime",
            info="X",
            text=u"Output",
        )

    assert crash.agent_output is None
    assert crash.snmp_info == u"[]\n"
Exemplo n.º 2
0
def test_test_check_2(request, test_cfg, site, web):
    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")
        if site.file_exists("var/check_mk/autochecks/modes-test-host.mk"):
            site.delete_file("var/check_mk/autochecks/modes-test-host.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",
}
""")

    site.write_file("var/check_mk/agent_output/modes-test-host",
                    "<<<test_check_2>>>\n1 2\n")

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])

    # 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("modes-test-host")

    # Should have discovered nothing so far
    assert site.read_file(
        "var/check_mk/autochecks/modes-test-host.mk") == "[\n]\n"

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

    # 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("modes-test-host")

    # Verify that the discovery worked as expected
    assert site.read_file("var/check_mk/autochecks/modes-test-host.mk") == """[
Exemplo n.º 3
0
def test_host_config_snmp_check_interval(monkeypatch, hostname, section_name, result):
    config.load_checks(check_api.get_check_api_context, ["checks/uptime", "checks/snmp_uptime"])
    ts = Scenario().add_host(hostname)
    ts.set_ruleset("snmp_check_interval", [
        (("snmp_uptime", 4), [], ["testhost2"], {}),
    ])
    config_cache = ts.apply(monkeypatch)
    assert config_cache.get_host_config(hostname).snmp_check_interval(section_name) == result
Exemplo n.º 4
0
def check_info(request, check_name):
    if not config._all_checks_loaded:
        print "Load all checks"
        config._initialize_data_structures()
        filelist = config.get_plugin_paths('/src/tests/fixtures/checks')
        config.load_checks(check_api.get_check_api_context, filelist)
        config._all_checks_loaded = True

    return config.check_info[check_name]
Exemplo n.º 5
0
def test_config_cache_icons_and_actions(monkeypatch, hostname, result):
    config.load_checks(check_api.get_check_api_context, ["checks/ps"])
    ts = Scenario().add_host(hostname)
    ts.set_ruleset("service_icons_and_actions", [
        ("icon1", [], ["testhost2"], "CPU load$", {}),
        ("icon1", [], ["testhost2"], "CPU load$", {}),
        ("icon2", [], ["testhost2"], "CPU load$", {}),
    ])
    config_cache = ts.apply(monkeypatch)
    assert sorted(config_cache.icons_and_actions_of_service(hostname, "CPU load", "ps",
                                                            {})) == sorted(result)
Exemplo n.º 6
0
def test_get_check_table(monkeypatch, hostname, expected_result):
    autochecks = {
        "ping-host": [("smart.temp", "bla", {})],
        "autocheck-overwrite": [
            ('smart.temp', '/dev/sda', {
                "is_autocheck": True
            }),
            ('smart.temp', '/dev/sdb', {
                "is_autocheck": True
            }),
        ],
        "ignore-not-existing-checks": [
            ("bla.blub", "ITEM", {}),
        ],
        "node1": [("smart.temp", "auto-clustered", {}),
                  ("smart.temp", "auto-not-clustered", {})],
    }

    ts = Scenario().add_host(hostname, tags={"criticality": "test"})
    ts.add_host("ping-host", tags={"agent": "no-agent"})
    ts.add_host("node1")
    ts.add_cluster("cluster1", nodes=["node1"])
    ts.set_option(
        "static_checks",
        {
            "temperature": [
                (('smart.temp', '/dev/sda', {}), [],
                 ["no-autochecks", "autocheck-overwrite"]),
                (('blub.bla', 'ITEM', {}), [], ["ignore-not-existing-checks"]),
                (('smart.temp', 'ITEM1', {}), [], ["ignore-disabled-rules"], {
                    "disabled": True
                }),
                (('smart.temp', 'ITEM2', {}), [], ["ignore-disabled-rules"]),
                (('smart.temp', '/dev/sda', {
                    "rule": 1
                }), [], ["static-check-overwrite"]),
                (('smart.temp', '/dev/sda', {
                    "rule": 2
                }), [], ["static-check-overwrite"]),
                (('smart.temp', 'static-node1', {}), [], ["node1"]),
                (('smart.temp', 'static-cluster', {}), [], ["cluster1"]),
            ]
        },
    )
    ts.set_ruleset("clustered_services", [
        ([], ['node1'], [u'Temperature SMART auto-clustered$']),
    ])
    config_cache = ts.apply(monkeypatch)
    monkeypatch.setattr(config_cache, "get_autochecks_of",
                        lambda h: autochecks.get(h, []))

    config.load_checks(check_api.get_check_api_context, ["checks/smart"])
    assert check_table.get_check_table(hostname) == expected_result
Exemplo n.º 7
0
    def load(self, file_names=None):
        """Load either all check plugins or the given file_names"""
        import cmk_base.config as config
        import cmk_base.check_api as check_api
        import cmk.utils.paths

        if file_names is None:
            config.load_all_checks(
                check_api.get_check_api_context)  # loads all checks
        else:
            config._initialize_data_structures()
            config.load_checks(check_api.get_check_api_context, [
                os.path.join(cmk.utils.paths.checks_dir, f) for f in file_names
            ])

        return self
Exemplo n.º 8
0
def test_read_autochecks_of(monkeypatch, autochecks_content, expected_result):
    config.load_checks(check_api.get_check_api_context,
                       ["checks/df", "checks/cpu", "checks/chrony", "checks/lnx_if"])

    ts = Scenario().add_host("host")
    ts.apply(monkeypatch)

    autochecks_file = Path(cmk.utils.paths.autochecks_dir).joinpath("host.mk")
    with autochecks_file.open("w", encoding="utf-8") as f:  # pylint: disable=no-member
        f.write(autochecks_content)

    if expected_result is MKGeneralException:
        with pytest.raises(MKGeneralException):
            autochecks.read_autochecks_of("host")
        return

    result = autochecks.read_autochecks_of("host")
    assert result == expected_result

    # Check that all items are unicode strings
    assert all(not isinstance(e[1], str) for e in result)
Exemplo n.º 9
0
def test_get_cmk_passive_service_attributes(monkeypatch, hostname, result):
    config.load_checks(check_api.get_check_api_context, ["checks/cpu"])

    ts = Scenario().add_host("localhost")
    ts.add_host("blub")
    ts.set_option(
        "extra_service_conf", {
            "contact_groups": [
                (u'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_spec = core_config.get_cmk_passive_service_attributes(
        config_cache, host_config, "CPU load", "cpu.loads", {}, check_mk_attrs)
    assert service_spec == result
Exemplo n.º 10
0
def test_test_check_1(request, test_cfg, site, web):

    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")

        if site.file_exists("var/check_mk/autochecks/modes-test-host.mk"):
            site.delete_file("var/check_mk/autochecks/modes-test-host.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"
}
""")

    site.write_file("var/check_mk/agent_output/modes-test-host",
                    "<<<test_check_1>>>\n1 2\n")

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])

    # 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"]

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

    # Verify that the discovery worked as expected
    assert site.read_file("var/check_mk/autochecks/modes-test-host.mk") == """[
  ('test_check_1', None, test_check_1_default_levels),
]
"""

    # Now execute the check function to verify the variable is available
    p = site.execute(["cmk", "-nv", "modes-test-host"],
                     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", "modes-test-host"],
                     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
Exemplo n.º 11
0
def test_check_factory_settings(request, test_cfg, site, web):
    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")
        if site.file_exists("var/check_mk/autochecks/modes-test-host.mk"):
            site.delete_file("var/check_mk/autochecks/modes-test-host.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",
}
""")

    site.write_file("var/check_mk/agent_output/modes-test-host",
                    "<<<test_check_3>>>\n1 2\n")

    config.load_checks(check_api.get_check_api_context,
                       ["%s/%s" % (site.root, test_check_path)])

    # 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("modes-test-host")

    # Verify that the discovery worked as expected
    assert site.read_file("var/check_mk/autochecks/modes-test-host.mk") == """[
  ('test_check_3', None, {}),
]
"""

    # Now execute the check function to verify the variable is available
    p = site.execute(["cmk", "-nv", "modes-test-host"],
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    assert "OK - {'param1': 123}\n" 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_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", "modes-test-host"],
                     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