Ejemplo n.º 1
0
    def action(self) -> ActionResult:
        if html.request.var('_delete'):
            delname = html.request.get_ascii_input_mandatory("_delete")
            usages = watolib.find_usages_of_group(delname, self.type_name)

            if usages:
                message = "<b>%s</b><br>%s:<ul>" % \
                            (_("You cannot delete this %s group.") % self.type_name,
                             _("It is still in use by"))
                for title, link in usages:
                    message += '<li><a href="%s">%s</a></li>\n' % (link, title)
                message += "</ul>"
                raise MKUserError(None, message)

            confirm_txt = _('Do you really want to delete the %s group "%s"?'
                            ) % (self.type_name, delname)

            c = wato_confirm(
                _("Confirm deletion of group \"%s\"") % delname, confirm_txt)
            if c:
                watolib.delete_group(delname, self.type_name)
                self._groups = self._load_groups()
            elif c is False:
                return ""

        return None
Ejemplo n.º 2
0
    def _delete_tag_group(self):
        del_id = html.get_item_input(
            "_delete", dict(self._tag_config.get_tag_group_choices()))[1]

        if not html.request.has_var(
                "_repair") and self._is_cleaning_up_user_tag_group_to_builtin(
                    del_id):
            message = _("Transformed the user tag group \"%s\" to builtin."
                        ) % del_id  # type: Union[bool, str]
        else:
            message = _rename_tags_after_confirmation(
                OperationRemoveTagGroup(del_id))
            if message is True:  # no confirmation yet
                c = wato_confirm(
                    _("Confirm deletion of the tag group '%s'") % del_id,
                    _("Do you really want to delete the tag group '%s'?") %
                    del_id)
                if c is False:
                    return ""
                if c is None:
                    return None

        if message:
            self._tag_config.remove_tag_group(del_id)
            try:
                self._tag_config.validate_config()
            except MKGeneralException as e:
                raise MKUserError(None, "%s" % e)
            self._save_tags_and_update_hosts(
                self._tag_config.get_dict_format())
            add_change("edit-tags",
                       _("Removed tag group %s (%s)") % (message, del_id))
            return "tags", message is not True and message or None
Ejemplo n.º 3
0
    def action(self) -> ActionResult:
        if html.request.has_var("_delete"):
            icon_name = html.request.var("_delete")
            if icon_name in self._load_custom_icons():
                c = wato_confirm(
                    _("Confirm Icon deletion"),
                    _("Do you really want to delete the icon <b>%s</b>?") %
                    icon_name)
                if c:
                    os.remove(
                        "%s/local/share/check_mk/web/htdocs/images/icons/%s.png"
                        % (cmk.utils.paths.omd_root, icon_name))
                elif c is False:
                    return ""
                else:
                    return None

        elif html.request.has_var("_do_upload"):
            if not html.check_transaction():
                return None

            vs_upload = self._vs_upload()
            icon_info = vs_upload.from_html_vars('_upload_icon')
            vs_upload.validate_value(icon_info, '_upload_icon')
            self._upload_icon(icon_info)

        return None
Ejemplo n.º 4
0
    def action(self):
        delname = html.request.var("_delete")
        if delname and html.transaction_valid():
            if delname in watolib.timeperiods.builtin_timeperiods():
                raise MKUserError("_delete",
                                  _("Builtin timeperiods can not be modified"))

            usages = self._find_usages_of_timeperiod(delname)
            if usages:
                message = "<b>%s</b><br>%s:<ul>" % \
                            (_("You cannot delete this timeperiod."),
                             _("It is still in use by"))
                for title, link in usages:
                    message += '<li><a href="%s">%s</a></li>\n' % (link, title)
                message += "</ul>"
                raise MKUserError(None, message)

            c = wato_confirm(
                _("Confirm deletion of time period %s") % delname,
                _("Do you really want to delete the time period '%s'? I've checked it: "
                  "it is not being used by any rule or user profile right now."
                  ) % delname)
            if c:
                del self._timeperiods[delname]
                watolib.timeperiods.save_timeperiods(self._timeperiods)
                watolib.add_change("edit-timeperiods",
                                   _("Deleted timeperiod %s") % delname)
            elif c is False:
                return ""
