Exemplo n.º 1
0
def test_create_check_plugin_mgmt_reserved():
    kwargs = MINIMAL_CREATION_KWARGS.copy()
    kwargs["service_name"] = "Management Interface: "
    with pytest.raises(ValueError):
        _ = check_plugins.create_check_plugin(**kwargs)

    kwargs = MINIMAL_CREATION_KWARGS.copy()
    kwargs["name"] = "mgmt_foo"
    with pytest.raises(ValueError):
        _ = check_plugins.create_check_plugin(**kwargs)

    kwargs = MINIMAL_CREATION_KWARGS.copy()
    kwargs["service_name"] = "Management Interface: "
    kwargs["name"] = "mgmt_foo"
    _ = check_plugins.create_check_plugin(**kwargs)
Exemplo n.º 2
0
def check_plugin(
    *,
    name: str,
    sections: Optional[List[str]] = None,
    service_name: str,
    discovery_function: DiscoveryFunction,
    discovery_default_parameters: Optional[Dict[str, Any]] = None,
    discovery_ruleset_name: Optional[str] = None,
    discovery_ruleset_type: DiscoveryRuleSetType = "merged",
    check_function: CheckFunction,
    check_default_parameters: Optional[Dict[str, Any]] = None,
    check_ruleset_name: Optional[str] = None,
    cluster_check_function: Optional[Callable] = None,
) -> None:
    """Register a check plugin to checkmk.

    :param name: The name of the check plugin. It must be unique. And contain only the characters
                 A-Z, a-z, 0-9 and the underscore.
    :param sections: An optional list of section names that this plugin subscribes to. The
                     corresponding sections are passed to the discovery and check function. The
                     functions arguments must be called 'section_<name1>, section_<name2>' ect.
                     Default: [<name>]
    :param service_name: The template for the service. The check function must accept 'item' as
                         first argument if and only if "%s" is present in the value of
                         "service_name".
    :param discovery_function: The discovery_function. Arguments must be 'params' (if discovery
                               parameters are defined) and 'section_<name1>, section_<name2>' ect.
                               corresponding to the `sections`.
    :param discovery_parameters: Default parameters for the discovery function. Must match the
                                 ValueSpec of the corresponding WATO ruleset.
    :param discovery_ruleset_name: The name of the discovery ruleset.
    :param check_function: The check_function. Arguments must be 'item' (if the service has an item)
                           'params' (if check parameters are defined) and 'section_<name1>,
                           section_<name2>' ect. corresponding to the `sections`.
    :param check_parameters: Default parameters for the check function. Must match the
                             ValueSpec of the corresponding WATO ruleset.
    :param check_ruleset_name: The name of the check ruleset.
    """
    plugin = create_check_plugin(
        name=name,
        sections=sections,
        service_name=service_name,
        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,
        module=get_plugin_module_name(),
    )

    if config.get_registered_check_plugin(plugin.name):
        raise ValueError("duplicate check plugin definition: %s" % plugin.name)

    config.registered_check_plugins[plugin.name] = plugin
    if plugin.discovery_ruleset_name is not None:
        config.discovery_parameter_rulesets.setdefault(
            plugin.discovery_ruleset_name, [])
Exemplo n.º 3
0
def create_check_plugin_from_legacy(check_plugin_name, check_info_dict,
                                    forbidden_names):
    # type: (str, Dict[str, Any], List[PluginName]) -> CheckPlugin

    if check_info_dict.get('extra_sections'):
        raise NotImplementedError(
            "[%s]: cannot auto-migrate plugins with extra sections" %
            check_plugin_name)

    if check_info_dict.get("node_info"):
        # We refuse to tranform these. The requirement of adding the node info
        # makes rewriting of the base code too difficult.
        # Affected Plugins must be migrated manually after CMK-4240 is done.
        raise NotImplementedError(
            "[%s]: cannot auto-migrate plugins with node info" %
            check_plugin_name)

    # make sure we haven't missed something important:
    unconsidered_keys = set(check_info_dict) - CONSIDERED_KEYS
    assert not unconsidered_keys, (
        "Unconsidered key(s) in check_info[%r]: %r" %
        (check_plugin_name, unconsidered_keys))

    new_check_name = maincheckify(check_plugin_name)

    check_default_parameters = _create_wrapped_parameters(
        check_plugin_name, check_info_dict)

    discovery_function = _create_discovery_function(check_info_dict,
                                                    check_default_parameters)

    check_ruleset_name = check_info_dict.get("group")
    if check_ruleset_name is None and check_default_parameters is not None:
        check_ruleset_name = DUMMY_RULESET_NAME
    check_function = _create_check_function(
        check_plugin_name,
        check_info_dict,
        check_ruleset_name,
    )

    return create_check_plugin(
        name=new_check_name,
        sections=[check_plugin_name.split('.', 1)[0]],
        service_name=check_info_dict['service_description'],
        management_board_option=_create_management_board_option(
            check_info_dict),
        discovery_function=discovery_function,
        discovery_default_parameters=None,  # legacy madness!
        discovery_ruleset_name=None,
        check_function=check_function,
        check_default_parameters=check_default_parameters,
        check_ruleset_name=check_ruleset_name,
        cluster_check_function=_create_cluster_legacy_mode_from_hell(
            check_function),
        forbidden_names=forbidden_names,
    )
