Exemple #1
0
    def _delete_aux_tag(self) -> ActionResult:
        del_id = request.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(self.breadcrumb(), OperationRemoveAuxTag(del_id))
        if message is False:
            return FinalizeRequest(code=200)

        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))
            if isinstance(message, str):
                flash(message)
        return redirect(mode_url("tags"))
Exemple #2
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
Exemple #3
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
Exemple #4
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
Exemple #5
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
Exemple #6
0
    def _delete_tag_group(self) -> ActionResult:
        del_id = request.get_item_input("_delete",
                                        dict(self._tag_config.get_tag_group_choices()))[1]

        if not request.has_var("_repair") and self._is_cleaning_up_user_tag_group_to_builtin(
                del_id):
            message: Union[bool,
                           str] = _("Transformed the user tag group \"%s\" to builtin.") % del_id
        else:
            message = _rename_tags_after_confirmation(self.breadcrumb(),
                                                      OperationRemoveTagGroup(del_id))
            if message is False:
                return FinalizeRequest(code=200)

        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))
            if isinstance(message, str):
                flash(message)
        return redirect(mode_url("tags"))
Exemple #7
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
Exemple #8
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return redirect(mode_url("tags"))

        vs = self._valuespec()
        tag_group_spec = vs.from_html_vars("tag_group")
        vs.validate_value(tag_group_spec, "tag_group")

        # Create new object with existing host tags
        changed_hosttags_config = cmk.utils.tags.TagConfig()
        changed_hosttags_config.parse_config(
            self._tag_config_file.load_for_modification())
        changed_tag_group = cmk.utils.tags.TagGroup(tag_group_spec)
        self._tag_group = changed_tag_group

        if self._new:
            # Inserts and verifies changed tag group
            changed_hosttags_config.insert_tag_group(changed_tag_group)
            try:
                changed_hosttags_config.validate_config()
            except MKGeneralException as e:
                raise MKUserError(None, "%s" % e)
            self._save_tags_and_update_hosts(
                changed_hosttags_config.get_dict_format())
            add_change(
                "edit-hosttags",
                _("Created new host tag group '%s'") % changed_tag_group.id)
            flash(
                _("Created new host tag group '%s'") % changed_tag_group.title)
            return redirect(mode_url("tags"))

        # Updates and verifies changed tag group
        changed_hosttags_config.update_tag_group(changed_tag_group)
        try:
            changed_hosttags_config.validate_config()
        except MKGeneralException as e:
            raise MKUserError(None, "%s" % e)

        remove_tag_ids, replace_tag_ids = identify_modified_tags(
            changed_tag_group, self._untainted_tag_group)
        tg_id = self._tag_group.id
        if tg_id is None:
            raise Exception("tag group ID not set")
        operation = OperationReplaceGroupedTags(tg_id, remove_tag_ids,
                                                replace_tag_ids)

        # Now check, if any folders, hosts or rules are affected
        message = _rename_tags_after_confirmation(self.breadcrumb(), operation)
        if message is False:
            return FinalizeRequest(code=200)

        self._save_tags_and_update_hosts(
            changed_hosttags_config.get_dict_format())
        add_change("edit-hosttags",
                   _("Edited host tag group %s (%s)") % (message, self._id))
        if isinstance(message, str):
            flash(message)

        return redirect(mode_url("tags"))
Exemple #9
0
def rename_hosts_in_check_mk(renamings):
    action_counts = {}
    for site_id, name_pairs in group_renamings_by_site(renamings).items():
        message = _("Renamed host %s") % ", ".join(
            [_("%s into %s") % (oldname, newname) for (oldname, newname) in name_pairs])

        # Restart is done by remote automation (below), so don't do it during rename/sync
        # The sync is automatically done by the remote automation call
        add_change("renamed-hosts", message, sites=[site_id], need_restart=False)

        new_counts = watolib.check_mk_automation(site_id, "rename-hosts", [], name_pairs)

        merge_action_counts(action_counts, new_counts)
    return action_counts