Ejemplo n.º 5
0
    def _delete_aux_tag(self):
        del_id = html.get_item_input("_del_aux",
                                     dict(self._tag_config.aux_tag_list.get_choices()))[1]

        # Make sure that this aux tag is not begin used by any tag group
        for group in self._tag_config.tag_groups:
            for grouped_tag in group.tags:
                if del_id in grouped_tag.aux_tag_ids:
                    raise MKUserError(
                        None,
                        _("You cannot delete this auxiliary tag. "
                          "It is being used in the tag group <b>%s</b>.") % group.title)

        operations = {del_id: False}
        message = _rename_tags_after_confirmation(None, operations)
        if message is True:  # no confirmation yet
            c = wato_confirm(
                _("Confirm deletion of the auxiliary tag '%s'") % del_id,
                _("Do you really want to delete the auxiliary tag '%s'?") % del_id)
            if c is False:
                return ""
            elif c is None:
                return None

        if message:
            self._tag_config.aux_tag_list.remove(del_id)
            self._tag_config.validate_config()
            self._tag_config_file.save(self._tag_config.get_dict_format())
            watolib.Folder.invalidate_caches()
            watolib.Folder.root_folder().rewrite_hosts_files()
            add_change("edit-tags", _("Removed auxiliary tag %s (%s)") % (message, del_id))
            return "tags", message != True and message or None
Ejemplo n.º 6
0
    def action(self) -> ActionResult:
        if html.request.var("_delete"):
            delid = html.request.get_ascii_input_mandatory("_delete")

            if delid not in self._roles:
                raise MKUserError(None, _("This role does not exist."))

            if html.transaction_valid() and self._roles[delid].get('builtin'):
                raise MKUserError(None, _("You cannot delete the builtin roles!"))

            users = userdb.load_users()
            for user in users.values():
                if delid in user["roles"]:
                    raise MKUserError(
                        None, _("You cannot delete roles, that are still in use (%s)!" % delid))

            c = wato_confirm(
                _("Confirm deletion of role %s") % delid,
                _("Do you really want to delete the role %s?") % delid)
            if c:
                self._rename_user_role(delid, None)  # Remove from existing users
                del self._roles[delid]
                self._save_roles()
                watolib.add_change("edit-roles",
                                   _("Deleted role '%s'") % delid,
                                   sites=config.get_login_sites())
            elif c is False:
                return FinalizeRequest(code=200)

        elif html.request.var("_clone"):
            if html.check_transaction():
                cloneid = html.request.get_ascii_input_mandatory("_clone")

                try:
                    cloned_role = self._roles[cloneid]
                except KeyError:
                    raise MKUserError(None, _("This role does not exist."))

                newid = cloneid
                while newid in self._roles:
                    newid += "x"

                new_role = {}
                new_role.update(cloned_role)

                new_alias = new_role["alias"]
                while not watolib.is_alias_used("roles", newid, new_alias)[0]:
                    new_alias += _(" (copy)")
                new_role["alias"] = new_alias

                if cloned_role.get("builtin"):
                    new_role["builtin"] = False
                    new_role["basedon"] = cloneid

                self._roles[newid] = new_role
                self._save_roles()
                watolib.add_change("edit-roles",
                                   _("Created new role '%s'") % newid,
                                   sites=config.get_login_sites())
        return None
Ejemplo n.º 7
0
    def action(self):
        renaming_config = self._vs_renaming_config().from_html_vars("")
        self._vs_renaming_config().validate_value(renaming_config, "")
        renamings = self._collect_host_renamings(renaming_config)

        if not renamings:
            return None, _("No matching host names")

        warning = self._renaming_collision_error(renamings)
        if warning:
            return None, warning

        message = _(
            "<b>Do you really want to rename to following hosts? This involves a restart of the monitoring core!</b>"
        )
        message += "<table>"
        for _folder, host_name, target_name in renamings:
            message += u"<tr><td>%s</td><td> → %s</td></tr>" % (host_name, target_name)
        message += "</table>"

        c = wato_confirm(_("Confirm renaming of %d hosts") % len(renamings), HTML(message))
        if c:
            title = _("Renaming of %s") % ", ".join(u"%s → %s" % x[1:] for x in renamings)
            host_renaming_job = RenameHostsBackgroundJob(title=title)
            host_renaming_job.set_function(rename_hosts_background_job, renamings)

            try:
                host_renaming_job.start()
            except background_job.BackgroundJobAlreadyRunning as e:
                raise MKGeneralException(_("Another host renaming job is already running: %s") % e)

            raise HTTPRedirect(host_renaming_job.detail_url())
        if c is False:  # not yet confirmed
            return ""
        return None  # browser reload
