示例#1
0
    def page(self):
        all_rulesets = watolib.AllRulesets()
        all_rulesets.load()

        # Object type specific detail information
        if self._service:
            self._show_service_info(all_rulesets)
        else:
            self._show_host_info()

        last_maingroup = None
        for groupname in sorted(
                rulespec_group_registry.get_host_rulespec_group_names()):
            maingroup = groupname.split("/")[0]
            for rulespec in sorted(rulespec_registry.get_by_group(groupname),
                                   key=lambda x: x.title):
                if (rulespec.item_type == 'service') == (not self._service):
                    continue  # This rule is not for hosts/services

                # Open form for that group here, if we know that we have at least one rule
                if last_maingroup != maingroup:
                    last_maingroup = maingroup
                    rulegroup = watolib.get_rulegroup(maingroup)
                    forms.header(rulegroup.title,
                                 isopen=maingroup == "monconf",
                                 narrow=True,
                                 css="rulesettings")
                    html.help(rulegroup.help)

                self._output_analysed_ruleset(all_rulesets,
                                              rulespec,
                                              svc_desc_or_item=self._service,
                                              svc_desc=self._service)

        forms.end()
示例#2
0
def list_rules(param):
    """List rules"""
    all_sets = watolib.AllRulesets()
    all_sets.load()
    ruleset_name = param["ruleset_name"]

    try:
        ruleset = all_sets.get(ruleset_name.replace("-", ":"))
    except KeyError:
        return problem(
            status=400,
            title="Unknown ruleset.",
            detail=f"The ruleset of name {ruleset_name!r} is not known.",
        )

    result = []
    for folder, index, rule in ruleset.get_rules():
        result.append(_serialize_rule(folder, index, rule))

    return serve_json(
        constructors.collection_object(
            domain_type="rule",
            value=result,
            extensions={
                "found_rules": len(result),
            },
        )
    )
示例#3
0
 def _find_usages_in_time_specific_parameters(
         self, tpname: str) -> List[TimeperiodUsage]:
     used_in: List[TimeperiodUsage] = []
     rulesets = watolib.AllRulesets()
     rulesets.load()
     for ruleset in rulesets.get_rulesets().values():
         vs = ruleset.valuespec()
         if not isinstance(vs,
                           cmk.gui.plugins.wato.utils.TimeperiodValuespec):
             continue
         for rule_folder, rule_index, rule in ruleset.get_rules():
             if not vs.is_active(rule.value):
                 continue
             for index, (rule_tp_name,
                         _value) in enumerate(rule.value["tp_values"]):
                 if rule_tp_name != tpname:
                     continue
                 edit_url = watolib.folder_preserving_link([
                     ("mode", "edit_rule"),
                     ("back_mode", "timeperiods"),
                     ("varname", ruleset.name),
                     ("rulenr", rule_index),
                     ("rule_folder", rule_folder.path()),
                 ])
                 used_in.append(
                     (_("Time specific check parameter #%d") % (index + 1),
                      edit_url))
     return used_in
示例#4
0
文件: webapi.py 项目: petrows/checkmk
    def _get_used_tags_from_rules(self):
        used_tags = set()

        all_rulesets = watolib.AllRulesets()
        all_rulesets.load()
        for ruleset in all_rulesets.get_rulesets().values():
            for _folder, _rulenr, rule in ruleset.get_rules():
                for tag_group_id, tag_spec in rule.conditions.host_tags.items():
                    if isinstance(tag_spec, dict):
                        if "$ne" in tag_spec:
                            used_tags.add((tag_group_id, tag_spec["$ne"]))
                            continue

                        if "$or" in tag_spec:
                            for tag_id in tag_spec["$or"]:
                                used_tags.add((tag_group_id, tag_id))
                            continue

                        if "$nor" in tag_spec:
                            for tag_id in tag_spec["$nor"]:
                                used_tags.add((tag_group_id, tag_id))
                            continue

                        raise NotImplementedError()

                    used_tags.add((tag_group_id, tag_spec))

        return used_tags