Exemple #10
0
    def action(self) -> ActionResult:
        if not html.check_transaction():
            return redirect(self.mode_url())

        if not html.request.var('_delete'):
            return redirect(self.mode_url())

        delname = html.request.var("_delete")
        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))
        return redirect(self.mode_url())
Exemple #11
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 ""
Exemple #12
0
    def rename_host_in_folder_rules(folder):
        rulesets = watolib.FolderRulesets(folder)
        rulesets.load()

        changed = False
        for varname, ruleset in rulesets.get_rulesets().items():
            for _rule_folder, _rulenr, rule in ruleset.get_rules():
                if rule.replace_explicit_host_condition(oldname, newname):
                    changed_rulesets.append(varname)
                    changed = True

        if changed:
            add_change("edit-ruleset",
                       _("Renamed host in %d rulesets of folder %s") %
                       (len(changed_rulesets), folder.title),
                       obj=folder,
                       sites=folder.all_site_ids())
            rulesets.save()

        for subfolder in folder.subfolders():
            rename_host_in_folder_rules(subfolder)
Exemple #13
0
    def rename_host_in_folder_rules(folder):
        rulesets = watolib.FolderRulesets(folder)
        rulesets.load()

        changed = False
        for varname, ruleset in rulesets.get_rulesets().items():
            for _rule_folder, _rulenr, rule in ruleset.get_rules():
                # TODO: Move to rule?
                if watolib.rename_host_in_list(rule.host_list, oldname,
                                               newname):
                    changed_rulesets.append(varname)
                    changed = True

        if changed:
            add_change("edit-ruleset",
                       _("Renamed host in %d rulesets of folder %s") %
                       (len(changed_rulesets), folder.title),
                       obj=folder,
                       sites=folder.all_site_ids())
            rulesets.save()

        for subfolder in folder.all_subfolders().values():
            rename_host_in_folder_rules(subfolder)
Exemple #14
0
 def _add_change(self, action_name, text):
     add_change(action_name,
                text,
                domains=[watolib.ConfigDomainGUI],
                sites=config.get_login_sites())
    def action(self) -> ActionResult:
        # TODO: remove subclass specific things specifict things (everything with _type == 'user')
        if not html.check_transaction():
            return None

        title = html.request.get_unicode_input_mandatory("title").strip()
        if not title:
            raise MKUserError("title", _("Please specify a title."))

        for this_attr in self._attrs:
            if title == this_attr['title'] and self._name != this_attr['name']:
                raise MKUserError(
                    "alias",
                    _("This alias is already used by the attribute %s.") %
                    this_attr['name'])

        topic = html.request.get_unicode_input_mandatory('topic', '').strip()
        help_txt = html.request.get_unicode_input_mandatory('help', '').strip()
        show_in_table = html.get_checkbox('show_in_table')
        add_custom_macro = html.get_checkbox('add_custom_macro')

        if self._new:
            self._name = html.request.get_ascii_input_mandatory("name",
                                                                '').strip()
            if not self._name:
                raise MKUserError(
                    "name", _("Please specify a name for the new attribute."))
            if ' ' in self._name:
                raise MKUserError(
                    "name",
                    _("Sorry, spaces are not allowed in attribute names."))
            if not re.match("^[-a-z0-9A-Z_]*$", self._name):
                raise MKUserError(
                    "name",
                    _("Invalid attribute name. Only the characters a-z, A-Z, 0-9, _ and - are allowed."
                      ))
            if [a for a in self._attrs if a['name'] == self._name]:
                raise MKUserError(
                    "name",
                    _("Sorry, there is already an attribute with that name."))

            ty = html.request.get_ascii_input_mandatory('type', '').strip()
            if ty not in [t[0] for t in custom_attr_types()]:
                raise MKUserError('type',
                                  _('The choosen attribute type is invalid.'))

            self._attr = {
                'name': self._name,
                'type': ty,
            }
            self._attrs.append(self._attr)

            add_change(
                "edit-%sattr" % self._type,
                _("Create new %s attribute %s") % (self._type, self._name))
        else:
            add_change(
                "edit-%sattr" % self._type,
                _("Modified %s attribute %s") % (self._type, self._name))
        self._attr.update({
            'title': title,
            'topic': topic,
            'help': help_txt,
            'show_in_table': show_in_table,
            'add_custom_macro': add_custom_macro,
        })

        self._add_extra_attrs_from_html_vars()

        save_custom_attrs_to_mk_file(self._all_attrs)
        self._update_config()

        return redirect(mode_url(self._type + "_attrs"))