Ejemplo n.º 8
0
    def _delete_tag_group(self):
        del_id = html.get_item_input("_delete", dict(self._tag_config.get_tag_group_choices()))[1]

        tag_group = self._tag_config.get_tag_group(del_id)
        if tag_group:
            operations = list(tag_group.get_tag_ids())
        else:
            operations = None

        message = _rename_tags_after_confirmation(del_id, operations)
        if message is True:  # no confirmation yet
            c = wato_confirm(
                _("Confirm deletion of the tag group '%s'") % del_id,
                _("Do you really want to delete the tag group '%s'?") % del_id)
            if c is False:
                return ""
            elif c is None:
                return None

        if message:
            self._tag_config.remove_tag_group(del_id)
            self._tag_config.validate_config()
            self._tag_config_file.save(self._tag_config.get_dict_format())
            watolib.Folder.invalidate_caches()
            watolib.Folder.root_folder().rewrite_hosts_files()
            add_change("edit-tags", _("Removed tag group %s (%s)") % (message, del_id))
            return "tags", message != True and message or None
Ejemplo n.º 9
0
    def _delete_aux_tag(self):
        del_id = html.get_item_input("_del_aux",
                                     dict(self._tag_config.aux_tag_list.get_choices()))[1]

        # Make sure that this aux tag is not begin used by any tag group
        for group in self._tag_config.tag_groups:
            for grouped_tag in group.tags:
                if del_id in grouped_tag.aux_tag_ids:
                    raise MKUserError(
                        None,
                        _("You cannot delete this auxiliary tag. "
                          "It is being used in the tag group <b>%s</b>.") % group.title)

        message = _rename_tags_after_confirmation(OperationRemoveAuxTag(del_id))
        if message is True:  # no confirmation yet
            c = wato_confirm(
                _("Confirm deletion of the auxiliary tag '%s'") % del_id,
                _("Do you really want to delete the auxiliary tag '%s'?") % del_id)
            if c is False:
                return ""
            elif c is None:
                return None

        if message:
            self._tag_config.aux_tag_list.remove(del_id)
            try:
                self._tag_config.validate_config()
            except MKGeneralException as e:
                raise MKUserError(None, "%s" % e)
            self._save_tags_and_update_hosts(self._tag_config.get_dict_format())
            add_change("edit-tags", _("Removed auxiliary tag %s (%s)") % (message, del_id))
            return "tags", message if message is not True else None
Ejemplo n.º 10
0
    def _delete_tag_group(self):
        del_id = html.get_item_input(
            "_delete", dict(self._tag_config.get_tag_group_choices()))[1]

        message = _rename_tags_after_confirmation(
            OperationRemoveTagGroup(del_id))
        if message is True:  # no confirmation yet
            c = wato_confirm(
                _("Confirm deletion of the tag group '%s'") % del_id,
                _("Do you really want to delete the tag group '%s'?") % del_id)
            if c is False:
                return ""
            elif c is None:
                return None

        if message:
            self._tag_config.remove_tag_group(del_id)
            try:
                self._tag_config.validate_config()
            except MKGeneralException as e:
                raise MKUserError(None, "%s" % e)
            self._save_tags_and_update_hosts(
                self._tag_config.get_dict_format())
            add_change("edit-tags",
                       _("Removed tag group %s (%s)") % (message, del_id))
            return "tags", message != True and message or None
Ejemplo n.º 11
0
    def action(self):
        connections = load_connection_config(lock=True)
        if html.request.has_var("_delete"):
            index = html.request.get_integer_input_mandatory("_delete")
            connection = connections[index]
            c = wato_confirm(
                _("Confirm deletion of LDAP connection"),
                _("Do you really want to delete the LDAP connection <b>%s</b>?"
                  ) % (connection["id"]))
            if c:
                self._add_change(
                    "delete-ldap-connection",
                    _("Deleted LDAP connection %s") % (connection["id"]))
                del connections[index]
                save_connection_config(connections)
            elif c is False:
                return ""
            else:
                return

        elif html.request.has_var("_move"):
            if not html.check_transaction():
                return

            from_pos = html.request.get_integer_input_mandatory("_move")
            to_pos = html.request.get_integer_input_mandatory("_index")
            connection = connections[from_pos]
            self._add_change(
                "move-ldap-connection",
                _("Changed position of LDAP connection %s to %d") %
                (connection["id"], to_pos))
            del connections[from_pos]  # make to_pos now match!
            connections[to_pos:to_pos] = [connection]
            save_connection_config(connections)
