Пример #1
0
    def discovery_migration_wrapper(section):
        disco_func = check_info_dict.get("inventory_function")
        if not callable(disco_func):  # never discover:
            return

        original_discovery_result = disco_func(section)
        if not original_discovery_result:
            return

        for element in original_discovery_result:
            if isinstance(element, (HostLabel, DiscoveredHostLabels)):
                # these are dealt with in the host_label_function!
                continue

            if isinstance(element, LegacyService):
                yield Service(
                    item=element.item,
                    parameters=wrap_parameters(element.parameters or {}),
                    labels=list(element.service_labels),
                )
            elif isinstance(element, tuple) and len(element) in (2, 3):
                parameters = _resolve_string_parameters(element[-1], check_name)
                service = Service(
                    item=element[0] or None,
                    parameters=wrap_parameters(parameters or {}),
                )
                # nasty hack for nasty plugins:
                # Bypass validation. Item should be None or non-empty string!
                service._item = element[0]  # pylint: disable=protected-access
                yield service
            else:
                # just let it through. Base must deal with bogus return types anyway.
                yield element
Пример #2
0
    def discovery_migration_wrapper(section):
        disco_func = check_info_dict.get("inventory_function")
        if not callable(disco_func):  # never discover:
            return

        original_discovery_result = disco_func(section)
        if not original_discovery_result:
            return

        for element in original_discovery_result:
            if isinstance(element, tuple) and len(element) in (2, 3):
                parameters = _resolve_string_parameters(
                    element[-1], check_name, get_check_context)
                service = Service(
                    item=element[0] or None,
                    parameters=wrap_parameters(parameters or {}),
                )
                # nasty hack for nasty plugins:
                # Bypass validation. Item should be None or non-empty string!
                service = service._replace(item=element[0])
                yield service
            else:
                try:
                    yield Service(
                        item=element.item,
                        parameters=wrap_parameters(element.parameters or {}),
                        labels=[
                            ServiceLabel(l.name, l.value)
                            for l in element.service_labels
                        ],
                    )
                except AttributeError:
                    # just let it through. Base must deal with bogus return types anyway.
                    yield element
Пример #3
0
def _check_preview_table_row(
    *,
    host_config: config.HostConfig,
    ip_address: Optional[HostAddress],
    service: Service,
    check_source: str,
    parsed_sections_broker: ParsedSectionsBroker,
    found_on_nodes: List[HostName],
    value_store_manager: ValueStoreManager,
) -> CheckPreviewEntry:
    plugin = agent_based_register.get_check_plugin(service.check_plugin_name)
    params = _preview_params(host_config.hostname, service, plugin,
                             check_source)

    if check_source in ['legacy', 'active', 'custom']:
        exitcode = None
        output = u"WAITING - %s check, cannot be done offline" % check_source.title(
        )
        ruleset_name: Optional[RulesetName] = None
    else:

        ruleset_name = (str(plugin.check_ruleset_name)
                        if plugin and plugin.check_ruleset_name else None)
        wrapped_params = (Parameters(wrap_parameters(params)) if plugin
                          and plugin.check_default_parameters is not None else
                          None)

        exitcode, output, _perfdata = checking.get_aggregated_result(
            parsed_sections_broker,
            host_config,
            ip_address,
            service,
            plugin,
            lambda p=wrapped_params:
            p,  # type: ignore[misc]  # "type of lambda"
            value_store_manager=value_store_manager,
            persist_value_store_changes=False,  # never during discovery
        ).result

    # Service discovery never uses the perfdata in the check table. That entry
    # is constantly discarded, yet passed around(back and forth) as part of the
    # discovery result in the request elements. Some perfdata VALUES are not parsable
    # by ast.literal_eval such as "inf" it lead to ValueErrors. Thus keep perfdata empty
    perfdata: List[MetricTuple] = []

    return (
        _preview_check_source(host_config.hostname, service, check_source),
        str(service.check_plugin_name),
        ruleset_name,
        service.item,
        service.parameters,
        params,
        service.description,
        exitcode,
        output,
        perfdata,
        service.service_labels.to_dict(),
        found_on_nodes,
    )
Пример #4
0
    def discovery_migration_wrapper(section):
        disco_func = check_info_dict.get("inventory_function")
        if not callable(disco_func):  # never discover:
            return

        original_discovery_result = disco_func(section)
        if not original_discovery_result:
            return

        for element in original_discovery_result:
            if isinstance(element, tuple) and len(element) in (2, 3):
                item, raw_params = element[0], element[-1]
                if item is not None and not isinstance(item, str):
                    raise ValueError("item must be None or of type `str`")

                parameters = _resolve_string_parameters(
                    raw_params, check_name, get_check_context)
                service = Service(
                    item=None,  # will be replaced
                    parameters=wrap_parameters(parameters or {}),
                )
                # nasty hack for nasty plugins: item = ''
                # Bypass validation. Item should be None or non-empty string!
                service = service._replace(item=item)
                yield service
                continue

            with suppress(AttributeError):
                yield Service(
                    item=element.item,
                    parameters=wrap_parameters(element.parameters or {}),
                    labels=[
                        ServiceLabel(l.name, l.value)
                        for l in element.service_labels
                    ],
                )
                continue

            # just let it through. Base must deal with bogus return types anyway.
            yield element