示例#5
0
    def _save_service_enable_disable_rules(self, services, value):
        if not services:
            return

        rulesets = watolib.AllRulesets()
        rulesets.load()

        try:
            ruleset = rulesets.get("ignored_services")
        except KeyError:
            ruleset = watolib.Ruleset("ignored_services",
                                      ruleset_matcher.get_tag_to_group_map(config.tags))

        modified_folders = []

        service_patterns = [service_description_to_condition(s) for s in services]
        modified_folders += self._remove_from_rule_of_host(ruleset,
                                                           service_patterns,
                                                           value=not value)

        # Check whether or not the service still needs a host specific setting after removing
        # the host specific setting above and remove all services from the service list
        # that are fine without an additional change.
        for service in list(services):
            value_without_host_rule = ruleset.analyse_ruleset(self._host.name(), service,
                                                              service)[0]
            if (not value and value_without_host_rule in [None, False]) \
               or value == value_without_host_rule:
                services.remove(service)

        service_patterns = [service_description_to_condition(s) for s in services]
        modified_folders += self._update_rule_of_host(ruleset, service_patterns, value=value)

        for folder in modified_folders:
            rulesets.save_folder(folder)
示例#6
0
文件: webapi.py 项目: PLUTEX/checkmk
    def _get_used_tags_from_rules(
        self,
    ) -> Set[Tuple[TagID, Optional[TagID]]]:
        used_tags: Set[Tuple[TagID, Optional[TagID]]] = set()

        all_rulesets = watolib.AllRulesets()
        all_rulesets.load()
        for ruleset in all_rulesets.get_rulesets().values():
            for _folder, _rulenr, rule in ruleset.get_rules():
                for tag_group_id, tag_spec in rule.conditions.host_tags.items():
                    if isinstance(tag_spec, dict):
                        # NOTE: mypy cannot distinguish variants of a union of TypedDicts. It would
                        # be possible via the tagged union pattern, but this would alter the dicts.
                        # https://mypy.readthedocs.io/en/stable/more_types.html#unions-of-typeddicts
                        if "$ne" in tag_spec:
                            used_tags.add((tag_group_id, tag_spec["$ne"]))  # type: ignore[typeddict-item]
                            continue

                        if "$or" in tag_spec:
                            for tag_id in tag_spec["$or"]:  # type: ignore[typeddict-item,misc]
                                used_tags.add((tag_group_id, tag_id))
                            continue

                        if "$nor" in tag_spec:
                            for tag_id in tag_spec["$nor"]:  # type: ignore[typeddict-item,misc]
                                used_tags.add((tag_group_id, tag_id))
                            continue

                        raise NotImplementedError()

                    used_tags.add((tag_group_id, tag_spec))

        return used_tags
示例#7
0
def _get_rule_by_id(rule_uuid: str) -> Tuple[watolib.Ruleset, watolib.CREFolder, int, watolib.Rule]:
    all_sets = watolib.AllRulesets()
    all_sets.load()
    for ruleset in all_sets.get_rulesets().values():
        for folder, index, rule in ruleset.get_rules():
            if rule.id == rule_uuid:
                return ruleset, folder, index, rule
    raise KeyError(f"Rule with UUID {rule_uuid} was not found.")
示例#8
0
    def _get_used_rule_tags(self):
        all_rulesets = watolib.AllRulesets()
        all_rulesets.load()
        used_tags = set()
        for ruleset in all_rulesets.get_rulesets().itervalues():
            for _folder, _rulenr, rule in ruleset.get_rules():
                for tag_spec in rule.tag_specs:
                    used_tags.add(tag_spec.lstrip("!"))

        used_tags.discard(None)
        return used_tags
