Пример #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"))
Пример #2
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"))
Пример #3
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.from_config(
            self._tag_config_file.load_for_modification())
        changed_tag_group = cmk.utils.tags.TagGroup.from_config(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())
            _changes.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())
        _changes.add_change(
            "edit-hosttags",
            _("Edited host tag group %s (%s)") % (message, self._id))
        if isinstance(message, str):
            flash(message)

        return redirect(mode_url("tags"))
Пример #4
0
    def action(self) -> ActionResult:
        settings = self._vs().from_html_vars("_read_only")
        self._vs().validate_value(settings, "_read_only")
        self._settings = settings

        self._save()
        flash(_("Saved read only settings"))
        return redirect(mode_url("read_only"))
Пример #5
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return redirect(mode_url("folder", folder=watolib.Folder.current().path()))

        count = request.get_integer_input_mandatory("count")
        folders = request.get_integer_input_mandatory("folders")
        levels = request.get_integer_input_mandatory("levels")
        created = self._create_random_hosts(watolib.Folder.current(), count, folders, levels)
        flash(_("Added %d random hosts.") % created)
        return redirect(mode_url("folder", folder=watolib.Folder.current().path()))
Пример #6
0
    def action(self) -> ActionResult:
        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:
            flash(_("No matching host names"))
            return None

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

        message = HTMLWriter.render_b(
            _("Do you really want to rename to following hosts?"
              "This involves a restart of the monitoring core!"))

        rows = []
        for _folder, host_name, target_name in renamings:
            rows.append(
                HTMLWriter.render_tr(
                    HTMLWriter.render_td(host_name) +
                    HTMLWriter.render_td(" → %s" % target_name)))
        message += HTMLWriter.render_table(HTML().join(rows))

        nr_rename = len(renamings)
        c = _confirm(
            _("Confirm renaming of %d %s") %
            (nr_rename, ungettext("host", "hosts", nr_rename)),
            message,
        )
        if c:
            title = _("Renaming of %s") % ", ".join("%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)

            return redirect(host_renaming_job.detail_url())
        if c is False:  # not yet confirmed
            return FinalizeRequest(code=200)
        return None  # browser reload
Пример #7
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return None

        if request.var("_save"):
            try:
                self._validate_diag_html_vars()
            except MKUserError as e:
                user_errors.add(e)
            return None

        if request.var("go_to_properties"):
            # Save the ipaddress and/or community
            vs_host = self._vs_host()
            new = vs_host.from_html_vars("vs_host")
            vs_host.validate_value(new, "vs_host")

            # If both snmp types have credentials set - snmpv3 takes precedence
            return_message = []
            if "ipaddress" in new:
                return_message.append(_("IP address"))
            if "snmp_v3_credentials" in new:
                if "snmp_community" in new:
                    return_message.append(_("SNMPv3 credentials (SNMPv2 community was discarded)"))
                else:
                    return_message.append(_("SNMPv3 credentials"))
                new["snmp_community"] = new["snmp_v3_credentials"]
            elif "snmp_community" in new:
                return_message.append(_("SNMP credentials"))

            # The hostname field used by this dialog is not a host_attribute. Remove it here to
            # prevent data corruption.
            new = new.copy()
            del new["hostname"]

            self._host.update_attributes(new)
            flash(_("Updated attributes: ") + ", ".join(return_message))
            return redirect(
                mode_url(
                    "edit_host",
                    host=self._hostname,
                    folder=Folder.current().path(),
                )
            )
        return None
Пример #8
0
 def _clear_audit_log_after_confirm(self) -> ActionResult:
     self._clear_audit_log()
     flash(_("Cleared audit log."))
     return redirect(self.mode_url())
Пример #9
0
    def _import(self, csv_reader: CSVReader) -> ActionResult:
        if self._has_title_line:
            try:
                next(csv_reader)  # skip header
            except StopIteration:
                pass

        num_succeeded, num_failed = 0, 0
        fail_messages = []
        selected = []
        imported_hosts = []

        for row_num, row in enumerate(csv_reader):
            if not row:
                continue  # skip empty lines

            host_name, attributes = self._get_host_info_from_row(row, row_num)
            try:
                watolib.Folder.current().create_hosts(
                    [(host_name, attributes, None)],
                    bake_hosts=False,
                )
                imported_hosts.append(host_name)
                selected.append("_c_%s" % host_name)
                num_succeeded += 1
            except Exception as e:
                fail_messages.append(
                    _("Failed to create a host from line %d: %s") %
                    (csv_reader.line_num, e))
                num_failed += 1

        watolib.hosts_and_folders.try_bake_agents_for_hosts(imported_hosts)

        self._delete_csv_file()

        msg = _("Imported %d hosts into the current folder.") % num_succeeded
        if num_failed:
            msg += "<br><br>" + (_("%d errors occured:") % num_failed)
            msg += "<ul>"
            for fail_msg in fail_messages:
                msg += "<li>%s</li>" % fail_msg
            msg += "</ul>"

        folder_path = watolib.Folder.current().path()
        if num_succeeded > 0 and request.var("do_service_detection") == "1":
            # Create a new selection for performing the bulk discovery
            user.set_rowselection(
                weblib.selection_id(),
                "wato-folder-/" + folder_path,
                selected,
                "set",
            )
            return redirect(
                mode_url(
                    "bulkinventory",
                    _bulk_inventory="1",
                    show_checkboxes="1",
                    folder=folder_path,
                    selection=weblib.selection_id(),
                ))
        flash(msg)
        return redirect(mode_url("folder", folder=folder_path))