Esempio n. 1
0
    def _get_static_check_entries(self, host_config):
        # type: (config.HostConfig) -> Iterator[Service]
        entries = []  # type: List[Service]
        for _checkgroup_name, check_plugin_name, item, params in host_config.static_checks:
            if config.has_timespecific_params(params):
                timespec_params = [params]
                params = {}
            else:
                timespec_params = []

            new_params = config.compute_check_parameters(
                host_config.hostname, check_plugin_name, item, params)

            if timespec_params:
                params = config.set_timespecific_param_list(
                    timespec_params, new_params)
            else:
                params = new_params

            descr = config.service_description(host_config.hostname,
                                               check_plugin_name, item)
            entries.append(Service(check_plugin_name, item, descr, params))

        # Note: We need to reverse the order of the static_checks. This is
        # because users assume that earlier rules have precedence over later
        # ones. For static checks that is important if there are two rules for
        # a host with the same combination of check type and item.
        return reversed(entries)
Esempio n. 2
0
    def _get_static_check_entries(self, host_config):
        # type: (config.HostConfig) -> Iterator[Service]
        entries = []  # type: List[Service]
        for _checkgroup_name, check_plugin_name, item, params in host_config.static_checks:
            # Make sure, that for dictionary based checks at least those keys
            # defined in the factory settings are present in the parameters
            # TODO: Isn't this done during checking for all checks in more generic code?
            if isinstance(params,
                          dict) and check_plugin_name in config.check_info:
                def_levels_varname = config.check_info[check_plugin_name].get(
                    "default_levels_variable")
                if def_levels_varname:
                    for key, value in config.factory_settings.get(
                            def_levels_varname, {}).items():
                        if key not in params:
                            params[key] = value

            descr = config.service_description(host_config.hostname,
                                               check_plugin_name, item)
            entries.append(Service(check_plugin_name, item, descr, params))

        # Note: We need to reverse the order of the static_checks. This is
        # because users assume that earlier rules have precedence over later
        # ones. For static checks that is important if there are two rules for
        # a host with the same combination of check type and item.
        return reversed(entries)
Esempio n. 3
0
def _get_static_check_entries(
    config_cache: config.ConfigCache,
    host_config: config.HostConfig,
) -> Iterator[Service]:
    entries: List[Service] = []
    for _checkgroup_name, check_plugin_name_str, item, params in host_config.static_checks:
        # TODO (mo): centralize maincheckify: CMK-4295
        # in this case: move it to the transform of the static services rule.
        check_plugin_name = CheckPluginName(maincheckify(check_plugin_name_str))

        descr = config.service_description(host_config.hostname, check_plugin_name, item)
        new_parameters = config.compute_check_parameters(
            config_cache.host_of_clustered_service(host_config.hostname, descr),
            check_plugin_name,
            item,
            {},
            configured_parameters=TimespecificParameters((params,)),
        )

        entries.append(Service(check_plugin_name, item, descr, new_parameters))

    # Note: We need to reverse the order of the static_checks. This is
    # because users assume that earlier rules have precedence over later
    # ones. For static checks that is important if there are two rules for
    # a host with the same combination of check type and item.
    return reversed(entries)
Esempio n. 4
0
def _get_static_check_entries(
    config_cache: config.ConfigCache,
    host_config: config.HostConfig,
) -> Iterator[ConfiguredService]:
    entries = []
    for _checkgroup_name, check_plugin_name, item, params in host_config.static_checks:

        descr = config.service_description(host_config.hostname, check_plugin_name, item)
        entries.append(
            ConfiguredService(
                check_plugin_name=check_plugin_name,
                item=item,
                description=descr,
                parameters=config.compute_check_parameters(
                    config_cache.host_of_clustered_service(host_config.hostname, descr),
                    check_plugin_name,
                    item,
                    {},
                    configured_parameters=TimespecificParameters((params,)),
                ),
                discovered_parameters=None,
                service_labels={},
            )
        )

    # Note: We need to reverse the order of the static_checks. This is
    # because users assume that earlier rules have precedence over later
    # ones. For static checks that is important if there are two rules for
    # a host with the same combination of check type and item.
    return reversed(entries)
