示例#1
0
文件: tags.py 项目: petrows/checkmk
    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"))
示例#2
0
文件: tags.py 项目: petrows/checkmk
    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"))
示例#3
0
文件: tags.py 项目: bbaumer/checkmk
    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"))
示例#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 _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>"

        if num_succeeded > 0 and html.request.var(
                "do_service_detection") == "1":
            # Create a new selection for performing the bulk discovery
            config.user.set_rowselection(
                weblib.selection_id(),
                'wato-folder-/' + watolib.Folder.current().path(), selected,
                'set')
            return redirect(
                mode_url("bulkinventory",
                         _bulk_inventory='1',
                         show_checkboxes='1'))
        flash(msg)
        return redirect(mode_url("folder"))
示例#6
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
示例#7
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return redirect(mode_url("folder", folder=watolib.Folder.current().path()))

        count = html.request.get_integer_input_mandatory("count")
        folders = html.request.get_integer_input_mandatory("folders")
        levels = html.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()))
示例#8
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 = html.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(
                html.render_tr(
                    html.render_td(host_name) +
                    html.render_td(" → %s" % target_name)))
        message += html.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
示例#9
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 = _(
            "<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)

            return redirect(host_renaming_job.detail_url())
        if c is False:  # not yet confirmed
            return FinalizeRequest(code=200)
        return None  # browser reload
示例#10
0
    def action(self) -> ActionResult:
        if not transactions.check_transaction():
            return None

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

        if request.var('_save'):
            # 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"))

            self._host.update_attributes(new)
            flash(_("Updated attributes: ") + ", ".join(return_message))
            return redirect(
                mode_url(
                    "edit_host",
                    host=self._hostname,
                    folder=watolib.Folder.current().path(),
                ))
        return None
示例#11
0
文件: users.py 项目: arusa/checkmk
    def action(self) -> ActionResult:
        if not html.check_transaction():
            return redirect(self.mode_url())

        if html.request.var('_delete'):
            delete_users([html.request.get_unicode_input("_delete")])

        elif html.request.var('_sync'):
            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"):
            self._bulk_delete_users_after_confirm()

        else:
            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()
                flash(_("Synchronization job acknowledged"))
        return redirect(self.mode_url())
示例#12
0
 def _clear_audit_log_after_confirm(self) -> ActionResult:
     self._clear_audit_log()
     flash(_("Cleared audit log."))
     return redirect(self.mode_url())