def test_create_check_plugin_from_legacy_with_params(): plugin = check_plugins_legacy.create_check_plugin_from_legacy( "norris", { **MINIMAL_CHECK_INFO, "group": "norris_rule", "default_levels_variable": "norris_default_levels", }, [], {"norris_default_levels": { "levels": (23, 42) }}, lambda _x: {"norris_default_levels": { "levels_lower": (1, 2) }}, ) assert plugin.name == CheckPluginName("norris") assert plugin.sections == [ParsedSectionName("norris")] assert plugin.service_name == MINIMAL_CHECK_INFO["service_description"] assert plugin.discovery_function.__name__ == "discovery_migration_wrapper" assert plugin.discovery_default_parameters is None assert plugin.discovery_ruleset_name is None assert plugin.check_function.__name__ == "check_migration_wrapper" assert plugin.check_default_parameters == { "levels": (23, 42), "levels_lower": (1, 2), } assert plugin.check_ruleset_name == RuleSetName("norris_rule") assert plugin.cluster_check_function is None
def _get_discovery_ruleset() -> Any: # NOTE: THIS AN API VIOLATION, DO NOT REPLICATE THIS # This is needed because inventory_ipmi_rules was once not a dict, which is not allowed by the # API for discovery rulesets # ============================================================================================== rules_all_hosts = get_discovery_ruleset(RuleSetName("inventory_ipmi_rules")) rules_this_host = get_config_cache().host_extra_conf(host_name(), rules_all_hosts) rules_this_host += [{"discovery_mode": ("summarize", {})}] # default parameters return rules_this_host[0]
def test_create_snmp_section_plugin(): trees: List[SNMPTree] = [ SNMPTree( base='.1.2.3', oids=[OIDEnd(), '2.3'], ), ] detect = SNMPDetectSpec([ [('.1.2.3.4.5', 'Foo.*', True)], ]) rule_dependent_detect = SNMPRuleDependentDetectSpec( [RuleSetName('a'), RuleSetName('b')], lambda a, b: detect, ) plugin = section_plugins.create_snmp_section_plugin( name="norris", parsed_section_name="chuck", parse_function=_parse_dummy, trees=trees, detect_spec=detect, supersedes=["foo", "bar"], rule_dependent_detect_spec=rule_dependent_detect, ) assert isinstance(plugin, SNMPSectionPlugin) assert len(plugin) == 9 assert plugin.name == SectionName("norris") assert plugin.parsed_section_name == ParsedSectionName("chuck") assert plugin.parse_function is _parse_dummy assert plugin.host_label_function is section_plugins._noop_host_label_function assert plugin.detect_spec == detect assert plugin.trees == trees assert plugin.supersedes == {SectionName("bar"), SectionName("foo")} assert plugin.rule_dependent_detect_spec == rule_dependent_detect
def create_agent_section_plugin( *, name: str, parsed_section_name: Optional[str] = None, parse_function: Optional[AgentParseFunction] = None, host_label_function: Optional[HostLabelFunction] = None, host_label_default_parameters: Optional[ParametersTypeAlias] = None, host_label_ruleset_name: Optional[str] = None, host_label_ruleset_type: RuleSetType = RuleSetType.MERGED, supersedes: Optional[List[str]] = None, module: Optional[str] = None, validate_creation_kwargs: bool = True, ) -> AgentSectionPlugin: """Return an AgentSectionPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ section_name = SectionName(name) if validate_creation_kwargs: if parse_function is not None: _validate_parse_function( parse_function, expected_annotation=_create_parse_annotation(), ) if host_label_function is not None: _validate_host_label_kwargs( host_label_function=host_label_function, host_label_default_parameters=host_label_default_parameters, host_label_ruleset_name=host_label_ruleset_name, host_label_ruleset_type=host_label_ruleset_type, ) return AgentSectionPlugin( name=section_name, parsed_section_name=ParsedSectionName( parsed_section_name if parsed_section_name else str(section_name)), parse_function=_create_agent_parse_function(parse_function), host_label_function=_create_host_label_function(host_label_function), host_label_default_parameters=host_label_default_parameters, host_label_ruleset_name=(None if host_label_ruleset_name is None else RuleSetName(host_label_ruleset_name)), host_label_ruleset_type=("merged" if host_label_ruleset_type is RuleSetType.MERGED else "all"), supersedes=_create_supersedes(section_name, supersedes), module=module, )
def create_inventory_plugin( *, name: str, sections: Optional[List[str]] = None, inventory_function: Callable, inventory_default_parameters: Optional[Dict] = None, inventory_ruleset_name: Optional[str] = None, module: Optional[str] = None, ) -> InventoryPlugin: """Return an InventoryPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ plugin_name = InventoryPluginName(name) subscribed_sections = create_subscribed_sections(sections, plugin_name) validate_function_arguments( type_label="inventory", function=inventory_function, has_item=False, default_params=inventory_default_parameters, sections=subscribed_sections, ) # validate check arguments validate_default_parameters( "inventory", inventory_ruleset_name, inventory_default_parameters, ) return InventoryPlugin( name=plugin_name, sections=subscribed_sections, inventory_function=_filter_inventory(inventory_function), inventory_default_parameters=inventory_default_parameters or {}, inventory_ruleset_name=(RuleSetName(inventory_ruleset_name) if inventory_ruleset_name else None), module=module, )
def test_rule_dependent( self, monkeypatch, discovery_rulesets, hostname, ipaddress, ): detect_spec_1 = SNMPDetectSpec([[('.1.2.3.4.5', 'Bar.*', False)]]) detect_spec_2 = SNMPDetectSpec([[('.7.8.9', 'huh.*', True)]]) def evaluator(discovery_ruleset): if len(discovery_ruleset) > 0 and discovery_ruleset[0]: return detect_spec_1 return detect_spec_2 plugin = section_plugins.create_snmp_section_plugin( name="norris", parse_function=lambda string_table: None, trees=[ SNMPTree( base='.1.2.3', oids=['2.3'], ), ], detect_spec=SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), rule_dependent_detect_spec=SNMPRuleDependentDetectSpec( [RuleSetName('discovery_ruleset')], evaluator, ), ) snmp_configurator = self.do_monkeypatch_and_make_configurator( monkeypatch, plugin, hostname, ipaddress, ) assert snmp_configurator._make_snmp_scan_sections() == [ SNMPScanSection( plugin.name, detect_spec_1, ) ]
def test_create_check_plugin_from_legacy_with_params(monkeypatch): monkeypatch.setattr(config, 'factory_settings', {"norris_default_levels": { "levels": (23, 42) }}) monkeypatch.setattr( config, '_check_contexts', {"norris": { "norris_default_levels": { "levels_lower": (1, 2) } }}) plugin = check_plugins_legacy.create_check_plugin_from_legacy( "norris", { **MINIMAL_CHECK_INFO, "group": "norris_rule", "default_levels_variable": "norris_default_levels", }, [], ) assert plugin.name == CheckPluginName("norris") assert plugin.sections == [ParsedSectionName("norris")] assert plugin.service_name == MINIMAL_CHECK_INFO["service_description"] assert plugin.discovery_function.__name__ == 'discovery_migration_wrapper' assert plugin.discovery_default_parameters == {} assert plugin.discovery_ruleset_name is None assert plugin.check_function.__name__ == 'check_migration_wrapper' assert plugin.check_default_parameters == { "levels": (23, 42), "levels_lower": (1, 2), } assert plugin.check_ruleset_name == RuleSetName("norris_rule") assert plugin.cluster_check_function.__name__ == "cluster_legacy_mode_from_hell"
def create_check_plugin( *, name: str, sections: Optional[List[str]] = None, service_name: str, discovery_function: Callable, discovery_default_parameters: Optional[Dict] = None, discovery_ruleset_name: Optional[str] = None, discovery_ruleset_type: RuleSetType = "merged", check_function: Callable, check_default_parameters: Optional[Dict] = None, check_ruleset_name: Optional[str] = None, cluster_check_function: Optional[Callable] = None, module: Optional[str] = None, validate_item: bool = True, validate_kwargs: bool = True, ) -> CheckPlugin: """Return an CheckPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ plugin_name = CheckPluginName(name) subscribed_sections = create_subscribed_sections(sections, plugin_name) requires_item = _requires_item(service_name) if validate_kwargs: _validate_kwargs( plugin_name=plugin_name, subscribed_sections=subscribed_sections, service_name=service_name, requires_item=requires_item, discovery_function=discovery_function, discovery_default_parameters=discovery_default_parameters, discovery_ruleset_name=discovery_ruleset_name, discovery_ruleset_type=discovery_ruleset_type, check_function=check_function, check_default_parameters=check_default_parameters, check_ruleset_name=check_ruleset_name, cluster_check_function=cluster_check_function, ) disco_func = _filter_discovery(discovery_function, requires_item, validate_item) disco_ruleset_name = RuleSetName( discovery_ruleset_name) if discovery_ruleset_name else None cluster_check_function = (unfit_for_clustering_wrapper(check_function) if cluster_check_function is None else _filter_check(cluster_check_function)) return CheckPlugin( name=plugin_name, sections=subscribed_sections, service_name=service_name, discovery_function=disco_func, discovery_default_parameters=discovery_default_parameters, discovery_ruleset_name=disco_ruleset_name, discovery_ruleset_type=discovery_ruleset_type, check_function=_filter_check(check_function), check_default_parameters=check_default_parameters, check_ruleset_name=RuleSetName(check_ruleset_name) if check_ruleset_name else None, cluster_check_function=cluster_check_function, module=module, )
item: str, params: type_defs.Parameters, section_ipmi: Optional[ipmi.Section], section_ipmi_discrete: Optional[ipmi.Section], ) -> type_defs.CheckResult: yield from ipmi.check_ipmi( item, params, _merge_sections(section_ipmi, section_ipmi_discrete), False, ipmi_status_txt_mapping, ) register.check_plugin( name="ipmi", sections=["ipmi", "ipmi_discrete"], service_name="IPMI Sensor %s", discovery_function=discover_ipmi, check_function=check_ipmi, check_ruleset_name='ipmi', check_default_parameters={"ignored_sensorstates": ["ns", "nr", "na"]}, ) # NOTE: THIS AN API VIOLATION, DO NOT REPLICATE THIS # This is needed because inventory_ipmi_rules was once not a dict, which is not allowed by the API # for discovery rulesets # ================================================================================================== add_discovery_ruleset(RuleSetName("inventory_ipmi_rules")) # ==================================================================================================
def create_snmp_section_plugin( *, name: str, detect_spec: SNMPDetectBaseType, fetch: Union[SNMPTree, List[SNMPTree]], parsed_section_name: Optional[str] = None, parse_function: Union[SimpleSNMPParseFunction, SNMPParseFunction, None] = None, host_label_function: Optional[HostLabelFunction] = None, host_label_default_parameters: Optional[Dict] = None, host_label_ruleset_name: Optional[str] = None, host_label_ruleset_type: RuleSetType = "merged", supersedes: Optional[List[str]] = None, module: Optional[str] = None, validate_creation_kwargs: bool = True, ) -> SNMPSectionPlugin: """Return an SNMPSectionPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ section_name = SectionName(name) # normalize to List[SNMPTree] tree_list = [fetch] if isinstance(fetch, SNMPTree) else fetch if validate_creation_kwargs: _validate_detect_spec(detect_spec) _validate_fetch_spec(tree_list) if parse_function is not None: needs_bytes = any(oid.encoding == "binary" for tree in tree_list for oid in tree.oids) _validate_parse_function( parse_function, expected_annotation=_create_parse_annotation( needs_bytes=needs_bytes, is_list=isinstance(fetch, list), ), ) if host_label_function is not None: _validate_host_label_kwargs( host_label_function=host_label_function, host_label_default_parameters=host_label_default_parameters, host_label_ruleset_name=host_label_ruleset_name, host_label_ruleset_type=host_label_ruleset_type, ) return SNMPSectionPlugin( name=section_name, parsed_section_name=ParsedSectionName( parsed_section_name if parsed_section_name else str(section_name)), parse_function=_create_snmp_parse_function(parse_function, isinstance(fetch, SNMPTree)), host_label_function=_create_host_label_function(host_label_function), host_label_default_parameters=host_label_default_parameters, host_label_ruleset_name=(None if host_label_ruleset_name is None else RuleSetName(host_label_ruleset_name)), host_label_ruleset_type=host_label_ruleset_type, supersedes=_create_supersedes(section_name, supersedes), detect_spec=detect_spec, trees=tree_list, module=module, )
"12", # ifInNUcastPkts 7 "13", # ifInDiscards 8 "14", # ifInErrors 9 "16", # ifOutOctets 10 "17", # ifOutUcastPkts 11 "18", # ifOutNUcastPkts 12 "19", # ifOutDiscards 13 "20", # ifOutErrors 14 "21", # ifOutQLen 15 OIDBytes("6"), # ifPhysAddress 16 ], ), ], detect_spec=never_detect, # does not matter what we put here rule_dependent_detect_spec=SNMPRuleDependentDetectSpec( [RuleSetName('if_disable_if64_hosts')], compute_detect_spec_if, ), ) add_section_plugin(section_plugin) assert section_plugin.rule_dependent_detect_spec for discovery_ruleset in section_plugin.rule_dependent_detect_spec.rulesets: add_discovery_ruleset(discovery_ruleset) # ================================================================================================== register.check_plugin( name="if", service_name="Interface %s", discovery_ruleset_name="inventory_if_rules", discovery_ruleset_type="all", discovery_default_parameters=dict(interfaces.DISCOVERY_DEFAULT_PARAMETERS),
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2019 tribe29 GmbH - License: GNU General Public License v2 # This file is part of Checkmk (https://checkmk.com). It is subject to the terms and # conditions defined in the file COPYING, which is part of this source code package. import pytest # type: ignore[import] from cmk.snmplib.type_defs import SNMPDetectSpec, SNMPRuleDependentDetectSpec from cmk.utils.type_defs import RuleSetName @pytest.mark.parametrize("rulesets, evaluator, expect_type_error", [ ( [RuleSetName('a'), RuleSetName('b')], lambda a, b: SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), False, ), ( [], lambda: SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), False, ), ( [RuleSetName('a'), RuleSetName('b')], lambda b, a: SNMPDetectSpec([[('.1.2.3.4.5', 'Foo.*', True)]]), True, ), ]) def test_snmp_rule_dependent_detect_spec(rulesets, evaluator, expect_type_error): if expect_type_error:
def create_check_plugin( *, name: str, sections: Optional[List[str]] = None, service_name: str, discovery_function: Callable, discovery_default_parameters: Optional[Dict] = None, discovery_ruleset_name: Optional[str] = None, check_function: Callable, check_default_parameters: Optional[Dict] = None, check_ruleset_name: Optional[str] = None, cluster_check_function: Optional[Callable] = None, forbidden_names: List[CheckPluginName], module: Optional[str] = None, ) -> CheckPlugin: """Return an CheckPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ plugin_name = CheckPluginName(name, forbidden_names) subscribed_sections = _create_sections(sections, plugin_name) _validate_service_name(name, service_name) requires_item = _requires_item(service_name) # validate discovery arguments _validate_default_parameters( name, "discovery", discovery_ruleset_name, discovery_default_parameters, ) _validate_discovery_ruleset( discovery_ruleset_name, discovery_default_parameters, ) _validate_function_args( name, "discovery", discovery_function, False, # no item discovery_ruleset_name is not None, subscribed_sections, ) # validate check arguments _validate_default_parameters( name, "check", check_ruleset_name, check_default_parameters, ) _validate_check_ruleset( check_ruleset_name, check_default_parameters, ) _validate_function_args( name, "check", check_function, requires_item, check_ruleset_name is not None, subscribed_sections, ) if cluster_check_function is None: cluster_check_function = unfit_for_clustering_wrapper(check_function) else: _validate_function_args( name, "cluster check", cluster_check_function, requires_item, check_ruleset_name is not None, subscribed_sections, ) cluster_check_function = _filter_check(cluster_check_function) return CheckPlugin( plugin_name, subscribed_sections, service_name, _filter_discovery(discovery_function, requires_item), discovery_default_parameters or {}, None if discovery_ruleset_name is None else RuleSetName(discovery_ruleset_name), _filter_check(check_function), check_default_parameters or {}, None if check_ruleset_name is None else RuleSetName(check_ruleset_name), cluster_check_function, module, )
def test_check_table__get_static_check_entries( monkeypatch: MonkeyPatch, check_group_parameters: LegacyCheckParameters) -> None: hostname = HostName("hostname") static_parameters_default = {"levels": (1, 2, 3, 4)} static_checks: Dict[str, List] = { "ps": [(("ps", "item", static_parameters_default), [], [hostname], {})], } ts = Scenario() ts.add_host(hostname) ts.set_option("static_checks", static_checks) ts.set_ruleset( "checkgroup_parameters", { "ps": [(check_group_parameters, [hostname], [], {})], }, ) config_cache = ts.apply(monkeypatch) monkeypatch.setattr( agent_based_register, "get_check_plugin", lambda cpn: CheckPlugin( CheckPluginName("ps"), [], "Process item", lambda: [], None, None, "merged", lambda: [], {}, RuleSetName("ps"), None, None, ), ) host_config = config_cache.get_host_config(hostname) static_check_parameters = [ service.parameters for service in check_table._get_static_check_entries( config_cache, host_config) ] entries = config._get_checkgroup_parameters( config_cache, hostname, "ps", "item", "Process item", ) assert len(entries) == 1 assert entries[0] == check_group_parameters assert len(static_check_parameters) == 1 static_check_parameter = static_check_parameters[0] assert static_check_parameter == TimespecificParameters(( TimespecificParameterSet(static_parameters_default, ()), TimespecificParameterSet({}, ()), ))
def create_check_plugin( *, name: str, sections: Optional[List[str]] = None, service_name: str, discovery_function: Callable, discovery_default_parameters: Optional[Dict] = None, discovery_ruleset_name: Optional[str] = None, discovery_ruleset_type: DiscoveryRuleSetType = "merged", check_function: Callable, check_default_parameters: Optional[Dict] = None, check_ruleset_name: Optional[str] = None, cluster_check_function: Optional[Callable] = None, module: Optional[str] = None, validate_item: bool = True, ) -> CheckPlugin: """Return an CheckPlugin object after validating and converting the arguments one by one For a detailed description of the parameters please refer to the exposed function in the 'register' namespace of the API. """ plugin_name = CheckPluginName(name) subscribed_sections = create_subscribed_sections(sections, plugin_name) _validate_service_name(plugin_name, service_name) requires_item = _requires_item(service_name) # validate discovery arguments validate_default_parameters( "discovery", discovery_ruleset_name, discovery_default_parameters, ) _validate_discovery_ruleset( discovery_ruleset_name, discovery_default_parameters, ) _validate_discovery_ruleset_type(discovery_ruleset_type, ) validate_function_arguments( type_label="discovery", function=discovery_function, has_item=False, has_params=discovery_ruleset_name is not None, sections=subscribed_sections, ) disco_func = _filter_discovery(discovery_function, requires_item, validate_item) disco_params = discovery_default_parameters or {} disco_ruleset_name = RuleSetName( discovery_ruleset_name) if discovery_ruleset_name else None # validate check arguments validate_default_parameters( "check", check_ruleset_name, check_default_parameters, ) _validate_check_ruleset( check_ruleset_name, check_default_parameters, ) validate_function_arguments( type_label="check", function=check_function, has_item=requires_item, has_params=check_default_parameters is not None, sections=subscribed_sections, ) if cluster_check_function is None: cluster_check_function = unfit_for_clustering_wrapper(check_function) else: validate_function_arguments( type_label="cluster_check", function=cluster_check_function, has_item=requires_item, has_params=check_ruleset_name is not None, sections=subscribed_sections, ) cluster_check_function = _filter_check(cluster_check_function) return CheckPlugin( name=plugin_name, sections=subscribed_sections, service_name=service_name, discovery_function=disco_func, discovery_default_parameters=disco_params, discovery_ruleset_name=disco_ruleset_name, discovery_ruleset_type=discovery_ruleset_type, check_function=_filter_check(check_function), check_default_parameters=check_default_parameters or {}, check_ruleset_name=RuleSetName(check_ruleset_name) if check_ruleset_name else None, cluster_check_function=cluster_check_function, module=module, )
section_plugin = create_snmp_section_plugin( name="if64adm", parse_function=if64.parse_if64_if6adm, trees=[ SNMPTree( base=if64.BASE_OID, oids=if64.END_OIDS + [ "2.2.1.7", # ifAdminStatus ], ), ], detect_spec=never_detect, # does not matter what we put here rule_dependent_detect_spec=SNMPRuleDependentDetectSpec( [RuleSetName('if_disable_if64_hosts'), RuleSetName('use_if64adm')], compute_detect_spec_if64adm, ), ) add_section_plugin(section_plugin) assert section_plugin.rule_dependent_detect_spec for discovery_ruleset in section_plugin.rule_dependent_detect_spec.rulesets: add_discovery_ruleset(discovery_ruleset) # ================================================================================================== register.check_plugin( name="if64adm", service_name="Interface %s", discovery_ruleset_name="inventory_if_rules", discovery_ruleset_type="all",