Esempio n. 5
0
def _get_static_check_entries(host_config: config.HostConfig,) -> Iterator[Service]:
    entries: List[Service] = []
    for _checkgroup_name, check_plugin_name_str, item, params in host_config.static_checks:
        # TODO (mo): centralize maincheckify: CMK-4295
        check_plugin_name = CheckPluginName(maincheckify(check_plugin_name_str))

        if config.has_timespecific_params(params):
            timespec_params = [params]
            params = {}
        else:
            timespec_params = []

        new_params = config.compute_check_parameters(
            host_config.hostname,
            check_plugin_name,
            item,
            params,
            for_static_checks=True,
        )

        if timespec_params:
            params = config.set_timespecific_param_list(timespec_params, new_params)
        else:
            params = new_params

        descr = config.service_description(host_config.hostname, check_plugin_name, item)
        entries.append(Service(check_plugin_name, item, descr, params))

    # Note: We need to reverse the order of the static_checks. This is
    # because users assume that earlier rules have precedence over later
    # ones. For static checks that is important if there are two rules for
    # a host with the same combination of check type and item.
    return reversed(entries)
Esempio n. 6
0
def update_service_info(config_cache, hostnames):
    pnp_files_present = False

    for hostname in hostnames:
        for service in config_cache.get_autochecks_of(hostname):
            if service.check_plugin_name in CHECKS_USING_DF_INCLUDE:
                servicedesc = config.service_description(hostname, service.check_plugin_name,
                                                         service.item)
                update_files(hostname, servicedesc, service.item, 'cmc')
                pnp_files_present |= update_files(hostname, servicedesc, service.item, 'pnp4nagios')
Esempio n. 7
0
def _filter_service_by_patterns(
    host_name: HostName,
    service: Service,
    whitelist: Pattern[str],
    blacklist: Pattern[str],
) -> bool:
    #TODO Call sites: Why do we not use discovered_service.description;
    # Is discovered_service.description already finalized as
    # in config.service_description?
    # (mo): we should indeed make sure that is the case, and use it
    description = config.service_description(host_name, service.check_plugin_name, service.item)
    return whitelist.match(description) is not None and blacklist.match(description) is None
Esempio n. 8
0
def update_service_info(config_cache, hostnames):
    cmc_capable = not cmk.utils.version.is_raw_edition()

    rename_journal = {}
    for hostname in hostnames:
        for entry in cmk.base.autochecks.AutochecksStore(hostname).read():
            if entry.check_plugin_name not in CHECKS_USING_DF_INCLUDE:
                continue

            description = config.service_description(hostname, entry.check_plugin_name, entry.item)

            if cmc_capable:
                update_files(hostname, description, entry.item, "cmc")
            rename_journal.update(update_files(hostname, description, entry.item, "pnp4nagios"))

    update_journal(rename_journal)
Esempio n. 9
0
def _parse_autocheck_entry(hostname, entry):
    # type: (HostName, Union[ast.Tuple, ast.Dict]) -> Optional[DiscoveredService]
    if isinstance(entry, ast.Tuple):
        ast_check_plugin_name, ast_item, ast_parameters_unresolved = _parse_pre_16_tuple_autocheck_entry(
            entry)
        ast_service_labels = ast.Dict()
    elif isinstance(entry, ast.Dict):
        ast_check_plugin_name, ast_item, ast_parameters_unresolved, ast_service_labels = \
            _parse_dict_autocheck_entry(entry)
    else:
        raise Exception("Invalid autocheck: Wrong type: %r" % entry)

    if not isinstance(ast_check_plugin_name, ast.Str):
        raise Exception("Invalid autocheck: Wrong check plugin type: %r" %
                        ast_check_plugin_name)
    check_plugin_name = ast_check_plugin_name.s

    item = None  # type: Item
    if isinstance(ast_item, ast.Str):
        item = ast_item.s
    elif isinstance(ast_item, ast.Num):
        item = "%s" % int(ast_item.n)
    elif isinstance(ast_item, ast.Name) and ast_item.id == "None":
        item = None
    else:
        raise Exception("Invalid autocheck: Wrong item type: %r" % ast_item)

    # With Check_MK 1.2.7i3 items are now defined to be unicode
    # strings. Convert items from existing autocheck files for
    # compatibility.
    if isinstance(item, str):
        item = convert_to_unicode(item)

    try:
        description = config.service_description(hostname, check_plugin_name,
                                                 item)
    except Exception:
        return None  # ignore

    return DiscoveredService(
        check_plugin_name,
        item,
        description,
        _parse_unresolved_parameters_from_ast(ast_parameters_unresolved),
        service_labels=_parse_discovered_service_label_from_ast(
            ast_service_labels))