Пример #5
0
def _create_wrapped_parameters(check_plugin_name: str,
                               check_info_dict: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """compute default parameters and wrap them in a dictionary"""
    default_parameters = get_default_parameters(
        check_info_dict,
        config.factory_settings,
        config.get_check_context(check_plugin_name),
    )
    if default_parameters is None:
        return {} if check_info_dict.get("group") else None

    if isinstance(default_parameters, dict):
        return default_parameters
    return wrap_parameters(default_parameters)
Пример #6
0
def _create_wrapped_parameters(
    check_plugin_name: str,
    check_info_dict: Dict[str, Any],
    factory_settings: Dict[str, Dict],
    get_check_context: Callable,
) -> ParametersTypeAlias:
    """compute default parameters and wrap them in a dictionary"""
    default_parameters = _get_default_parameters(
        check_info_dict,
        factory_settings,
        get_check_context(check_plugin_name),
    )
    if default_parameters is None:
        return {}

    if isinstance(default_parameters, dict):
        return default_parameters
    return wrap_parameters(default_parameters)
Пример #7
0
def get_check_preview(
    *,
    host_name: HostName,
    max_cachefile_age: int,
    use_cached_snmp_data: bool,
    on_error: str,
) -> Tuple[CheckPreviewTable, QualifiedDiscovery[HostLabel]]:
    """Get the list of service of a host or cluster and guess the current state of
    all services if possible"""
    config_cache = config.get_config_cache()
    host_config = config_cache.get_host_config(host_name)

    ip_address = None if host_config.is_cluster else config.lookup_ip_address(
        host_config)
    discovery_parameters = DiscoveryParameters(
        on_error=on_error,
        load_labels=True,
        save_labels=False,
        only_host_labels=False,
    )

    _set_cache_opts_of_checkers(use_cached_snmp_data=use_cached_snmp_data)

    parsed_sections_broker, _source_results = make_broker(
        config_cache=config_cache,
        host_config=host_config,
        ip_address=ip_address,
        mode=Mode.DISCOVERY,
        file_cache_max_age=max_cachefile_age,
        selected_sections=NO_SELECTION,
        fetcher_messages=(),
        force_snmp_cache_refresh=not use_cached_snmp_data,
        on_scan_error=on_error,
    )

    grouped_services, host_label_result = _get_host_services(
        host_config,
        ip_address,
        parsed_sections_broker,
        discovery_parameters,
    )

    table: CheckPreviewTable = []
    for check_source, services_with_nodes in grouped_services.items():
        for service, found_on_nodes in services_with_nodes:
            plugin = agent_based_register.get_check_plugin(
                service.check_plugin_name)
            params = _preview_params(host_name, service, plugin, check_source)

            if check_source in ['legacy', 'active', 'custom']:
                exitcode = None
                output = u"WAITING - %s check, cannot be done offline" % check_source.title(
                )
                ruleset_name: Optional[RulesetName] = None
            else:

                ruleset_name = (str(plugin.check_ruleset_name) if plugin
                                and plugin.check_ruleset_name else None)
                wrapped_params = (
                    Parameters(wrap_parameters(params)) if plugin
                    and plugin.check_default_parameters is not None else None)

                exitcode, output, _perfdata = checking.get_aggregated_result(
                    parsed_sections_broker,
                    host_config,
                    ip_address,
                    service,
                    plugin,
                    lambda p=wrapped_params:
                    p,  # type: ignore[misc]  # "type of lambda"
                ).result

            # Service discovery never uses the perfdata in the check table. That entry
            # is constantly discarded, yet passed around(back and forth) as part of the
            # discovery result in the request elements. Some perfdata VALUES are not parsable
            # by ast.literal_eval such as "inf" it lead to ValueErrors. Thus keep perfdata empty
            perfdata: List[MetricTuple] = []
            table.append((
                _preview_check_source(host_name, service, check_source),
                str(service.check_plugin_name),
                ruleset_name,
                service.item,
                service.parameters,
                params,
                service.description,
                exitcode,
                output,
                perfdata,
                service.service_labels.to_dict(),
                found_on_nodes,
            ))

    return table, host_label_result
Пример #8
0
def test_noop_wrap_parameters():
    assert {"levels": (1, 2)} == wrap_parameters({"levels": (1, 2)})
Пример #9
0
def test_un_wrap_parameters(params):
    wrapped = wrap_parameters(params)
    assert isinstance(wrapped, dict)
    assert unwrap_parameters(wrapped) == params