示例#9
0
    def _find_usages_in_host_and_service_rules(self, tpname: str) -> List[TimeperiodUsage]:
        used_in: List[TimeperiodUsage] = []
        rulesets = watolib.AllRulesets()
        rulesets.load()
        for varname, ruleset in rulesets.get_rulesets().items():
            if not isinstance(ruleset.valuespec(), watolib.timeperiods.TimeperiodSelection):
                continue

            for _folder, _rulenr, rule in ruleset.get_rules():
                if rule.value == tpname:
                    used_in.append(("%s: %s" % (_("Ruleset"), ruleset.title()),
                                    watolib.folder_preserving_link([("mode", "edit_ruleset"),
                                                                    ("varname", varname)])))
                    break
        return used_in
示例#10
0
def list_rulesets(param):
    """Search rule sets"""
    all_sets = (watolib.FolderRulesets(param["folder"])
                if param.get("folder") else watolib.AllRulesets())
    all_sets.load()

    def _get_search_options(params):
        # We remove 'folder' because that has already been handled at the start of the endpoint.
        options = dict(params)
        if "folder" in options:
            del options["folder"]
        return options

    if search_options := _get_search_options(param):
        all_sets = watolib.SearchedRulesets(all_sets, search_options)
示例#11
0
文件: webapi.py 项目: petrows/checkmk
    def _get_rulesets_info(self, request):
        rulesets_info = {}
        all_rulesets = watolib.AllRulesets()
        all_rulesets.load()

        for varname, ruleset in all_rulesets.get_rulesets().items():
            rulesets_info[varname] = {
                "title": ruleset.title(),
                "help": ruleset.help(),
                "number_of_rules": ruleset.num_rules(),
            }
            item_help = ruleset.item_help()
            if item_help:
                rulesets_info[varname]["item_help"] = item_help

        return rulesets_info
示例#12
0
    def _save_service_enable_disable_rules(self, services, value):
        if not services:
            return

        def _compile_patterns(_services, unescaped="exclude"):
            ret = []
            for svc in _services:
                ret.append({"$regex": "%s$" % re.escape(svc)})
                if unescaped == "include":
                    ret.append({"$regex": "%s$" % svc})
            return ret

        rulesets = watolib.AllRulesets()
        rulesets.load()

        try:
            ruleset = rulesets.get("ignored_services")
        except KeyError:
            ruleset = watolib.Ruleset(
                "ignored_services",
                ruleset_matcher.get_tag_to_group_map(config.tags))

        modified_folders = []

        service_patterns = _compile_patterns(services, unescaped="include")
        modified_folders += self._remove_from_rule_of_host(ruleset,
                                                           service_patterns,
                                                           value=not value)

        # Check whether or not the service still needs a host specific setting after removing
        # the host specific setting above and remove all services from the service list
        # that are fine without an additional change.
        for service in list(services):
            value_without_host_rule = ruleset.analyse_ruleset(
                self._host.name(), service, service)[0]
            if (not value and value_without_host_rule in [None, False]) \
               or value == value_without_host_rule:
                services.remove(service)

        service_patterns = _compile_patterns(services)
        modified_folders += self._update_rule_of_host(ruleset,
                                                      service_patterns,
                                                      value=value)

        for folder in modified_folders:
            rulesets.save_folder(folder)
示例#13
0
def list_rules(param):
    """List rules"""
    all_sets = watolib.AllRulesets()
    all_sets.load()
    ruleset = all_sets.get(param["ruleset_name"].replace("-", ":"))

    result = []
    for folder, index, rule in ruleset.get_rules():
        result.append(_serialize_rule(folder, index, rule))

    return serve_json(
        constructors.collection_object(
            domain_type="rule",
            value=result,
            extensions={
                "found_rules": len(result),
            },
        )
    )
示例#14
0
def delete_rule(param):
    """Delete a rule"""
    rule_id = param["rule_id"]
    rule: watolib.Rule
    all_sets = watolib.AllRulesets()
    all_sets.load()

    found = False
    for ruleset in all_sets.get_rulesets().values():
        for _folder, _index, rule in ruleset.get_rules():
            if rule.id == rule_id:
                ruleset.delete_rule(rule)
                all_sets.save()
                found = True
    if found:
        return http.Response(status=204)

    return problem(
        status=404,
        title="Rule not found.",
        detail=f"The rule with ID {rule_id!r} could not be found.",
    )