Exemplo n.º 4
0
def check_plugin(
    *,
    name: str,
    sections: Optional[List[str]] = None,
    service_name: str,
    discovery_function: DiscoveryFunction,
    discovery_default_parameters: Optional[Dict[str, Any]] = None,
    discovery_ruleset_name: Optional[str] = None,
    check_function: CheckFunction,
    check_default_parameters: Optional[Dict[str, Any]] = None,
    check_ruleset_name: Optional[str] = None,
    management_board: Optional[management_board_enum] = None,
) -> None:
    """Register a check plugin to checkmk.

    :param name: The name of the check plugin. It must be unique. And contain only the characters
                 A-Z, a-z, 0-9 and the underscore.
    :param sections: An optional list of section names that this plugin subscribes to. The
                     corresponding sections are passed to the discovery and check function. The
                     functions arguments must be called 'section_<name1>, section_<name2>' ect.
                     Default: [<name>]
    :param service_name: The template for the service. The check function must accept 'item' as
                         first argument if and only if "%s" is present in the value of
                         "service_name".
    :param discovery_function: The discovery_function. Arguments must be 'params' (if discovery
                               parameters are defined) and 'section_<name1>, section_<name2>' ect.
                               corresponding to the `sections`.
    :param discovery_parameters: Default parameters for the discovery function. Must match the
                                 ValueSpec of the corresponding WATO ruleset.
    :param discovery_ruleset_name: The name of the discovery ruleset.
    :param check_function: The check_function. Arguments must be 'item' (if the service has an item)
                           'params' (if check parameters are defined) and 'section_<name1>,
                           section_<name2>' ect. corresponding to the `sections`.
    :param check_parameters: Default parameters for the check function. Must match the
                             ValueSpec of the corresponding WATO ruleset.
    :param check_ruleset_name: The name of the check ruleset.
    :param management_board: Explicitly tell checkmk wether this plugins services should be
                             discovered on a management board. Choices are
                             `management_board.EXCLUSIVE` or `management_board.DISABLED`
    """
    plugin = create_check_plugin(
        name=name,
        sections=sections,
        service_name=service_name,
        discovery_function=discovery_function,
        discovery_default_parameters=discovery_default_parameters,
        discovery_ruleset_name=discovery_ruleset_name,
        check_function=check_function,
        check_default_parameters=check_default_parameters,
        check_ruleset_name=check_ruleset_name,
        management_board_option=management_board,
        forbidden_names=list(config.registered_check_plugins),
    )

    config.registered_check_plugins[plugin.name] = plugin
Exemplo n.º 5
0
def create_check_plugin_from_legacy(
    check_plugin_name: str,
    check_info_dict: Dict[str, Any],
) -> CheckPlugin:

    if check_info_dict.get('extra_sections'):
        raise NotImplementedError("[%s]: cannot auto-migrate plugins with extra sections" %
                                  check_plugin_name)

    if check_info_dict.get("node_info"):
        # We refuse to tranform these. The requirement of adding the node info
        # makes rewriting of the base code too difficult.
        # Affected Plugins must be migrated manually after CMK-4240 is done.
        raise NotImplementedError("[%s]: cannot auto-migrate plugins with node info" %
                                  check_plugin_name)

    # make sure we haven't missed something important:
    unconsidered_keys = set(check_info_dict) - CONSIDERED_KEYS
    assert not unconsidered_keys, ("Unconsidered key(s) in check_info[%r]: %r" %
                                   (check_plugin_name, unconsidered_keys))

    new_check_name = maincheckify(check_plugin_name)

    check_default_parameters = _create_wrapped_parameters(check_plugin_name, check_info_dict)

    discovery_function = _create_discovery_function(check_plugin_name, check_info_dict)

    check_ruleset_name = check_info_dict.get("group")
    if check_ruleset_name is None and check_default_parameters is not None:
        check_ruleset_name = DUMMY_RULESET_NAME
    check_function = _create_check_function(
        check_plugin_name,
        check_info_dict,
        check_ruleset_name,
    )

    return create_check_plugin(
        name=new_check_name,
        sections=[check_plugin_name.split('.', 1)[0]],
        service_name=check_info_dict['service_description'],
        discovery_function=discovery_function,
        discovery_default_parameters=None,  # legacy madness!
        discovery_ruleset_name=None,
        check_function=check_function,
        check_default_parameters=check_default_parameters,
        check_ruleset_name=check_ruleset_name,
        cluster_check_function=_create_cluster_legacy_mode_from_hell(check_function),
        # Legacy check plugins may return an item even if the service description
        # does not contain a '%s'. In this case the old check API assumes an implicit,
        # trailing '%s'. Therefore, we disable this validation for legacy check plugins.
        # Once all check plugins are migrated to the new API this flag can be removed.
        validate_item=False,
    )
