def ts(monkeypatch): ts = Scenario(site_id="site1") ts.add_host("host1", tags={"agent": "no-agent", "criticality": "test"}) ts.add_host("host2", tags={"agent": "no-agent"}) ts.add_host("host3", tags={"agent": "no-agent", "site": "site2"}) ts.apply(monkeypatch) return ts
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_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_get_labels_of_service(monkeypatch): automation = automations.AutomationGetLabelsOf() ts = Scenario().add_host("test-host") ts.set_ruleset( "service_label_rules", [ ({ "label1": "val1" }, [], config.ALL_HOSTS, ["CPU load$"], {}), ({ "label2": "val2" }, [], config.ALL_HOSTS, ["CPU load$"], {}), ], ) ts.apply(monkeypatch) assert automation.execute(["service", "test-host", "CPU load"]) == GetLabelsOfResult({ "labels": { "label1": "val1", "label2": "val2" }, "label_sources": { "label1": "ruleset", "label2": "ruleset" }, })
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_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_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 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_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_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_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_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_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 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_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 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_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_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_get_check_table_of_mgmt_boards( monkeypatch: MonkeyPatch, hostname_str: str, expected_result: List[ServiceID]) -> None: hostname = HostName(hostname_str) ts = Scenario() ts.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"}) ts.set_autochecks( "mgmt-board-ipmi", [ AutocheckEntry(CheckPluginName("mgmt_ipmi_sensors"), "TEMP X", {}, {}) ], ) ts.set_autochecks( "ipmi-host", [AutocheckEntry(CheckPluginName("ipmi_sensors"), "TEMP Y", {}, {})], ) ts.apply(monkeypatch) assert list( check_table.get_check_table(hostname).keys()) == expected_result
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_basic_host_ruleset_is_matching_host_ruleset( monkeypatch: MonkeyPatch) -> None: ts = Scenario() ts.add_host(HostName("abc")) 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 (matcher.is_matching_host_ruleset( RulesetMatchObject(host_name=HostName("abc"), service_description=None), ruleset=binary_ruleset, ) is False) assert (matcher.is_matching_host_ruleset( RulesetMatchObject(host_name=HostName("xyz"), service_description=None), ruleset=binary_ruleset, ) is False) assert (matcher.is_matching_host_ruleset( RulesetMatchObject(host_name=HostName("host1"), service_description=None), ruleset=binary_ruleset, ) is True) assert (matcher.is_matching_host_ruleset( RulesetMatchObject(host_name=HostName("host2"), service_description=None), ruleset=binary_ruleset, ) is False)
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_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_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_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_tcpdatasource_restricted_address_mismatch( monkeypatch, restricted_address_mismatch_state, only_from, rule, res, ): # TODO(ml): Not only is this white box testing but all these instantiations # before the summarizer obscure the purpose of the test. This is # way too complicated. Test the `AgentSummarizerDefault` directly # in `tests.unit.cmk.core_helpers.test_summarizers` instead. hostname = HostName("hostname") ts = Scenario().add_host(hostname) ts.set_option("agent_config", {"only_from": [(rule, [], [str(hostname)], {})]}) if restricted_address_mismatch_state is not None: ts.set_ruleset( "check_mk_exit_status", [ ( { "restricted_address_mismatch": restricted_address_mismatch_state, }, [], [str(hostname)], {}, ), ], ) ts.apply(monkeypatch) source = TCPSource(hostname, "ipaddress") summarizer = AgentSummarizerDefault( source.exit_spec, is_cluster=source.host_config.is_cluster, agent_min_version=0, agent_target_version=source.host_config.agent_target_version, only_from=source.host_config.only_from, ) assert summarizer._check_only_from(only_from) == res
def test_attribute_defaults(self, monkeypatch): hostname = "testhost" ipaddress = "1.2.3.4" ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = SNMPSource.snmp( HostName(hostname), ipaddress, selected_sections=NO_SELECTION, on_scan_error=OnError.RAISE, force_cache_refresh=False, ) assert source.description == ( "SNMP (Community: 'public', Bulk walk: no, Port: 161, Backend: Classic)" )
def test_attribute_defaults(monkeypatch): hostname = HostName("testhost") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) host_config = config.get_config_cache().get_host_config(hostname) ipaddress = config.lookup_mgmt_board_ip_address(host_config) source = IPMISource(hostname, ipaddress) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.description == "Management board - IPMI" assert source.source_type is SourceType.MANAGEMENT assert source.summarize(result.OK(HostSections[AgentRawDataSection]())) == [ ActiveCheckResult(0, "Success") ] assert source.id == "mgmt_ipmi"
def test_attribute_defaults(self, ipaddress, monkeypatch): template = "" hostname = HostName("testhost") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = DSProgramSource( hostname, ipaddress, template=template, ) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.cmdline == "" assert source.stdin is None assert source.description == "Program: " assert source.id == "agent"
def test_snmp_ipaddress_from_mgmt_board_unresolvable(hostname, monkeypatch): def fake_lookup_ip_address(*_a, **_kw): raise MKIPAddressLookupError("Failed to ...") ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) monkeypatch.setattr(ip_lookup, "lookup_ip_address", fake_lookup_ip_address) monkeypatch.setattr( config, "host_attributes", { "hostname": { "management_address": "lolo" }, }, ) host_config = config.get_config_cache().get_host_config(hostname) assert config.lookup_mgmt_board_ip_address(host_config) is None