def test_mgmt_board_ip_addresses( monkeypatch, protocol, cred_attribute, credentials, tags, host_attributes, ipaddresses, ipv6addresses, ip_address_result, ): hostname = "mgmt-host" ts = Scenario() ts.add_host(hostname, tags=tags) ts.set_option("host_attributes", {hostname: host_attributes}) ts.set_option("ipaddresses", ipaddresses) ts.set_option("ipv6addresses", ipv6addresses) ts.set_option("management_protocol", {hostname: protocol}) ts.set_option(cred_attribute, {hostname: credentials}) config_cache = ts.apply(monkeypatch) host_config = config_cache.get_host_config(hostname) assert host_config.has_management_board assert host_config.management_protocol == protocol assert host_config.management_address == ip_address_result assert host_config.management_credentials == credentials
def test__rename_discovered_host_label_files_do_not_overwrite( monkeypatch: pytest.MonkeyPatch, uc: update_config.UpdateConfig, ) -> None: ts = Scenario() ts.add_host("abc.d") ts.apply(monkeypatch) host_name = "abc.d" old_path = (cmk.utils.paths.discovered_host_labels_dir / host_name).with_suffix(".mk") new_path = cmk.utils.paths.discovered_host_labels_dir / (host_name + ".mk") old_path.parent.mkdir(exist_ok=True, parents=True) with old_path.open("w") as f: f.write("{}\n") assert old_path.exists() with new_path.open("w") as f: f.write("{}\n") assert new_path.exists() uc._rename_discovered_host_label_files() assert old_path.exists() assert new_path.exists()
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
def test_analyse_host(monkeypatch): automation = automations.AutomationAnalyseHost() ts = Scenario() ts.add_host("test-host") ts.set_option( "host_labels", { "test-host": { "explicit": "ding", }, }, ) ts.apply(monkeypatch) assert automation.execute(["test-host"]) == AnalyseHostResult( label_sources={ "cmk/site": "discovered", "explicit": "explicit" }, labels={ "cmk/site": "NO_SITE", "explicit": "ding" }, )
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)}), )
def test_attribute_defaults( self, special_agent_id, ipaddress, agent_dir, expected_args, expected_stdin, monkeypatch, ): hostname = HostName("testhost") params: Dict[Any, Any] = {} ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) # end of setup source = SpecialAgentSource( hostname, ipaddress, special_agent_id=special_agent_id, params=params, ) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.cmdline == ( # str(agent_dir / "special" / ("agent_%s" % special_agent_id)) + " " + expected_args) assert source.stdin == expected_stdin assert source.id == "special_%s" % special_agent_id
def test_mgmt_config_ruleset_overidden_by_explicit_setting( monkeypatch, protocol, cred_attribute, host_credentials, ruleset_credentials): ts = Scenario() ts.set_ruleset( "management_board_config", [ { "condition": {}, "options": {}, "value": (protocol, ruleset_credentials), }, ], ) ts.add_host("mgmt-host", host_path="/wato/folder1/hosts.mk") ts.set_option("ipaddresses", {"mgmt-host": "127.0.0.1"}) ts.set_option("management_protocol", {"mgmt-host": protocol}) ts.set_option(cred_attribute, {"mgmt-host": host_credentials}) config_cache = ts.apply(monkeypatch) host_config = config_cache.get_host_config("mgmt-host") assert host_config.has_management_board assert host_config.management_protocol == protocol assert host_config.management_address == "127.0.0.1" assert host_config.management_credentials == host_credentials
def test_get_check_table__static_checks_win(monkeypatch: MonkeyPatch) -> None: hostname_str = "df_host" hostname = HostName(hostname_str) plugin_name = CheckPluginName("df") item = "/snap/core/9066" ts = Scenario() ts.add_host(hostname) ts.set_option( "static_checks", { "filesystem": [ ((str(plugin_name), item, { "source": "static" }), [], [hostname_str]), ], }, ) ts.set_autochecks( hostname_str, [AutocheckEntry(plugin_name, item, {"source": "auto"}, {})]) ts.apply(monkeypatch) chk_table = check_table.get_check_table(hostname) # assert check table is populated as expected assert len(chk_table) == 1 # assert static checks won effective_params = chk_table[(plugin_name, item)].parameters.evaluate(lambda _: True) assert effective_params[ "source"] == "static" # type: ignore[index,call-overload]
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", [Service(*service_id, "Temperature SMART auto-clustered", {})]) ts.apply(monkeypatch) # a rule for the node: monkeypatch.setattr( config, "_update_with_configured_check_parameters", lambda host, plugin, item, params, configured_params: {"levels_for_node": (1, 2), **params} if host == node else params, ) clustered_service = check_table.get_check_table(cluster)[service_id] assert clustered_service.parameters == {"levels": (35, 40)}
def test_mgmt_config_ruleset_order(monkeypatch, protocol, cred_attribute, folder_credentials, ruleset_credentials): ts = Scenario() ts.set_ruleset( "management_board_config", [ { "condition": {}, "options": {}, "value": ("snmp", "RULESET1"), }, { "condition": {}, "options": {}, "value": ("snmp", "RULESET2"), }, ], ) ts.add_host("mgmt-host", host_path="/wato/folder1/hosts.mk") ts.set_option("ipaddresses", {"mgmt-host": "127.0.0.1"}) ts.set_option("management_protocol", {"mgmt-host": "snmp"}) config_cache = ts.apply(monkeypatch) host_config = config_cache.get_host_config("mgmt-host") assert host_config.has_management_board assert host_config.management_protocol == "snmp" assert host_config.management_address == "127.0.0.1" assert host_config.management_credentials == "RULESET1"
def test_attribute_defaults(self, monkeypatch): hostname = "testhost" ipaddress = "1.2.3.4" ts = Scenario() ts.add_host(hostname) ts.set_option("management_protocol", {hostname: "snmp"}) ts.set_option( "host_attributes", { hostname: { "management_address": ipaddress }, }, ) ts.apply(monkeypatch) source = SNMPSource.management_board( HostName(hostname), ipaddress, force_cache_refresh=False, selected_sections=NO_SELECTION, on_scan_error=OnError.RAISE, ) assert source.description == ( "Management board - SNMP " "(Community: 'public', Bulk walk: no, Port: 161, Backend: Classic)" )
def test_attribute_defaults(monkeypatch): ipaddress = "1.2.3.4" hostname = HostName("testhost") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = TCPSource(hostname, ipaddress) monkeypatch.setattr(source, "file_cache_base_path", Path("/my/path/")) assert source.fetcher_configuration == { "file_cache": { "hostname": "testhost", "disabled": False, "max_age": MaxAge.none(), "base_path": "/my/path", "simulation": False, "use_outdated": False, }, "family": socket.AF_INET, "address": (ipaddress, 6556), "host_name": str(hostname), "timeout": 5.0, "encryption_settings": { "use_realtime": "enforce", "use_regular": "disable", }, "use_only_cache": False, } assert source.description == "TCP: %s:%s" % (ipaddress, 6556) assert source.id == "agent"
def make_scenario(hostname, tags): ts = Scenario() ts.add_host(hostname, tags=tags) ts.set_ruleset( "datasource_programs", [ ("echo 1", [], ["ds-host-14", "all-agents-host", "all-special-host"], {}), ], ) ts.set_option( "special_agents", { "jolokia": [ ( {}, [], [ "special-host-14", "all-agents-host", "all-special-host", ], {}, ), ] }, ) return ts
def test_get_effective_service_level(monkeypatch): ts = Scenario().add_host("testhost1") ts.add_host("testhost2") ts.add_host("testhost3") ts.set_ruleset( "host_service_levels", [ (10, [], ["testhost2"], {}), (2, [], ["testhost2"], {}), ], ) ts.set_ruleset( "service_service_levels", [ (33, [], ["testhost1"], ["CPU load$"], {}), ], ) ts.apply(monkeypatch) with plugin_contexts.current_service( Service( item=None, check_plugin_name=CheckPluginName("cpu_loads"), description="CPU load", parameters={}, )): with plugin_contexts.current_host("testhost1"): assert check_api.get_effective_service_level() == 33 with plugin_contexts.current_host("testhost2"): assert check_api.get_effective_service_level() == 10 with plugin_contexts.current_host("testhost3"): assert check_api.get_effective_service_level() == 0
def test_get_effective_service_level(monkeypatch): ts = Scenario() ts.add_host("testhost1") ts.add_host("testhost2") ts.add_host("testhost3") ts.set_ruleset( "host_service_levels", [ (10, [], ["testhost2"], {}), (2, [], ["testhost2"], {}), ], ) ts.set_ruleset( "service_service_levels", [ (33, [], ["testhost1"], ["CPU load$"], {}), ], ) ts.apply(monkeypatch) with plugin_contexts.current_service(CheckPluginName("cpu_loads"), "CPU load"): with plugin_contexts.current_host("testhost1"): assert check_api.get_effective_service_level() == 33 with plugin_contexts.current_host("testhost2"): assert check_api.get_effective_service_level() == 10 with plugin_contexts.current_host("testhost3"): assert check_api.get_effective_service_level() == 0
def test_ruleset_matcher_get_host_ruleset_values_tags_duplicate_ids( monkeypatch: MonkeyPatch, rule_spec: RuleConditionsSpec, expected_result: Sequence[RuleValue], ) -> None: ts = Scenario() add_tag_config = TagConfig.from_config( { "aux_tags": [], "tag_groups": [ { "id": "grp1", "tags": [ { "aux_tags": [], "id": "v1", "title": "Value1", }, ], "title": "Group 1", }, { "id": "grp2", "tags": [ { "aux_tags": [], "id": "v1", "title": "Value1", }, ], "title": "Group 2", }, ], } ) ts.tags += add_tag_config ts.add_host( "host", tags={ "grp1": "v1", }, ) config_cache = ts.apply(monkeypatch) matcher = config_cache.ruleset_matcher assert ( list( matcher.get_host_ruleset_values( RulesetMatchObject( host_name=HostName("host"), service_description=None, ), ruleset=[rule_spec], is_binary=False, ) ) == expected_result )
def test_lookup_mgmt_board_ip_address_unresolveable( monkeypatch: MonkeyPatch, tags: Dict[str, str], family: socket.AddressFamily) -> None: hostname = HostName("unresolveable-hostname") ts = Scenario() ts.add_host(hostname, tags=tags) ts.apply(monkeypatch) host_config = config.get_config_cache().get_host_config(hostname) assert config.lookup_mgmt_board_ip_address(host_config) is None
def test_lookup_mgmt_board_ip_address_ipv4_host(monkeypatch: MonkeyPatch, hostname_str: str, tags: Dict[str, str], result_address: str) -> None: hostname = HostName(hostname_str) ts = Scenario() ts.add_host(hostname, tags=tags) ts.apply(monkeypatch) host_config = config.get_config_cache().get_host_config(hostname) assert config.lookup_mgmt_board_ip_address(host_config) == result_address
def clear_config_caches(monkeypatch): from cmk.utils.caching import config_cache as _config_cache from cmk.utils.caching import runtime_cache as _runtime_cache _config_cache.clear() _runtime_cache.clear() ts = Scenario() ts.add_host("non-existent-testhost") ts.apply(monkeypatch)
def test_ruleset_matcher_get_service_ruleset_values_labels( monkeypatch: MonkeyPatch, hostname: HostName, service_description: str, expected_result: Sequence[str], ) -> None: ts = Scenario() ts.add_host(HostName("host1")) ts.set_autochecks( HostName("host1"), [ Service( CheckPluginName("cpu_load"), None, "CPU load", "{}", service_labels={ "os": ServiceLabel("os", "linux"), "abc": ServiceLabel("abc", "xä"), "hu": ServiceLabel("hu", "ha"), }, ) ], ) ts.add_host(HostName("host2")) ts.set_autochecks( HostName("host2"), [ Service( CheckPluginName("cpu_load"), None, "CPU load", "{}", service_labels={}, ), ], ) config_cache = ts.apply(monkeypatch) matcher = config_cache.ruleset_matcher assert ( list( matcher.get_service_ruleset_values( config_cache.ruleset_match_object_of_service( hostname, ServiceName(service_description) ), ruleset=service_label_ruleset, is_binary=False, ) ) == expected_result )
def test_compile_delayed_host_check(monkeypatch: MonkeyPatch, config_path: VersionedConfigPath) -> None: hostname = HostName("localhost") ts = Scenario() ts.add_host(hostname) ts.set_option("delay_precompile", True) config_cache = ts.apply(monkeypatch) # Ensure a host check is created monkeypatch.setattr( core_nagios, "_get_needed_plugin_names", lambda c: (set(), {CheckPluginName("uptime")}, set()), ) source_file = core_nagios.HostCheckStore.host_check_source_file_path( config_path, hostname, ) compiled_file = core_nagios.HostCheckStore.host_check_file_path( config_path, hostname) assert config.delay_precompile is True assert not source_file.exists() assert not compiled_file.exists() # Write the host check source file host_check = core_nagios._dump_precompiled_hostcheck( config_cache, config_path, hostname, verify_site_python=False, ) assert host_check is not None core_nagios.HostCheckStore().write(config_path, hostname, host_check) # The compiled file path links to the source file until it has been executed for the first # time. Then the symlink is replaced with the compiled file assert source_file.exists() assert compiled_file.exists() assert compiled_file.resolve() == source_file # Expect the command to fail: We don't have the correct environment to execute it. # But this is no problem for our test, we only want to see the result of the compilation. assert (subprocess.run( ["python3", str(compiled_file)], shell=False, close_fds=True, check=False, ).returncode == 1) assert compiled_file.resolve() != source_file with compiled_file.open("rb") as f: assert f.read().startswith(importlib.util.MAGIC_NUMBER)
def test_dump_precompiled_hostcheck_without_check_mk_service( monkeypatch: MonkeyPatch, config_path: VersionedConfigPath) -> None: hostname = HostName("localhost") ts = Scenario() ts.add_host(hostname) config_cache = ts.apply(monkeypatch) host_check = core_nagios._dump_precompiled_hostcheck( config_cache, config_path, hostname, ) assert host_check is None
def test_is_bulkwalk_host(monkeypatch): ts = Scenario().set_ruleset( "bulkwalk_hosts", [ ([], ["localhost"], {}), ], ) ts.add_host("abc") ts.add_host("localhost") config_cache = ts.apply(monkeypatch) assert config_cache.get_host_config("abc").snmp_config("").is_bulkwalk_host is False assert config_cache.get_host_config("localhost").snmp_config("").is_bulkwalk_host is True
def test_template_translation(self, ipaddress, monkeypatch): template = "<NOTHING>x<IP>x<HOST>x<host>x<ip>x" hostname = HostName("testhost") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = DSProgramSource(hostname, ipaddress, template=template) assert source.cmdline == "<NOTHING>x%sx%sx<host>x<ip>x" % ( ipaddress if ipaddress is not None else "", hostname, )
def test_attribute_defaults(monkeypatch: MonkeyPatch, ipaddress: HostAddress) -> None: hostname = HostName("testhost") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = PiggybackSource(hostname, ipaddress) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.description.startswith("Process piggyback data from") assert not source.summarize(result.OK(HostSections[AgentRawDataSection]())) assert source.id == "piggyback"
def test_sanitize_snmp_encoding(monkeypatch, encoding, columns, expected): ts = Scenario() ts.add_host("localhost") ts.set_ruleset( "snmp_character_encodings", [ (encoding, [], config.ALL_HOSTS, {}), ], ) config_cache = ts.apply(monkeypatch) snmp_config = config_cache.get_host_config("localhost").snmp_config("") assert snmp_table._sanitize_snmp_encoding(columns, snmp_config) == expected
def test_get_check_table_of_mgmt_boards( monkeypatch: MonkeyPatch, hostname_str: str, expected_result: List[ServiceID]) -> None: hostname = HostName(hostname_str) autochecks: Mapping[str, Sequence[Service[LegacyCheckParameters]]] = { "mgmt-board-ipmi": [ Service( CheckPluginName("mgmt_ipmi_sensors"), "TEMP X", "Management Interface: IPMI Sensor TEMP X", {}, ), ], "ipmi-host": [ Service(CheckPluginName("ipmi_sensors"), "TEMP Y", "IPMI Sensor TEMP Y", {}), ], } ts = Scenario().add_host( "mgmt-board-ipmi", tags={ "piggyback": "auto-piggyback", "networking": "lan", "address_family": "no-ip", "criticality": "prod", "snmp_ds": "no-snmp", "site": "heute", "agent": "no-agent", }, ) ts.add_host( "ipmi-host", tags={ "piggyback": "auto-piggyback", "networking": "lan", "agent": "cmk-agent", "criticality": "prod", "snmp_ds": "no-snmp", "site": "heute", "address_family": "ip-v4-only", }, ) ts.set_option("management_protocol", {"mgmt-board-ipmi": "ipmi"}) config_cache = ts.apply(monkeypatch) monkeypatch.setattr(config_cache, "get_autochecks_of", lambda h: autochecks.get(h, [])) assert list( check_table.get_check_table(hostname).keys()) == expected_result
def test_mgmt_explicit_settings(monkeypatch, protocol, cred_attribute, credentials): ts = Scenario() ts.add_host("mgmt-host") ts.set_option("ipaddresses", {"mgmt-host": "127.0.0.1"}) ts.set_option("management_protocol", {"mgmt-host": protocol}) ts.set_option(cred_attribute, {"mgmt-host": credentials}) config_cache = ts.apply(monkeypatch) host_config = config_cache.get_host_config("mgmt-host") assert host_config.has_management_board assert host_config.management_protocol == protocol assert host_config.management_address == "127.0.0.1" assert host_config.management_credentials == credentials
def test_lookup_mgmt_board_ip_address_dual_host(monkeypatch: MonkeyPatch, hostname_str: str, result_address: str): hostname = HostName(hostname_str) ts = Scenario() ts.add_host( hostname, tags={ "address_family": "ip-v4v6", }, ) ts.apply(monkeypatch) host_config = config.get_config_cache().get_host_config(hostname) assert config.lookup_mgmt_board_ip_address(host_config) == result_address
def test_basic_get_host_ruleset_values(monkeypatch: MonkeyPatch) -> None: ts = Scenario() ts.add_host(HostName("abc")) ts.add_host(HostName("xyz")) ts.add_host(HostName("host1")) ts.add_host(HostName("host2")) config_cache = ts.apply(monkeypatch) matcher = config_cache.ruleset_matcher assert ( list( matcher.get_host_ruleset_values( RulesetMatchObject(host_name=HostName("abc"), service_description=None), ruleset=ruleset, is_binary=False, ) ) == [] ) assert ( list( matcher.get_host_ruleset_values( RulesetMatchObject(host_name=HostName("xyz"), service_description=None), ruleset=ruleset, is_binary=False, ) ) == [] ) assert ( list( matcher.get_host_ruleset_values( RulesetMatchObject(host_name=HostName("host1"), service_description=None), ruleset=ruleset, is_binary=False, ) ) == ["BLA", "BLUB"] ) assert ( list( matcher.get_host_ruleset_values( RulesetMatchObject(host_name=HostName("host2"), service_description=None), ruleset=ruleset, is_binary=False, ) ) == ["BLUB"] )