def test_attribute_defaults(monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = TCPDataSource(hostname, ipaddress) assert source._hostname == hostname assert source._ipaddress == ipaddress assert source.id() == "agent" assert source.port == 6556 assert source.timeout == 5.0 # From the base class assert source.name() == ("agent:%s:%s" % (hostname, ipaddress if ipaddress else "")) assert source.describe() == "TCP: %s:%s" % (ipaddress, source.port) assert source.is_agent_cache_disabled() is False assert source.get_may_use_cache_file() is False assert source.exception() is None
def test_attribute_defaults(monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = SNMPDataSource(hostname, ipaddress) assert source._hostname == hostname assert source._ipaddress == ipaddress assert source.id() == "snmp" assert source.title() == "SNMP" assert source._cpu_tracking_id() == "snmp" assert source.get_do_snmp_scan() is False # From the base class assert source.name() == ("snmp:%s:%s" % (hostname, ipaddress if ipaddress else "")) assert source.is_agent_cache_disabled() is False assert source.get_may_use_cache_file() is False assert source.exception() is None
def test_attribute_defaults(monkeypatch): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = IPMIManagementBoardDataSource( hostname, ip_lookup.management_board_ipaddress(hostname), ) assert source.source_type is SourceType.MANAGEMENT assert source.hostname == hostname # Address comes from management board. assert source.ipaddress is None assert source.id() == "mgmt_ipmi" assert source.title() == "Management board - IPMI" assert source._cpu_tracking_id() == source.id() assert source._summary_result(True) == (0, "Version: unknown", []) assert source._get_ipmi_version() == "unknown"
def test_attribute_defaults(monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = IPMIManagementBoardDataSource(hostname, ipaddress) assert source._for_mgmt_board is True assert source._hostname == hostname # Address comes from management board. assert source._ipaddress is None assert source.id() == "mgmt_ipmi" assert source.title() == "Management board - IPMI" assert source._cpu_tracking_id() == source.id() assert source._gather_check_plugin_names() == {"mgmt_ipmi_sensors"} assert source._summary_result("anything will do") == (0, "Version: unknown", []) assert source._get_ipmi_version() == "unknown"
def test_mgmt_disabled(monkeypatch): ts = Scenario() ts.add_host("mgmt-host") ts.set_option("ipaddresses", {"mgmt-host": "127.0.0.1"}) ts.set_option("management_protocol", {"mgmt-host": None}) ts.set_option("host_attributes", {"mgmt-host": { "management_address": "127.0.0.1" }}) ts.set_option("management_snmp_credentials", {"mgmt-host": "HOST"}) config_cache = ts.apply(monkeypatch) host_config = config_cache.get_host_config("mgmt-host") assert host_config.has_management_board is False assert host_config.management_protocol is None assert host_config.management_address == "127.0.0.1" assert host_config.management_credentials is None
def test_ipmi_ipaddress_from_mgmt_board(monkeypatch): hostname = "testhost" ipaddress = "127.0.0.1" Scenario().add_host(hostname).apply(monkeypatch) monkeypatch.setattr(ip_lookup, "lookup_ip_address", lambda h: ipaddress) monkeypatch.setattr(config, "host_attributes", { hostname: { "management_address": ipaddress }, }) source = IPMIManagementBoardDataSource( hostname, management_board_ipaddress(hostname), ) assert source._host_config.management_address == ipaddress assert source._ipaddress == ipaddress
def make_scenario(hostname, tags): ts = Scenario().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_ipmi_ipaddress_from_mgmt_board(mode, monkeypatch): hostname = "testhost" ipaddress = "127.0.0.1" def fake_lookup_ip_address(host_config, *, family, for_mgmt_board=True): return ipaddress Scenario().add_host(hostname).apply(monkeypatch) monkeypatch.setattr(ip_lookup, "lookup_ip_address", fake_lookup_ip_address) monkeypatch.setattr(config, "host_attributes", { hostname: { "management_address": ipaddress }, }) source = IPMISource(hostname, ipaddress, mode=mode) assert source.host_config.management_address == ipaddress
def test_attribute_defaults(mode, monkeypatch): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) host_config = config.get_config_cache().get_host_config(hostname) ipaddress = ip_lookup.lookup_mgmt_board_ip_address(host_config) source = IPMISource(hostname, ipaddress, mode=mode) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.mode is mode assert source.description == "Management board - IPMI" assert source.source_type is SourceType.MANAGEMENT assert source.summarize(result.OK( AgentHostSections())) == (0, "Version: unknown", []) assert source.id == "mgmt_ipmi" assert source.cpu_tracking_id == "mgmt_ipmi"
def test_check_crash_report_save(monkeypatch): Scenario().apply(monkeypatch) store = crash_reporting.CrashReportStore() try: raise Exception("DING") except Exception: crash = crash_reporting.CheckCrashReport.from_exception_and_context( hostname="testhost", check_plugin_name="uptime", check_plugin_kwargs={}, is_manual_check=False, description=u"Uptime", text=u"Output", ) store.save(crash) crash2 = store.load_from_directory(crash.crash_dir()) assert crash2.crash_info["exc_value"] == "DING"
def scenario_fixture(monkeypatch): test_hosts = ["ds-test-host1", "ds-test-host2", "ds-test-node1", "ds-test-node2"] ts = Scenario() if is_enterprise_repo(): ts.set_option("monitoring_core", "cmc") else: ts.set_option("monitoring_core", "nagios") for h in test_hosts: ts.add_host(h) ts.set_option("ipaddresses", dict((h, "127.0.0.1") for h in test_hosts)) ts.add_cluster("ds-test-cluster1", nodes=["ds-test-node1", "ds-test-node2"]) ts.fake_standard_linux_agent_output(*test_hosts) return ts.apply(monkeypatch)
def test_get_summary_result_requires_host_sections(monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = TCPDataSource(hostname, ipaddress) with pytest.raises(AssertionError): source.get_summary_result_for_discovery() with pytest.raises(AssertionError): source.get_summary_result_for_inventory() with pytest.raises(AssertionError): source.get_summary_result_for_checking() source._host_sections = _abstract.AgentHostSections() defaults = (0, "Version: unknown, OS: unknown", []) assert source.get_summary_result_for_discovery() == defaults assert source.get_summary_result_for_inventory() == defaults assert source.get_summary_result_for_checking() == defaults
def test_attribute_defaults(self, ipaddress, mode, monkeypatch): template = "" hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = DSProgramSource( hostname, ipaddress, mode=mode, template=template, ) assert source.hostname == hostname assert source.ipaddress == ipaddress assert source.mode is mode assert source.cmdline == "" assert source.stdin is None assert source.description == "Program: " assert source.id == "agent"
def test_get_check_plugin_names_requires_type_filter_function_and_ipaddress(monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = SNMPDataSource(hostname, ipaddress) with pytest.raises(Exception): source.get_check_plugin_names() # One filter function is defined in cmk.base.inventory and another one in snmp_scan. def dummy_filter_func(host_config, on_error, do_snmp_scan, for_mgmt_board=False): return set() source.set_check_plugin_name_filter(dummy_filter_func) if ipaddress is None: with pytest.raises(NotImplementedError): source.get_check_plugin_names() else: assert source.get_check_plugin_names() == set()
def test_make_snmp_section_detects_for_inventory(monkeypatch, hostname, ipaddress, check_plugin): plugin = section_plugins.create_snmp_section_plugin( name="norris", parse_function=lambda string_table: None, fetch=[ SNMPTree( base='.1.2.3', oids=['2.3'], ), ], detect_spec=SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), ) monkeypatch.setattr(_config, 'registered_snmp_sections', {plugin.name: plugin}) monkeypatch.setattr(_config, 'registered_inventory_plugins', {check_plugin.name: check_plugin}) Scenario().add_host(hostname).apply(monkeypatch) source = SNMPSource.snmp(hostname, ipaddress, mode=Mode.INVENTORY) assert source._make_snmp_section_detects() == {plugin.name: plugin.detect_spec}
def test_host_config_active_checks(monkeypatch, hostname, result): ts = Scenario().add_host(hostname) ts.set_option( "active_checks", { "abc": [ ({ "param1": 1 }, [], ["testhost2"], {}), ({ "param2": 2 }, [], ["testhost2"], {}), ], "xyz": [({ "param2": 1 }, [], ["testhost2"], {}),], }) config_cache = ts.apply(monkeypatch) assert config_cache.get_host_config(hostname).active_checks == result
def test_piggyback_storage(monkeypatch, mocker): hostname = "testhost" ipaddress = "1.2.3.4" raw_data = b"\n".join(( b"<<<<piggyback header>>>>", b"<<<section>>>", b"first line", b"second line", b"<<<<>>>>", )) ts = Scenario() ts.add_host(hostname) ts.apply(monkeypatch) source = TCPDataSource(hostname, ipaddress) monkeypatch.setattr(time, "time", lambda: 0) mhs = agent.Parser(logging.getLogger("test")).parse(hostname, raw_data, check_interval=0) monkeypatch.setattr( type(source), "run", lambda self, *, selected_raw_sections: mhs, ) mocker.patch.object( cmk.utils.piggyback, "store_piggyback_raw_data", autospec=True, ) # End of setup _make_host_sections( [(hostname, ipaddress, [source])], max_cachefile_age=0, selected_raw_sections=None, ) args = cmk.utils.piggyback.store_piggyback_raw_data.call_args.args # type: ignore[attr-defined] assert mhs.piggybacked_raw_data assert args == (hostname, mhs.piggybacked_raw_data)
def test_create_nagios_host_spec(hostname, result, monkeypatch): if cmk_version.is_managed_edition(): result = result.copy() result['_CUSTOMER'] = 'provider' ts = Scenario().add_host("localhost") ts.add_host("host2") ts.add_cluster("cluster1") ts.add_cluster("cluster2", nodes=["node1", "node2"]) ts.add_host("node1") ts.add_host("node2") ts.add_host("switch") ts.set_option("ipaddresses", { "node1": "127.0.0.1", "node2": "127.0.0.2", }) ts.set_option("extra_host_conf", { "alias": [ (u'lOCALhost', ['localhost']), ], }) ts.set_option( "extra_host_conf", { "alias": [ (u'lOCALhost', ['host2']), (u'CLUSTer', ['cluster2']), ], "parents": [ ('switch', ['node1', 'node2']), ], }) outfile = io.StringIO() cfg = core_nagios.NagiosConfig(outfile, [hostname]) config_cache = ts.apply(monkeypatch) host_attrs = core_config.get_host_attributes(hostname, config_cache) host_spec = core_nagios._create_nagios_host_spec(cfg, config_cache, hostname, host_attrs) assert host_spec == result
def test_get_labels_of_host(monkeypatch): automation = automations.AutomationGetLabelsOf() ts = Scenario().add_host("test-host") ts.set_option("host_labels", { "test-host": { "explicit": "ding", }, }) ts.apply(monkeypatch) assert automation.execute(["host", "test-host"]) == { "labels": { "explicit": "ding" }, "label_sources": { "explicit": "explicit" }, }
def test_detector_requires_type_filter_function_and_ipaddress( monkeypatch, ipaddress): hostname = "testhost" Scenario().add_host(hostname).apply(monkeypatch) source = SNMPDataSource(hostname, ipaddress) with pytest.raises(Exception): source._get_raw_section_names_to_process() def dummy_filter_func(sections, on_error, do_snmp_scan, *, binary_host, backend): return set() source.set_check_plugin_name_filter(dummy_filter_func, inventory=False) if ipaddress is None: with pytest.raises(NotImplementedError): source._get_raw_section_names_to_process() else: assert source._get_raw_section_names_to_process() == set()
def test__rename_discovered_host_label_files_fix_wrong_name(monkeypatch): Scenario().add_host("abc.d").apply(monkeypatch) uc = update_config.UpdateConfig(cmk.utils.log.logger, argparse.Namespace()) 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() assert not new_path.exists() uc._rename_discovered_host_label_files() assert not old_path.exists() assert new_path.exists()
def test_tcpdatasource_restricted_address_mismatch(mode, monkeypatch, restricted_address_mismatch_state, only_from, rule, result): hostname = "hostname" ts = Scenario().add_host(hostname) ts.set_option("agent_config", {"only_from": [(rule, [], [hostname], {})]}) if restricted_address_mismatch_state is not None: ts.set_ruleset("check_mk_exit_status", [ ({ "restricted_address_mismatch": restricted_address_mismatch_state, }, [], [hostname], {}), ]) ts.apply(monkeypatch) configurator = TCPConfigurator(hostname, "ipaddress", mode=mode) summarizer = AgentSummarizerDefault(configurator) assert summarizer._sub_result_only_from({"onlyfrom": only_from}) == result
def test_compile_delayed_host_check(monkeypatch, serial): hostname = "localhost" ts = Scenario().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( serial, hostname) compiled_file = core_nagios.HostCheckStore.host_check_file_path( serial, 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, serial, hostname, verify_site_python=False) assert host_check is not None core_nagios.HostCheckStore().write(serial, 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.Popen(["python3", str(compiled_file)], shell=False, close_fds=True).wait() == 1 assert compiled_file.resolve() != source_file with compiled_file.open("rb") as f: assert f.read().startswith(importlib.util.MAGIC_NUMBER)
def test_do_discovery(monkeypatch): ts = Scenario().add_host("test-host", ipaddress="127.0.0.1") ts.fake_standard_linux_agent_output("test-host") ts.apply(monkeypatch) with cmk_debug_enabled(): discovery.do_discovery( arg_hostnames={"test-host"}, selected_sections=NO_SELECTION, run_only_plugin_names=None, arg_only_new=False, ) services = autochecks.parse_autochecks_file("test-host", config.service_description) found = {(s.check_plugin_name, s.item): s.service_labels.to_dict() for s in services} assert found == _expected_services store = DiscoveredHostLabelsStore("test-host") assert store.load() == _expected_host_labels
def test_get_cmk_passive_service_attributes(monkeypatch, hostname, result): 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 = Service(CheckPluginName("cpu_loads"), None, "CPU load", {}) service_spec = core_config.get_cmk_passive_service_attributes(config_cache, host_config, service, check_mk_attrs) assert service_spec == result
def test_host_ruleset_match_object_of_service(monkeypatch): ts = Scenario() ts.add_host("test-host", tags={"agent": "no-agent"}) ts.add_host("xyz") config_cache = ts.apply(monkeypatch) obj = config_cache.ruleset_match_object_of_service("xyz", "bla blä") assert isinstance(obj, RulesetMatchObject) assert obj.to_dict() == { "host_folder": '/wato/', "host_name": "xyz", "host_tags": { 'address_family': 'ip-v4-only', 'agent': 'cmk-agent', 'criticality': 'prod', 'ip-v4': 'ip-v4', 'networking': 'lan', 'piggyback': 'auto-piggyback', 'site': 'unit', 'snmp_ds': 'no-snmp', 'tcp': 'tcp', }, "service_description": "bla blä", } obj = config_cache.ruleset_match_object_of_service("test-host", "CPU load") assert isinstance(obj, RulesetMatchObject) assert obj.to_dict() == { "host_folder": '/wato/', "host_name": "test-host", "host_tags": { 'address_family': 'ip-v4-only', 'agent': 'no-agent', 'criticality': 'prod', 'ip-v4': 'ip-v4', 'networking': 'lan', 'piggyback': 'auto-piggyback', 'site': 'unit', 'snmp_ds': 'no-snmp', }, "service_description": "CPU load", }
def test_get_check_table_of_mgmt_boards(monkeypatch, hostname, expected_result): autochecks = { "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, [])) CheckManager().load(["mgmt_ipmi_sensors", "ipmi_sensors"]) assert list( check_table.get_check_table(hostname).keys()) == expected_result
def test_filter_by_management_board_dual_host_with_SNMP_mgmt_board(monkeypatch, for_discovery, host_result, mgmt_board_result): ts = Scenario() ts.add_host("this_host", tags={"snmp_ds": "snmp-v1", "agent": "cmk-agent"}) config_cache = ts.apply(monkeypatch) h = config_cache.get_host_config("this_host") h.has_management_board = True found_check_plugins = [c for c in _check_plugins()] monkeypatch.setattr(config, "check_info", found_check_plugins) assert config.filter_by_management_board( "this_host", found_check_plugins, False, for_discovery=for_discovery) == set(host_result) found_check_plugins = [c for c in _check_plugins() if c.startswith("snmp_")] monkeypatch.setattr(config, "check_info", found_check_plugins) assert config.filter_by_management_board( "this_host", found_check_plugins, True, for_discovery=for_discovery) == set(mgmt_board_result)
def test_make_snmp_section_detects(monkeypatch, hostname, ipaddress): plugin = section_plugins.create_snmp_section_plugin( name="norris", parse_function=lambda string_table: None, fetch=[ SNMPTree( base='.1.2.3', oids=['2.3'], ), ], detect_spec=SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), ) monkeypatch.setattr( register, 'iter_all_snmp_sections', lambda: [plugin], ) Scenario().add_host(hostname).apply(monkeypatch) source = SNMPSource.snmp(hostname, ipaddress, mode=Mode.DISCOVERY) assert source._make_snmp_section_detects() == {plugin.name: plugin.detect_spec}
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