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(), )
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))