Пример #1
0
def test_rule_from_config_tuple(
    request_context,
    ruleset_name,
    rule_spec,
    expected_attributes,
    rule_options: Optional[RuleOptionsSpec],
):
    if rule_options is not None:
        rule_spec = rule_spec + (rule_options, )

    ruleset = rulesets.Ruleset(
        ruleset_name, ruleset_matcher.get_tag_to_group_map(active_config.tags))
    ruleset.from_config(hosts_and_folders.Folder.root_folder(), [rule_spec])
    rule = ruleset.get_folder_rules(hosts_and_folders.Folder.root_folder())[0]

    for key, val in expected_attributes.items():
        if key == "conditions":
            assert rule.conditions._to_config() == val
        else:
            assert getattr(rule, key) == val

    if rule_options is not None:
        assert rule.rule_options == RuleOptions.from_config(rule_options)
    else:
        assert rule.rule_options == RuleOptions.from_config({})
Пример #2
0
    def _parse_dict_rule(
        cls,
        folder: CREFolder,
        ruleset: Ruleset,
        rule_config: Dict[Any, Any],
    ) -> Rule:
        # cmk-update-config uses this to load rules from the config file for rewriting them To make
        # this possible, we need to accept missing "id" fields here. During runtime this is not
        # needed anymore, since cmk-update-config has updated all rules from the user configuration.
        id_ = rule_config["id"] if "id" in rule_config else utils.gen_id()
        assert isinstance(id_, str)

        rule_options = rule_config.get("options", {})
        assert all(isinstance(k, str) for k in rule_options)

        conditions = rule_config["condition"].copy()

        # Is known because of the folder associated with this object. Remove the
        # rendundant information here. It will be added dynamically in to_config()
        # for writing it back
        conditions.pop("host_folder", None)

        rule_conditions = RuleConditions(folder.path())
        rule_conditions.from_config(conditions)

        return cls(
            id_,
            folder,
            ruleset,
            rule_conditions,
            RuleOptions.from_config(rule_options),
            rule_config["value"],
        )
Пример #3
0
def create_rule(param):
    """Create rule"""
    body = param["body"]
    folder = body["folder"]
    value = body["value_raw"]
    rulesets = watolib.FolderRulesets(folder)
    rulesets.load()
    try:
        ruleset = rulesets.get(body["ruleset"])
    except KeyError:
        return problem(
            status=400,
            detail=f"Ruleset {body['ruleset']!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 = 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 = watolib.Rule(
        gen_id(),
        folder,
        ruleset,
        RuleConditions(
            host_folder=folder,
            host_tags=body["conditions"].get("host_tag"),
            host_labels=body["conditions"].get("host_label"),
            host_name=body["conditions"].get("host_name"),
            service_description=body["conditions"].get("service_description"),
            service_labels=body["conditions"].get("service_label"),
        ),
        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 watolib
    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(),
    )
    return serve_json(_serialize_rule(folder, index, rule))
Пример #4
0
def test_rule_from_config_dict(
    request_context,
    ruleset_name,
    rule_spec: RuleSpec,
    expected_attributes,
    rule_options: RuleOptionsSpec,
):
    rule_spec = rule_spec.copy()
    if rule_options is not None:
        rule_spec["options"] = rule_options

    rule = rulesets.Rule.from_config(
        hosts_and_folders.Folder.root_folder(),
        _ruleset(ruleset_name),
        rule_spec,
    )

    for key, val in expected_attributes.items():
        if key == "conditions":
            assert rule.conditions._to_config() == val
        else:
            assert getattr(rule, key) == val

    if rule_options is not None:
        assert rule.rule_options == RuleOptions.from_config(rule_options)
    else:
        assert rule.rule_options == RuleOptions.from_config({})

    # test for synchronous to_dict on the way. Except when rule_spec.id was not set, because the ID
    # is added dynamically when processing such rules.
    rule_spec_for_config = rule_spec.copy()
    new_rule_config = dict(rule.to_config())

    if "id" in rule_spec:
        assert new_rule_config == rule_spec_for_config
    else:
        assert new_rule_config["id"] == "1"
        del new_rule_config["id"]
        assert new_rule_config == rule_spec_for_config
Пример #5
0
 def from_ruleset_defaults(cls, folder: CREFolder, ruleset: Ruleset) -> Rule:
     return Rule(
         utils.gen_id(),
         folder,
         ruleset,
         RuleConditions(folder.path()),
         RuleOptions(
             disabled=False,
             description="",
             comment="",
             docu_url="",
             predefined_condition_id=None,
         ),
         ruleset.valuespec().default_value(),
     )
Пример #6
0
def test_rule_from_ruleset_defaults(request_context, ruleset_name,
                                    default_value, is_binary):
    ruleset = _ruleset(ruleset_name)
    rule = rulesets.Rule.from_ruleset_defaults(
        hosts_and_folders.Folder.root_folder(), ruleset)
    assert isinstance(rule.conditions, rulesets.RuleConditions)
    assert rule.rule_options == RuleOptions(
        disabled=False,
        description="",
        comment="",
        docu_url="",
        predefined_condition_id=None,
    )
    assert rule.value == default_value
    assert rule.ruleset.rulespec.is_binary_ruleset == is_binary