Exemple #16
0
    def action(self):
        if not html.check_transaction():
            return "tags"

        vs = self._valuespec()
        tag_group_spec = vs.from_html_vars("tag_group")
        vs.validate_value(tag_group_spec, "tag_group")

        # Create new object with existing host tags
        changed_hosttags_config = cmk.utils.tags.TagConfig()
        changed_hosttags_config.parse_config(
            self._tag_config_file.load_for_modification())

        changed_tag_group = cmk.utils.tags.TagGroup(tag_group_spec)
        self._tag_group = changed_tag_group

        if self._new:
            # Inserts and verifies changed tag group
            changed_hosttags_config.insert_tag_group(changed_tag_group)
            try:
                changed_hosttags_config.validate_config()
            except MKGeneralException as e:
                raise MKUserError(None, "%s" % e)
            self._save_tags_and_update_hosts(
                changed_hosttags_config.get_dict_format())
            add_change(
                "edit-hosttags",
                _("Created new host tag group '%s'") % changed_tag_group.id)
            return "tags", _(
                "Created new host tag group '%s'") % changed_tag_group.title

        # Updates and verifies changed tag group
        changed_hosttags_config.update_tag_group(changed_tag_group)
        try:
            changed_hosttags_config.validate_config()
        except MKGeneralException as e:
            raise MKUserError(None, "%s" % e)

        remove_tag_ids, replace_tag_ids = [], {}
        new_by_title = {tag.title: tag.id for tag in changed_tag_group.tags}

        for former_tag in self._untainted_tag_group.tags:
            # Detect renaming
            if former_tag.title in new_by_title:
                new_id = new_by_title[former_tag.title]
                if new_id != former_tag.id:
                    # new_id may be None
                    replace_tag_ids[former_tag.id] = new_id
                    continue

            # Detect removal
            if former_tag.id is not None \
                    and former_tag.id not in [ tmp_tag.id for tmp_tag in changed_tag_group.tags ]:
                # remove explicit tag (hosts/folders) or remove it from tag specs (rules)
                remove_tag_ids.append(former_tag.id)

        tg_id = self._tag_group.id
        if tg_id is None:
            raise Exception("tag group ID not set")
        operation = OperationReplaceGroupedTags(tg_id, remove_tag_ids,
                                                replace_tag_ids)

        # Now check, if any folders, hosts or rules are affected
        message = _rename_tags_after_confirmation(operation)
        if message:
            self._save_tags_and_update_hosts(
                changed_hosttags_config.get_dict_format())
            add_change(
                "edit-hosttags",
                _("Edited host tag group %s (%s)") % (message, self._id))
            return "tags", message is not True and message or None

        return "tags"
