def selection_id(): if not html.request.has_var('selection'): sel_id = utils.gen_id() html.request.set_var('selection', sel_id) return sel_id sel_id = html.request.var('selection') # Avoid illegal file access by introducing .. or / if not re.match("^[-0-9a-zA-Z]+$", sel_id): new_id = utils.gen_id() html.request.set_var('selection', new_id) return new_id return sel_id
def selection_id() -> str: """Generates a selection id or uses the given one""" if not request.has_var('selection'): sel_id = utils.gen_id() request.set_var('selection', sel_id) return sel_id sel_id = request.get_str_input_mandatory('selection') # Avoid illegal file access by introducing .. or / if not re.match("^[-0-9a-zA-Z]+$", sel_id): new_id = utils.gen_id() request.set_var('selection', new_id) return new_id return sel_id
def _process_notify_message(msg): msg['id'] = utils.gen_id() msg['time'] = time.time() if isinstance(msg['dest'], str): dest_what = msg['dest'] else: dest_what = msg['dest'][0] if dest_what == 'broadcast': recipients = list(config.multisite_users.keys()) elif dest_what == 'online': recipients = userdb.get_online_user_ids() elif dest_what == 'list': recipients = msg['dest'][1] else: recipients = [] num_recipients = len(recipients) num_success = {} for method in msg['methods']: num_success[method] = 0 # Now loop all notitification methods to send the notifications errors: Dict[str, List[Tuple]] = {} for user_id in recipients: for method in msg['methods']: try: handler = _notify_methods()[method]['handler'] handler(user_id, msg) num_success[method] = num_success[method] + 1 except MKInternalError as e: errors.setdefault(method, []).append((user_id, e)) message = _('The notification has been sent via<br>') message += "<table>" for method in msg['methods']: message += "<tr><td>%s</td><td>to %d of %d recipients</td></tr>" %\ (_notify_methods()[method]["title"], num_success[method], num_recipients) message += "</table>" message += _('<p>Sent notification to: %s</p>') % ', '.join(recipients) message += '<a href="%s">%s</a>' % (html.makeuri( []), _('Back to previous page')) html.show_message(HTML(message)) if errors: error_message = HTML() for method, method_errors in errors.items(): error_message += _( "Failed to send %s notifications to the following users:" ) % method table_rows = HTML() for user, exception in method_errors: table_rows += html.render_tr( html.render_td(html.render_tt(user)) + html.render_td(exception)) error_message += html.render_table(table_rows) + html.render_br() html.show_error(error_message)
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"], )
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))
def clone(self, preserve_id: bool = False) -> Rule: return Rule( self.id if preserve_id else utils.gen_id(), self.folder, self.ruleset, self.conditions.clone(), dataclasses.replace(self.rule_options), self.value, )
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(), )
def create_cmk_automation_user() -> None: secret = utils.gen_id() users = load_users(lock=True) users[UserId(u"automation")] = { 'alias': u"Check_MK Automation - used for calling web services", 'contactgroups': [], 'automation_secret': secret, 'password': cmk.gui.plugins.userdb.htpasswd.hash_password(secret), 'roles': ['admin'], 'locked': False, 'serial': 0, 'email': '', 'pager': '', 'notifications_enabled': False, 'language': 'en', } save_users(users)
def _parse_dict_rule(self, rule_config: Dict[Any, Any]) -> None: # 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. self.id = rule_config["id"] if "id" in rule_config else utils.gen_id() self.rule_options = rule_config.get("options", {}) self.value = rule_config["value"] 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) self.conditions = RuleConditions(self.folder.path()) self.conditions.from_config(conditions)
def buttonlink( self, href: str, text: str, add_transid: bool = False, obj_id: Optional[str] = None, style: Optional[str] = None, title: Optional[str] = None, disabled: Optional[str] = None, class_: Optional[CSSSpec] = None, ) -> None: if add_transid: href += "&_transid=%s" % transactions.get() if not obj_id: obj_id = utils.gen_id() # Same API as other elements: class_ can be a list or string/None css_classes = ["button", "buttonlink"] if class_: if not isinstance(class_, list): css_classes.append(class_) else: css_classes.extend(class_) self.input( name=obj_id, type_="button", id_=obj_id, class_=css_classes, value=text, style=style, title=title, disabled=disabled, onclick="location.href=%s" % json.dumps(href), )
def clone(self, preserve_id: bool = False) -> "Rule": cloned = Rule(self.folder, self.ruleset) cloned.from_config(self.to_config()) if not preserve_id: cloned.id = utils.gen_id() return cloned
def create(cls, folder, ruleset): rule = Rule(folder, ruleset) rule.id = utils.gen_id() rule.value = rule.ruleset.valuespec().default_value() return rule
def create_session_id() -> str: """Creates a random session id for the user and returns it.""" return utils.gen_id()
def _process_notify_message(msg): msg["id"] = utils.gen_id() msg["time"] = time.time() if isinstance(msg["dest"], str): dest_what = msg["dest"] else: dest_what = msg["dest"][0] if dest_what == "broadcast": recipients = list(config.multisite_users.keys()) elif dest_what == "online": recipients = userdb.get_online_user_ids() elif dest_what == "list": recipients = msg["dest"][1] else: recipients = [] num_recipients = len(recipients) num_success = {} for method in msg["methods"]: num_success[method] = 0 # Now loop all notitification methods to send the notifications errors: Dict[str, List[Tuple]] = {} for user_id in recipients: for method in msg["methods"]: try: handler = _notify_methods()[method]["handler"] handler(user_id, msg) num_success[method] = num_success[method] + 1 except MKInternalError as e: errors.setdefault(method, []).append((user_id, e)) message = escape_html_permissive(_("The notification has been sent via")) message += html.render_br() parts = [] for method in msg["methods"]: parts.append( html.render_tr( html.render_td(_notify_methods()[method]["title"]) + html.render_td( _("to %d of %d recipients") % (num_success[method], num_recipients) ) ) ) message += html.render_table(HTML().join(parts)) message += html.render_p(_("Sent notification to: %s") % ", ".join(recipients)) message += html.render_a(_("Back to previous page"), href=makeuri(request, [])) html.show_message(message) if errors: error_message = HTML() for method, method_errors in errors.items(): error_message += _("Failed to send %s notifications to the following users:") % method table_rows = HTML() for user_id, exception in method_errors: table_rows += html.render_tr( html.render_td(html.render_tt(user_id)) + html.render_td(exception) ) error_message += html.render_table(table_rows) + html.render_br() html.show_error(error_message)
def _process_message_message(msg): msg["id"] = utils.gen_id() msg["time"] = time.time() if isinstance(msg["dest"], str): dest_what = msg["dest"] else: dest_what = msg["dest"][0] if dest_what == "all_users": recipients = list(config.multisite_users.keys()) elif dest_what == "online": recipients = userdb.get_online_user_ids() elif dest_what == "list": recipients = msg["dest"][1] else: recipients = [] num_recipients = len(recipients) num_success: Dict[str, int] = {} for method in msg["methods"]: num_success[method] = 0 # Now loop all messaging methods to send the messages errors: Dict[str, List[Tuple]] = {} for user_id in recipients: for method in msg["methods"]: try: handler = _messaging_methods()[method]["handler"] handler(user_id, msg) num_success[method] = num_success[method] + 1 except MKInternalError as e: errors.setdefault(method, []).append((user_id, e)) message = escape_html_permissive( _("The message has successfully been sent...")) message += html.render_br() parts = [] for method in msg["methods"]: parts.append( html.render_li( _messaging_methods()[method]["confirmation_title"] + (_(" for all recipients.") if num_success[method] == num_recipients else _(" for %d of %d recipients.") % (num_success[method], num_recipients)))) message += html.render_ul(HTML().join(parts)) message += html.render_p(_("Recipients: %s") % ", ".join(recipients)) html.show_message(message) if errors: error_message = HTML() for method, method_errors in errors.items(): error_message += _( "Failed to send %s messages to the following users:") % method table_rows = HTML() for user_id, exception in method_errors: table_rows += html.render_tr( html.render_td(html.render_tt(user_id)) + html.render_td(str(exception))) error_message += html.render_table(table_rows) + html.render_br() html.show_error(error_message)