Esempio n. 10
0
def update_service_info(config_cache, hostnames, args):
    pnp_files_present = False
    if args.dry_run:
        logger.info("Files to be updated:")

    for hostname in hostnames:
        for service in config_cache.get_autochecks_of(hostname):
            if service.check_plugin_name in CHECKS_USING_DF_INCLUDE:
                servicedesc = config.service_description(
                    hostname, service.check_plugin_name, service.item)
                update_files(args, hostname, servicedesc, service.item, 'cmc')
                pnp_files_present |= update_files(args, hostname, servicedesc,
                                                  service.item, 'pnp4nagios')

    if args.dry_run and pnp_files_present:
        logger.info("Journal files will be updated")
        return
Esempio n. 11
0
def _enriched_discovered_services(
    host_name: HostName,
    check_plugin_name: CheckPluginName,
    plugins_services: checking_classes.DiscoveryResult,
) -> Generator[Service, None, None]:
    for service in plugins_services:
        description = config.service_description(host_name, check_plugin_name, service.item)
        # make sanity check
        if not description:
            console.error(
                f"{host_name}: {check_plugin_name} returned empty service description - ignoring it.\n"
            )
            continue

        yield Service(
            check_plugin_name=check_plugin_name,
            item=service.item,
            description=description,
            parameters=unwrap_parameters(service.parameters),
            # Convert from APIs ServiceLabel to internal ServiceLabel
            service_labels=DiscoveredServiceLabels(*(ServiceLabel(*l) for l in service.labels)),
        )
Esempio n. 12
0
def service_description(hostname, check_plugin_name, item):
    # type: (HostName, CheckPluginName, Item) -> Text
    _load_config()
    return config.service_description(hostname, check_plugin_name, item)
Esempio n. 13
0
    def _read_raw_autochecks_of(self, hostname):
        # type: (HostName) -> List[Service]
        """Read automatically discovered checks of one host"""
        basedir = cmk.utils.paths.autochecks_dir
        filepath = basedir + '/' + hostname + '.mk'

        result = []  # type: List[Service]
        if not os.path.exists(filepath):
            return result

        check_config = config.get_check_variables()
        try:
            cmk.base.console.vverbose("Loading autochecks from %s\n", filepath)
            autochecks_raw = eval(
                open(filepath).read().decode("utf-8"), check_config,
                check_config)  # type: List[Dict]
        except SyntaxError as e:
            cmk.base.console.verbose("Syntax error in file %s: %s\n",
                                     filepath,
                                     e,
                                     stream=sys.stderr)
            if cmk.utils.debug.enabled():
                raise
            return result
        except Exception as e:
            cmk.base.console.verbose("Error in file %s:\n%s\n", filepath, e, stream=sys.stderr)
            if cmk.utils.debug.enabled():
                raise
            return result

        for entry in autochecks_raw:
            if isinstance(entry, tuple):
                raise MKGeneralException(
                    "Invalid check entry '%r' of host '%s' (%s) found. This "
                    "entry is in pre Checkmk 1.6 format and needs to be converted. This is "
                    "normally done by \"cmk-update-config -v\" during \"omd update\". Please "
                    "execute \"cmk-update-config -v\" for convertig the old configuration." %
                    (entry, hostname, filepath))

            labels = DiscoveredServiceLabels()
            for label_id, label_value in entry["service_labels"].items():
                labels.add_label(ServiceLabel(label_id, label_value))

            # With Check_MK 1.2.7i3 items are now defined to be unicode strings. Convert
            # items from existing autocheck files for compatibility. TODO remove this one day
            item = entry["item"]
            if isinstance(item, str):
                item = convert_to_unicode(item)

            if not isinstance(entry["check_plugin_name"], six.string_types):
                raise MKGeneralException("Invalid entry '%r' in check table of host '%s': "
                                         "The check type must be a string." % (entry, hostname))

            check_plugin_name = str(entry["check_plugin_name"])

            try:
                description = config.service_description(hostname, check_plugin_name, item)
            except Exception:
                continue  # ignore

            result.append(
                Service(
                    check_plugin_name=check_plugin_name,
                    item=item,
                    description=description,
                    parameters=entry["parameters"],
                    service_labels=labels,
                ))

        return result
Esempio n. 14
0
def service_description(hostname: HostName, check_plugin_name: CheckPluginNameStr,
                        item: Item) -> str:
    _load_config()
    return config.service_description(hostname, CheckPluginName(check_plugin_name), item)
Esempio n. 15
0
def service_description(hostname, check_plugin_name, item):
    # type: (str, str, Text) -> Text
    _load_config()
    return config.service_description(hostname, check_plugin_name, item)