Ejemplo n.º 12
0
    def action(self):
        if watolib.get_pending_changes_info():
            raise MKUserError(
                "newname",
                _("You cannot rename a host while you have pending changes."))

        newname = html.request.var("newname")
        self._check_new_host_name("newname", newname)
        c = wato_confirm(
            _("Confirm renaming of host"),
            _("Are you sure you want to rename the host <b>%s</b> into <b>%s</b>? "
              "This involves a restart of the monitoring core!") %
            (self._host.name(), newname))
        if c:
            # Creating pending entry. That makes the site dirty and that will force a sync of
            # the config to that site before the automation is being done.
            host_renaming_job = RenameHostBackgroundJob(
                self._host,
                title=_("Renaming of %s -> %s") % (self._host.name(), newname))
            renamings = [(watolib.Folder.current(), self._host.name(), newname)
                         ]
            host_renaming_job.set_function(rename_hosts_background_job,
                                           renamings)

            try:
                host_renaming_job.start()
            except background_job.BackgroundJobAlreadyRunning as e:
                raise MKGeneralException(
                    _("Another host renaming job is already running: %s") % e)

            raise HTTPRedirect(host_renaming_job.detail_url())

        if c is False:  # not yet confirmed
            return ""
Ejemplo n.º 13
0
 def _clear_audit_log_after_confirm(self):
     c = wato_confirm(_("Confirm deletion of audit log"),
                      _("Do you really want to clear the audit log?"))
     if c:
         self._clear_audit_log()
         return None, _("Cleared audit log.")
     if c is False:  # not yet confirmed
         return ""
     return None  # browser reload
Ejemplo n.º 14
0
 def _clear_audit_log_after_confirm(self) -> ActionResult:
     c = wato_confirm(_("Confirm deletion of audit log"),
                      _("Do you really want to clear the audit log?"))
     if c:
         self._clear_audit_log()
         flash(_("Cleared audit log."))
         return None
     if c is False:  # not yet confirmed
         return FinalizeRequest(code=200)
     return None  # browser reload
Ejemplo n.º 15
0
    def action(self):
        if html.request.var('_delete'):
            delid = html.request.get_unicode_input("_delete")
            c = wato_confirm(
                _("Confirm deletion of user %s") % delid,
                _("Do you really want to delete the user %s?") % delid)
            if c:
                delete_users([delid])
            elif c is False:
                return ""

        elif html.request.var('_sync') and html.check_transaction():
            try:

                job = userdb.UserSyncBackgroundJob()
                job.set_function(job.do_sync,
                                 add_to_changelog=True,
                                 enforce_sync=True,
                                 load_users_func=userdb.load_users,
                                 save_users_func=userdb.save_users)

                try:
                    job.start()
                except background_job.BackgroundJobAlreadyRunning as e:
                    raise MKUserError(
                        None,
                        _("Another synchronization job is already running: %s")
                        % e)

                self._job_snapshot = job.get_status_snapshot()
            except Exception:
                logger.exception("error syncing users")
                raise MKUserError(
                    None,
                    traceback.format_exc().replace('\n', '<br>\n'))

        elif html.request.var("_bulk_delete_users"):
            return self._bulk_delete_users_after_confirm()

        elif html.check_transaction():
            action_handler = gui_background_job.ActionHandler(
                self.breadcrumb())
            action_handler.handle_actions()
            if action_handler.did_acknowledge_job():
                self._job_snapshot = userdb.UserSyncBackgroundJob(
                ).get_status_snapshot()
                return None, _("Synchronization job acknowledged")
Ejemplo n.º 16
0
    def _bulk_delete_users_after_confirm(self):
        selected_users = []
        users = userdb.load_users()
        for varname, _value in html.request.itervars(prefix="_c_user_"):
            if html.get_checkbox(varname):
                user = base64.b64decode(varname.split("_c_user_")[-1]).decode("utf-8")
                if user in users:
                    selected_users.append(user)

        if selected_users:
            c = wato_confirm(
                _("Confirm deletion of %d users") % len(selected_users),
                _("Do you really want to delete %d users?") % len(selected_users))
            if c:
                delete_users(selected_users)
            elif c is False:
                return ""
Ejemplo n.º 17
0
    def action(self):
        if html.request.var('_delete'):
            delname = html.request.var("_delete")

            # FIXME: Raise an error if the attribute is still used

            confirm_txt = _('Do you really want to delete the custom attribute "%s"?') % (delname)

            c = wato_confirm(_("Confirm deletion of attribute \"%s\"") % delname, confirm_txt)
            if c:
                for index, attr in enumerate(self._attrs):
                    if attr['name'] == delname:
                        self._attrs.pop(index)
                save_custom_attrs_to_mk_file(self._all_attrs)
                self._update_config()
                add_change("edit-%sattrs" % self._type, _("Deleted attribute %s") % (delname))
            elif c is False:
                return ""