Exemplo n.º 6
0
def test_create_check_plugin():
    plugin = check_plugins.create_check_plugin(**MINIMAL_CREATION_KWARGS)

    assert plugin.name == CheckPluginName(MINIMAL_CREATION_KWARGS["name"])
    assert plugin.sections == [ParsedSectionName(MINIMAL_CREATION_KWARGS["name"])]
    assert plugin.service_name == MINIMAL_CREATION_KWARGS["service_name"]
    assert plugin.discovery_function.__name__ == MINIMAL_CREATION_KWARGS[
        "discovery_function"].__name__
    assert plugin.discovery_default_parameters == {}
    assert plugin.discovery_ruleset_name is None
    assert plugin.check_function.__name__ == MINIMAL_CREATION_KWARGS["check_function"].__name__
    assert plugin.check_default_parameters == {}
    assert plugin.check_ruleset_name is None
Exemplo n.º 7
0
def test_create_check_plugin():
    plugin = check_plugins.create_check_plugin(**MINIMAL_CREATION_KWARGS)

    assert plugin.name == PluginName(MINIMAL_CREATION_KWARGS["name"])
    assert plugin.sections == [PluginName(MINIMAL_CREATION_KWARGS["name"])]
    assert plugin.service_name == MINIMAL_CREATION_KWARGS["service_name"]
    assert plugin.management_board is None
    assert plugin.discovery_function is MINIMAL_CREATION_KWARGS[
        "discovery_function"]
    assert plugin.discovery_default_parameters is None
    assert plugin.discovery_ruleset_name is None
    assert plugin.check_function is MINIMAL_CREATION_KWARGS["check_function"]
    assert plugin.check_default_parameters is None
    assert plugin.check_ruleset_name is None
    assert plugin.cluster_check_function is None
Exemplo n.º 8
0
def test_create_check_plugin_mandatory(key):
    kwargs = {k: v for k, v in MINIMAL_CREATION_KWARGS.items() if k != key}
    with pytest.raises(TypeError):
        _ = check_plugins.create_check_plugin(**kwargs)
Exemplo n.º 9
0
def check_plugin(
    *,
    name: str,
    sections: Optional[List[str]] = None,
    service_name: str,
    discovery_function: DiscoveryFunction,
    discovery_default_parameters: Optional[Dict[str, Any]] = None,
    discovery_ruleset_name: Optional[str] = None,
    discovery_ruleset_type: DiscoveryRuleSetType = "merged",
    check_function: CheckFunction,
    check_default_parameters: Optional[Dict[str, Any]] = None,
    check_ruleset_name: Optional[str] = None,
    cluster_check_function: Optional[Callable] = None,
) -> None:
    """Register a check plugin to checkmk.

    Args:

      name:                     The unique name of the check plugin. It must only contain the
                                characters 'A-Z', 'a-z', '0-9' and the underscore.

      sections:                 An optional list of section names that this plugin subscribes to.
                                They correspond to the 'parsed_section_name' specified in
                                :meth:`agent_section` and :meth:`snmp_section`.
                                The corresponding sections are passed to the discovery and check
                                function. The functions arguments must be called 'section_<name1>,
                                section_<name2>' ect. Defaults to a list containing as only element
                                a name equal to the name of the check plugin.

      service_name:             The template for the service name. The check function must accept
                                'item' as first argument if and only if "%s" is present in the value
                                of "service_name".

      discovery_function:       The discovery_function. Arguments must be 'params' (if discovery
                                parameters are defined) and 'section_<name1>, section_<name2>' ect.
                                corresponding to the `sections`.
                                It is expected to be a generator of :class:`Service` instances.

      discovery_default_parameters: Default parameters for the discovery function. Must match the
                                ValueSpec of the corresponding WATO ruleset, if it exists.

      discovery_ruleset_name:   The name of the discovery ruleset.

      check_function:           The check_function. Arguments must be 'item' (if the service has an
                                item), 'params' (if check default parameters are defined) and
                                'section_<name1>, section_<name2>' ect. corresponding to the
                                `sections`.

      check_default_parameters: Default parameters for the check function.
                                Must match the ValueSpec of the corresponding WATO ruleset, if it
                                exists.

      check_ruleset_name:       The name of the check ruleset.

      cluster_check_function:   The cluster check function. If this function is not specified, the
                                corresponding services will not be available for clusters.
                                The arguments are the same as the ones for the check function,
                                except that the sections are dicts (node name -> node section).

    """
    plugin = create_check_plugin(
        name=name,
        sections=sections,
        service_name=service_name,
        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,
        module=get_validated_plugin_module_name(),
    )

    if is_registered_check_plugin(plugin.name):
        raise ValueError("duplicate check plugin definition: %s" % plugin.name)

    add_check_plugin(plugin)
    if plugin.discovery_ruleset_name is not None:
        add_discovery_ruleset(plugin.discovery_ruleset_name)