Exemplo n.º 1
0
def _instantiate_ruleset(ruleset_name, param_value):
    ruleset = Ruleset(ruleset_name, {})
    rule = Rule(Folder(''), ruleset)
    rule.value = param_value
    ruleset.append_rule(Folder(''), rule)
    assert ruleset.get_rules()
    return ruleset
Exemplo n.º 2
0
def _instantiate_ruleset(ruleset_name, param_value) -> Ruleset:
    ruleset = Ruleset(ruleset_name, {})
    rule = Rule.from_ruleset_defaults(Folder(""), ruleset)
    rule.value = param_value
    ruleset.append_rule(Folder(""), rule)
    assert ruleset.get_rules()
    return ruleset
Exemplo n.º 3
0
    def _update_rule_of_host(self, ruleset: Ruleset,
                             service_patterns: HostOrServiceConditions,
                             value: Any) -> List[CREFolder]:
        folder = self._host.folder()
        rule = self._get_rule_of_host(ruleset, value)

        if rule:
            for service_condition in service_patterns:
                if service_condition not in rule.conditions.service_description:
                    rule.conditions.service_description.append(
                        service_condition)

        elif service_patterns:
            rule = Rule.from_ruleset_defaults(folder, ruleset)

            conditions = RuleConditions(folder.path())
            conditions.host_name = [self._host.name()]
            # mypy is wrong here vor some reason:
            # Invalid index type "str" for "Union[Dict[str, str], str]"; expected type "Union[int, slice]"  [index]
            conditions.service_description = sorted(service_patterns,
                                                    key=lambda x: x["$regex"])
            rule.update_conditions(conditions)

            rule.value = value
            ruleset.prepend_rule(folder, rule)

        if rule:
            return [rule.folder]
        return []
Exemplo n.º 4
0
 def _log_rule_change(
     _rule: Rule,
     _old_folder: CREFolder,
     _message: str,
     _dest_folder: typing.Optional[CREFolder] = None,
 ):
     yield
     affected_sites = _old_folder.all_site_ids()
     if _dest_folder is not None:
         affected_sites.extend(_dest_folder.all_site_ids())
     add_change(
         "edit-rule",
         _message,
         sites=list(set(affected_sites)),
         object_ref=_rule.object_ref(),
     )
Exemplo n.º 5
0
def create_rule(param):
    """Create rule"""
    user.need_permission("wato.edit")
    user.need_permission("wato.rulesets")
    body = param["body"]
    folder: CREFolder = body["folder"]
    value = body["value_raw"]
    ruleset_name = body["ruleset"]

    folder.need_permission("write")

    rulesets = FolderRulesets(folder)
    rulesets.load()
    try:
        ruleset = rulesets.get(ruleset_name)
    except KeyError:
        return problem(
            status=400,
            detail=f"Ruleset {ruleset_name!r} could not be found.",
        )

    try:
        ruleset.valuespec().validate_value(value, "")
    except exceptions.MKUserError as exc:
        if exc.varname is None:
            title = "A field has a problem"
        else:
            field_name = strip_tags(exc.varname.replace("_p_", ""))
            title = f"Problem in (sub-)field {field_name!r}"

        return problem(
            status=400,
            detail=strip_tags(exc.message),
            title=title,
        )

    rule = Rule(
        gen_id(),
        folder,
        ruleset,
        RuleConditions(
            host_folder=folder.path(),
            host_tags=body["conditions"].get("host_tags"),
            host_labels=body["conditions"].get("host_labels"),
            host_name=body["conditions"].get("host_name"),
            service_description=body["conditions"].get("service_description"),
            service_labels=body["conditions"].get("service_labels"),
        ),
        RuleOptions.from_config(body["properties"]),
        value,
    )
    index = ruleset.append_rule(folder, rule)
    rulesets.save()
    # TODO Duplicated code is in pages/rulesets.py:2670-
    # TODO Move to
    add_change(
        "new-rule",
        _l('Created new rule #%d in ruleset "%s" in folder "%s"') %
        (index, ruleset.title(), folder.alias_path()),
        sites=folder.all_site_ids(),
        diff_text=make_diff_text({}, rule.to_log()),
        object_ref=rule.object_ref(),
    )
    rule_entry = _get_rule_by_id(rule.id)
    return serve_json(_serialize_rule(rule_entry))