Exemple #17
0
    def action(self):
        if not html.check_transaction():
            return "tags"

        vs = self._valuespec()
        tag_group_spec = vs.from_html_vars("tag_group")
        vs.validate_value(tag_group_spec, "tag_group")

        # Create new object with existing host tags
        changed_hosttags_config = cmk.utils.tags.TagConfig()
        changed_hosttags_config.parse_config(
            self._tag_config_file.load_for_modification())

        changed_tag_group = cmk.utils.tags.TagGroup(tag_group_spec)
        self._tag_group = changed_tag_group

        if self._new:
            # Inserts and verifies changed tag group
            changed_hosttags_config.insert_tag_group(changed_tag_group)
            changed_hosttags_config.validate_config()
            self._tag_config_file.save(
                changed_hosttags_config.get_dict_format())

            # Make sure, that all tags are active (also manual ones from main.mk)
            config.load_config()
            add_change(
                "edit-hosttags",
                _("Created new host tag group '%s'") % changed_tag_group.id)
            return "tags", _(
                "Created new host tag group '%s'") % changed_tag_group.title

        # Updates and verifies changed tag group
        changed_hosttags_config.update_tag_group(changed_tag_group)
        changed_hosttags_config.validate_config()

        remove_tag_ids, replace_tag_ids = [], {}
        new_by_title = dict([(tag.title, tag.id)
                             for tag in changed_tag_group.tags])

        for former_tag in self._untainted_tag_group.tags:
            # Detect renaming
            if former_tag.title in new_by_title:
                new_id = new_by_title[former_tag.title]
                if new_id != former_tag.id:
                    # new_id may be None
                    replace_tag_ids[former_tag.id] = new_id
                    continue

            # Detect removal
            if former_tag.id is not None \
                    and former_tag.id not in [ tmp_tag.id for tmp_tag in changed_tag_group.tags ]:
                # remove explicit tag (hosts/folders) or remove it from tag specs (rules)
                remove_tag_ids.append(former_tag.id)

        operation = OperationReplaceGroupedTags(self._tag_group.id,
                                                remove_tag_ids,
                                                replace_tag_ids)

        # Now check, if any folders, hosts or rules are affected
        message = _rename_tags_after_confirmation(operation)
        if message:
            self._tag_config_file.save(
                changed_hosttags_config.get_dict_format())
            config.load_config()
            add_change(
                "edit-hosttags",
                _("Edited host tag group %s (%s)") % (message, self._id))
            return "tags", message != True and message or None

        return "tags"
Exemple #18
0
    def action(self):
        if not html.check_transaction():
            return "tags"

        vs = self._valuespec()
        tag_group_spec = vs.from_html_vars("tag_group")
        vs.validate_value(tag_group_spec, "tag_group")

        # Create new object with existing host tags
        changed_hosttags_config = cmk.gui.tags.TagConfig()
        changed_hosttags_config.parse_config(self._tag_config_file.load_for_modification())

        changed_tag_group = cmk.gui.tags.TagGroup(tag_group_spec)
        self._tag_group = changed_tag_group

        if self._new:
            # Inserts and verifies changed tag group
            changed_hosttags_config.insert_tag_group(changed_tag_group)
            changed_hosttags_config.validate_config()
            self._tag_config_file.save(changed_hosttags_config.get_dict_format())

            # Make sure, that all tags are active (also manual ones from main.mk)
            config.load_config()
            add_change("edit-hosttags", _("Created new host tag group '%s'") % changed_tag_group.id)
            return "tags", _("Created new host tag group '%s'") % changed_tag_group.title

        # Updates and verifies changed tag group
        changed_hosttags_config.update_tag_group(changed_tag_group)
        changed_hosttags_config.validate_config()

        # This is the major effort of WATO when it comes to
        # host tags: renaming and deleting of tags that might be
        # in use by folders, hosts and rules. First we create a
        # kind of "patch" from the old to the new tags. The renaming
        # of a tag is detected by comparing the titles. Addition
        # of new tags is not a problem and need not be handled.
        # Result of this is the dict 'operations': it's keys are
        # current tag names, its values the corresponding new names
        # or False in case of tag removals.
        operations = {}

        # Detect renaming
        new_by_title = dict([(tag.title, tag.id) for tag in changed_tag_group.tags])

        for former_tag in self._untainted_tag_group.tags:
            if former_tag.title in new_by_title:
                new_id = new_by_title[former_tag.title]
                if new_id != former_tag.id:
                    operations[former_tag.id] = new_id  # might be None

        # Detect removal
        for former_tag in self._untainted_tag_group.tags:
            if former_tag.id is not None \
                and former_tag.id not in [ tmp_tag.id for tmp_tag in changed_tag_group.tags ] \
                and former_tag.id not in operations:
                # remove explicit tag (hosts/folders) or remove it from tag specs (rules)
                operations[former_tag.id] = False

        # Now check, if any folders, hosts or rules are affected
        message = _rename_tags_after_confirmation(changed_tag_group.id, operations)
        if message:
            self._tag_config_file.save(changed_hosttags_config.get_dict_format())
            config.load_config()
            add_change("edit-hosttags", _("Edited host tag group %s (%s)") % (message, self._id))
            return "tags", message != True and message or None

        return "tags"