Esempio n. 1
0
    def _display_page_controls(self, start_time, end_time, previous_log_time, next_log_time):
        html.open_div(class_="paged_controls")

        def time_url_args(t):
            return [
                ("options_start_1_day", time.strftime("%d", time.localtime(t))),
                ("options_start_1_month", time.strftime("%m", time.localtime(t))),
                ("options_start_1_year", time.strftime("%Y", time.localtime(t))),
                ("options_start_sel", "1"),
            ]

        if next_log_time is not None:
            html.icon_button(makeactionuri(request, transactions, [
                ("options_start_sel", "0"),
            ]), _("Most recent events"), "start")

            html.icon_button(makeactionuri(request, transactions, time_url_args(next_log_time)),
                             "%s: %s" % (_("Newer events"), render.date(next_log_time)), "back")
        else:
            html.empty_icon_button()
            html.empty_icon_button()

        if previous_log_time is not None:
            html.icon_button(makeactionuri(request, transactions, time_url_args(previous_log_time)),
                             "%s: %s" % (_("Older events"), render.date(previous_log_time)),
                             "forth")
        else:
            html.empty_icon_button()

        html.close_div()
Esempio n. 2
0
    def page(self) -> None:
        with table_element(title=self._table_title(), searchable=False, sortable=False) as table:

            for key_id, key in sorted(self.key_store.load().items()):
                cert = crypto.load_certificate(crypto.FILETYPE_PEM, key.certificate.encode("ascii"))

                table.row()
                table.cell(_("Actions"), css=["buttons"])
                if self._may_edit_config():
                    message = self._delete_confirm_msg()
                    if key.owner != user.id:
                        message += (
                            _("<br><b>Note</b>: this key has created by user <b>%s</b>") % key.owner
                        )

                    delete_url = make_confirm_link(
                        url=makeactionuri(request, transactions, [("_delete", key_id)]),
                        message=message,
                    )
                    html.icon_button(delete_url, _("Delete this key"), "delete")
                download_url = makeuri_contextless(
                    request,
                    [("mode", self.download_mode), ("key", key_id)],
                )
                html.icon_button(download_url, _("Download this key"), "download")
                table.cell(_("Description"), key.alias)
                table.cell(_("Created"), cmk.utils.render.date(key.date))
                table.cell(_("By"), key.owner)
                table.cell(_("Digest (MD5)"), cert.digest("md5").decode("ascii"))
Esempio n. 3
0
def _extend_display_dropdown(menu: PageMenu) -> None:
    display_dropdown = menu.get_dropdown_by_name(
        "display", make_display_options_dropdown())
    context_hidden = request.var("_hidecontext", "no") == "yes"
    display_dropdown.topics.insert(
        0,
        PageMenuTopic(
            title=_("Context"),
            entries=[
                PageMenuEntry(
                    title=_("Show context"),
                    icon_name="checkbox"
                    if context_hidden else "checked_checkbox",
                    item=make_simple_link(
                        makeactionuri(
                            request,
                            transactions,
                            [
                                ("_show_backlog", "no") if context_hidden else
                                ("_hidecontext", "yes"),
                            ],
                        )),
                ),
            ],
        ),
    )
Esempio n. 4
0
    def _show_move_to_folder_action(self, obj):
        if isinstance(obj, watolib.Host):
            what = "host"
            what_title = _("host")
            ident = obj.name()
            style = None
        else:
            what = "folder"
            what_title = _("folder")
            ident = obj.path()
            style = "display:none"

        html.popup_trigger(
            html.render_icon("move",
                             title=_("Move this %s to another folder") % what_title,
                             cssclass="iconbutton"),
            ident="move_" + obj.name(),
            method=MethodAjax(endpoint="move_to_folder",
                              url_vars=[
                                  ("what", what),
                                  ("ident", ident),
                                  ("back_url", makeactionuri(global_request, transactions, [])),
                              ]),
            style=style,
        )
Esempio n. 5
0
def _page_menu_entry_acknowledge(
    site: Optional[SiteId] = None,
    host_name: Optional[HostName] = None,
    int_filename: Optional[str] = None,
) -> Iterator[PageMenuEntry]:
    if not user.may("general.act") or (host_name
                                       and not may_see(site, host_name)):
        return

    if int_filename:
        label = _("Clear log")
    else:
        label = _("Clear logs")

    urivars: HTTPVariables = [("_ack", "1")]
    if int_filename:
        urivars.append(("file", form_file_to_ext(int_filename)))

    ack_msg = _get_ack_msg(
        host_name,
        form_file_to_ext(int_filename) if int_filename else None)

    yield PageMenuEntry(
        title=label,
        icon_name="delete",
        item=make_simple_link(
            make_confirm_link(
                url=makeactionuri(request, transactions, urivars),
                message=_("Do you really want to acknowledge %s "
                          "by <b>deleting</b> all stored messages?") % ack_msg,
            )),
        is_shortcut=True,
        is_suggested=True,
    )
Esempio n. 6
0
    def delete_site(cls, site_id):
        # TODO: Clean this up
        from cmk.gui.watolib.hosts_and_folders import Folder
        all_sites = cls.load_sites()
        if site_id not in all_sites:
            raise MKUserError(
                None,
                _("Unable to delete unknown site id: %s") % site_id)

        # Make sure that site is not being used by hosts and folders
        if site_id in Folder.root_folder().all_site_ids():
            search_url = makeactionuri(request, transactions, [
                ("host_search_change_site", "on"),
                ("host_search_site", site_id),
                ("host_search", "1"),
                ("folder", ""),
                ("mode", "search"),
                ("filled_in", "edit_host"),
            ])
            raise MKUserError(
                None,
                _("You cannot delete this connection. It has folders/hosts "
                  "assigned to it. You can use the <a href=\"%s\">host "
                  "search</a> to get a list of the hosts.") % search_url)

        domains = cls._affected_config_domains()

        del all_sites[site_id]
        cls.save_sites(all_sites)
        cmk.gui.watolib.activate_changes.clear_site_replication_status(site_id)
        cmk.gui.watolib.changes.add_change("edit-sites",
                                           _("Deleted site %s") % site_id,
                                           domains=domains,
                                           sites=[omd_site()])
Esempio n. 7
0
    def _extend_display_dropdown(self, menu: PageMenu) -> None:
        display_dropdown = menu.get_dropdown_by_name("display", make_display_options_dropdown())

        display_dropdown.topics.insert(
            0,
            PageMenuTopic(
                title=_("Filter"),
                entries=[
                    PageMenuEntry(
                        title=_("Filter view"),
                        icon_name="filters_set" if html.form_submitted("options") else "filter",
                        item=PageMenuSidePopup(self._render_filter_form()),
                        name="filters",
                        is_shortcut=True,
                    ),
                ],
            ))

        display_dropdown.topics.insert(
            0,
            PageMenuTopic(
                title=_("Details"),
                entries=[
                    PageMenuEntry(
                        title=_("Show details"),
                        icon_name="checked_checkbox" if self._show_details else "checkbox",
                        item=make_simple_link(
                            makeactionuri(request, transactions, [
                                ("show_details", "0" if self._show_details else "1"),
                            ])),
                        name="show_details",
                        css_classes=["toggle"],
                    )
                ],
            ))
Esempio n. 8
0
    def page(self):
        if not self._attrs:
            html.div(_("No custom attributes are defined yet."), class_="info")
            return

        with table_element(self._type + "attrs") as table:
            for custom_attr in sorted(self._attrs, key=lambda x: x["title"]):
                table.row()

                table.cell(_("Actions"), css="buttons")
                edit_url = watolib.folder_preserving_link([
                    ("mode", "edit_%s_attr" % self._type),
                    ("edit", custom_attr["name"])
                ])
                delete_url = make_confirm_link(
                    url=makeactionuri(request, transactions,
                                      [("_delete", custom_attr["name"])]),
                    message=
                    _('Do you really want to delete the custom attribute "%s"?'
                      ) % custom_attr["name"],
                )
                html.icon_button(edit_url, _("Properties"), "edit")
                html.icon_button(delete_url, _("Delete"), "delete")

                table.cell(_("Name"), custom_attr["name"])
                table.cell(_("Title"), custom_attr["title"])
                table.cell(_("Type"),
                           dict(custom_attr_types())[custom_attr["type"]])
Esempio n. 9
0
    def _show_credentials(
            cls, webauthn_credentials: dict[str, WebAuthnCredential]) -> None:
        with table_element(title=None, searchable=False,
                           sortable=False) as table:
            for credential in webauthn_credentials.values():
                table.row()
                table.cell(_("Actions"), css="buttons")
                delete_url = make_confirm_link(
                    url=makeactionuri(
                        request, transactions,
                        [("_delete", credential["credential_id"])]),
                    message=_("Do you really want to delete this credential"),
                )
                html.icon_button(delete_url, _("Delete this credential"),
                                 "delete")

                html.icon_button(
                    makeuri_contextless(
                        request,
                        [("_edit", credential["credential_id"])],
                        filename="user_two_factor_edit_credential.py",
                    ),
                    _("Edit this credential"),
                    "edit",
                )
                table.cell(_("Alias"), credential["alias"])
                table.cell(
                    _("Registered at"),
                    time.strftime("%Y-%m-%d %H:%M:%S",
                                  time.localtime(credential["registered_at"])),
                )
Esempio n. 10
0
 def _page_menu_entries_details(self) -> Iterator[PageMenuEntry]:
     yield PageMenuEntry(
         title=_("Show all settings"),
         icon_name="checked_checkbox" if self._show_only_modified else "checkbox",
         item=make_simple_link(
             makeactionuri(request, transactions, [
                 ("_show_only_modified", "0" if self._show_only_modified else "1"),
             ])),
     )
Esempio n. 11
0
    def _page_menu_entries_all_sites(self) -> Iterator[PageMenuEntry]:
        if not self._may_activate_changes():
            return

        yield PageMenuEntry(
            title=_("Discard all pending changes"),
            icon_name="delete",
            item=make_simple_link(makeactionuri(request, transactions, [("_action", "discard")])),
            name="discard_changes",
            is_enabled=self.has_changes() and self._get_last_wato_snapshot_file(),
        )
Esempio n. 12
0
def page_menu_all_hosts_entries(should_use_dns_cache: bool) -> Iterator[PageMenuEntry]:
    if should_use_dns_cache:
        yield PageMenuEntry(
            title=_("Update DNS cache"),
            icon_name="update",
            item=make_simple_link(
                makeactionuri(request, transactions, [("_update_dns_cache", "1")])
            ),
            shortcut_title=_("Update site DNS cache"),
            is_shortcut=True,
            is_suggested=True,
        )
Esempio n. 13
0
    def _show_row_cells(self, table, name, group):
        table.cell(_("Actions"), css="buttons")
        edit_url = watolib.folder_preserving_link([("mode", "edit_%s_group" % self.type_name),
                                                   ("edit", name)])
        delete_url = make_confirm_link(
            url=makeactionuri(request, transactions, [("_delete", name)]),
            message=_('Do you really want to delete the %s group "%s"?') % (self.type_name, name))
        clone_url = watolib.folder_preserving_link([("mode", "edit_%s_group" % self.type_name),
                                                    ("clone", name)])
        html.icon_button(edit_url, _("Properties"), "edit")
        html.icon_button(clone_url, _("Create a copy of this group"), "clone")
        html.icon_button(delete_url, _("Delete"), "delete")

        table.cell(_("Name"), name)
        table.cell(_("Alias"), group['alias'])
Esempio n. 14
0
def _page_menu_entries_ack_werk(werk: Dict[str, Any]) -> Iterator[PageMenuEntry]:
    if not may_acknowledge():
        return

    ack_url = makeactionuri(
        request, transactions, [("_werk_ack", werk["id"])], filename="change_log.py"
    )
    yield PageMenuEntry(
        title=_("Acknowledge"),
        icon_name="werk_ack",
        item=make_simple_link(ack_url),
        is_enabled=werk["compatible"] == "incomp_unack",
        is_shortcut=True,
        is_suggested=True,
    )
Esempio n. 15
0
def _page_menu_entries_ack_all_werks() -> Iterator[PageMenuEntry]:
    if not may_acknowledge():
        return

    yield PageMenuEntry(
        title=_("Acknowledge all"),
        icon_name="werk_ack",
        is_shortcut=True,
        is_suggested=True,
        item=make_simple_link(
            make_confirm_link(
                url=makeactionuri(request, transactions, [("_ack_all", "1")]),
                message=_("Do you really want to acknowledge <b>all</b> incompatible werks?"),
            )
        ),
        is_enabled=bool(unacknowledged_incompatible_werks()),
    )
Esempio n. 16
0
    def _page_menu_entries_export(self) -> Iterator[PageMenuEntry]:
        if not self._log_exists():
            return

        if not user.may("wato.auditlog"):
            return

        if not user.may("wato.edit"):
            return

        if not user.may("general.csv_export"):
            return

        yield PageMenuEntry(
            title=_("Export CSV"),
            icon_name="download_csv",
            item=make_simple_link(makeactionuri(request, transactions, [("_action", "csv")])),
        )
Esempio n. 17
0
def render_page_confirm(acktime, failed_notifications):
    title = _("Confirm failed notifications")
    breadcrumb = make_simple_page_breadcrumb(
        mega_menu_registry.menu_monitoring(), title)

    confirm_url = make_simple_link(
        make_confirm_link(
            url=makeactionuri(request, transactions,
                              [("acktime", str(acktime)), ("_confirm", "1")]),
            message=
            _("Do you really want to acknowledge all failed notifications up to %s?"
              ) % cmk.utils.render.date_and_time(acktime),
        ))

    page_menu = PageMenu(
        dropdowns=[
            PageMenuDropdown(
                name="actions",
                title=_("Actions"),
                topics=[
                    PageMenuTopic(
                        title=_("Actions"),
                        entries=[
                            PageMenuEntry(
                                title=_("Confirm"),
                                icon_name="save",
                                item=confirm_url,
                                is_shortcut=True,
                                is_suggested=True,
                                is_enabled=failed_notifications,
                            ),
                        ],
                    ),
                ],
            ),
        ],
        breadcrumb=breadcrumb,
    )
    html.header(title, breadcrumb, page_menu)

    render_notification_table(failed_notifications)

    html.footer()
Esempio n. 18
0
    def _page_menu_entries_actions(self) -> Iterator[PageMenuEntry]:
        if not self._log_exists():
            return

        if not user.may("wato.auditlog"):
            return

        if not user.may("wato.edit"):
            return

        if user.may("wato.clear_auditlog"):
            yield PageMenuEntry(
                title=_("Clear log"),
                icon_name="delete",
                item=make_simple_link(
                    make_confirm_link(
                        url=makeactionuri(request, transactions, [("_action", "clear")]),
                        message=_("Do you really want to clear the audit log?"),
                    )),
            )
Esempio n. 19
0
    def _page_menu(self, acktime: float,
                   failed_notifications: LivestatusResponse,
                   breadcrumb: Breadcrumb) -> PageMenu:
        confirm_url = make_simple_link(
            make_confirm_link(
                url=makeactionuri(request,
                                  transactions, [("acktime", str(acktime)),
                                                 ("_confirm", "1")]),
                message=
                _("Do you really want to acknowledge all failed notifications up to %s?"
                  ) % cmk.utils.render.date_and_time(acktime),
            ))

        return PageMenu(
            dropdowns=[
                PageMenuDropdown(
                    name="actions",
                    title=_("Actions"),
                    topics=[
                        PageMenuTopic(
                            title=_("Actions"),
                            entries=[
                                PageMenuEntry(
                                    title=_("Confirm"),
                                    icon_name="save",
                                    item=confirm_url,
                                    is_shortcut=True,
                                    is_suggested=True,
                                    is_enabled=bool(failed_notifications),
                                ),
                            ],
                        ),
                    ],
                ),
            ],
            breadcrumb=breadcrumb,
        )
Esempio n. 20
0
    def _render_headers(self, actions_enabled: bool, actions_visible: bool,
                        empty_columns: List[bool]) -> None:
        if self.options["omit_headers"]:
            return

        table_id = self.id

        html.open_tr()
        first_col = True
        for nr, header in enumerate(self.headers):
            if self.options["omit_empty_columns"] and empty_columns[nr]:
                continue

            if header.help_txt:
                header_title: HTML = html.render_span(header.title,
                                                      title=header.help_txt)
            else:
                header_title = header.title

            if not isinstance(header.css, list):
                css_class: "CSSSpec" = [header.css]
            else:
                css_class = header.css

            assert isinstance(css_class, list)
            css_class = [("header_%s" % c) for c in css_class if c is not None]

            if not self.options["sortable"] or not header.sortable:
                html.open_th(class_=css_class)
            else:
                css_class.insert(0, "sort")
                reverse = 0
                sort = request.get_ascii_input("_%s_sort" % table_id)
                if sort:
                    sort_col, sort_reverse = map(int, sort.split(",", 1))
                    if sort_col == nr:
                        reverse = 1 if sort_reverse == 0 else 0

                action_uri = makeactionuri(request, transactions,
                                           [("_%s_sort" % table_id, "%d,%d" %
                                             (nr, reverse))])
                html.open_th(
                    class_=css_class,
                    title=_("Sort by %s") % header.title,
                    onclick="location.href='%s'" % action_uri,
                )

            # Add the table action link
            if first_col:
                first_col = False
                if actions_enabled:
                    if not header_title:
                        header_title = HTML(
                            "&nbsp;"
                        )  # Fixes layout problem with white triangle

                    if actions_visible:
                        state = "0"
                        help_txt = _("Hide table actions")
                        img = "table_actions_on"
                    else:
                        state = "1"
                        help_txt = _("Display table actions")
                        img = "table_actions_off"

                    html.open_div(class_=["toggle_actions"])
                    html.icon_button(
                        makeuri(request, [("_%s_actions" % table_id, state)]),
                        help_txt,
                        img,
                        cssclass="toggle_actions",
                    )
                    html.span(header_title)
                    html.close_div()
                else:
                    html.write_text(header_title)
            else:
                html.write_text(header_title)

            html.close_th()
        html.close_tr()
Esempio n. 21
0
    def render_job_row(cls,
                       job_id,
                       job_status,
                       odd,
                       job_details_back_url=None):
        html.open_tr(css="data %s0" % odd)

        # Actions
        html.open_td(css="job_actions")
        if job_status.get("may_stop"):
            html.icon_button(
                makeactionuri(request, transactions,
                              [(ActionHandler.stop_job_var, job_id)]),
                _("Stop this job"),
                "disable_test",
            )
        if job_status.get("may_delete"):
            html.icon_button(
                makeactionuri(request, transactions,
                              [(ActionHandler.delete_job_var, job_id)]),
                _("Delete this job"),
                "delete",
            )
        html.close_td()

        # Job ID
        html.open_td(css="job_id")
        uri = makeuri_contextless(
            request,
            [
                ("mode", "background_job_details"),
                ("back_url", job_details_back_url),
                ("job_id", job_id),
            ],
            filename="wato.py",
        )
        html.a(job_id, href=uri)
        html.close_td()

        # Title
        html.td(job_status.get("title", _("Background Job")), css="job_title")

        # State
        html.td(html.render_span(job_status["state"]),
                css=cls.get_css_for_jobstate(job_status["state"]))

        # Started
        html.td(cmk.utils.render.date_and_time(job_status["started"]),
                css="job_started")

        # Owner
        html.td(job_status.get("user", _("Unknown user")), css="job_owner")

        # PID
        html.td(job_status["pid"] or "", css="job_pid")

        # Druation
        html.td(cmk.utils.render.timespan(job_status.get("duration", 0)),
                css="job_runtime")

        # Progress info
        loginfo = job_status.get("loginfo")
        if loginfo:
            if job_status.get(
                    "state") == background_job.JobStatusStates.EXCEPTION:
                html.td(HTML("<br>".join(loginfo["JobException"])),
                        css="job_last_progress")
            else:
                progress_text = ""
                if loginfo["JobProgressUpdate"]:
                    progress_text += "%s" % loginfo["JobProgressUpdate"][-1]
                html.td(HTML(progress_text), css="job_last_progress")

            html.td(HTML("<br>".join(loginfo["JobResult"])), css="job_result")
        else:
            html.td("", css="job_last_progress")
            html.td("", css="job_result")
Esempio n. 22
0
    def show_job_details(cls, job_id, job_status):
        """Renders the complete job details in a single table with left headers"""
        html.open_table(class_=["data", "headerleft", "job_details"])

        # Static info
        for left, right in [
            (_("ID"), job_id),
            (_("Title"), job_status.get("title", "")),
            (_("Started"),
             cmk.utils.render.date_and_time(job_status["started"])),
            (_("Owner"), job_status.get("user", "")),
        ]:
            html.open_tr()
            html.th(left)
            html.td(right)
            html.close_tr()

        # Actions
        html.open_tr()
        html.th(_("Actions"))
        html.open_td()
        if job_status.get("may_stop"):
            html.icon_button(
                make_confirm_link(
                    url=makeactionuri(request, transactions,
                                      [(ActionHandler.stop_job_var, job_id)]),
                    message=_("Stop job %s%s?") %
                    (job_id, cls._get_extra_info(job_status)),
                ),
                _("Stop this job"),
                "disable_test",
            )
        if job_status.get("may_delete"):
            html.icon_button(
                make_confirm_link(
                    url=makeactionuri(
                        request, transactions,
                        [(ActionHandler.delete_job_var, job_id)]),
                    message=_("Delete job %s%s?") %
                    (job_id, cls._get_extra_info(job_status)),
                ),
                _("Delete this job"),
                "delete",
            )
        html.close_td()
        html.close_tr()

        # Job state
        html.open_tr()
        html.th(_("State"))
        html.td(job_status["state"],
                css=cls.get_css_for_jobstate(job_status["state"]))
        html.close_tr()

        if job_status["state"] == background_job.JobStatusStates.EXCEPTION:
            html.open_tr()
            html.th(_("Acknowledged by"))
            html.td(job_status.get("acknowledged_by", ""))
            html.close_tr()

        # Dynamic data
        loginfo = job_status.get("loginfo")
        runtime_info = cmk.utils.render.timespan(job_status.get("duration", 0))
        if (job_status["state"] == background_job.JobStatusStates.RUNNING
                and job_status.get("estimated_duration") is not None):
            runtime_info += " (%s: %s)" % (
                _("estimated duration"),
                cmk.utils.render.timespan(job_status["estimated_duration"]),
            )
        for left, right in [
            (_("Runtime"), runtime_info),
            (_("PID"), str(job_status["pid"]) or ""),
            (_("Result"), "<br>".join(loginfo["JobResult"])),
        ]:
            if right is None:
                continue
            html.open_tr()
            html.th(left)
            html.td(HTML(right))
            html.close_tr()

        # Exceptions
        exceptions = loginfo["JobException"]
        if exceptions:
            html.open_tr()
            html.th(_("Exceptions"))
            html.open_td()
            if exceptions and "logfile_path" in job_status:
                exceptions.append(
                    _("More information can be found in %s") %
                    job_status["logfile_path"])
            html.open_div(class_="log_output", id_="exception_log")
            html.pre("\n".join(exceptions))
            html.close_div()
            html.close_td()
            html.close_tr()

        # Progress Update
        html.open_tr()
        html.th(_("Progress Info"))
        html.open_td()
        html.open_div(class_="log_output",
                      style="height: 400px;",
                      id_="progress_log")
        html.pre(HTML("\n").join(loginfo["JobProgressUpdate"]))
        html.close_div()
        html.close_td()
        html.close_tr()

        html.close_table()
Esempio n. 23
0
    def _show_test_row(self, table, test_id, test_results_by_site, site_ids):
        table.row()

        table.cell(_("Actions"), css="buttons", sortable=False)
        html.icon_button(None,
                         _("Toggle result details"),
                         "toggle_details",
                         onclick="cmk.wato.toggle_container('test_result_details_%s')" % test_id)

        worst_result = sorted(test_results_by_site["site_results"].values(),
                              key=lambda result: result.status)[0]

        # Disabling of test in total
        is_test_disabled = self._is_test_disabled(test_id)
        if is_test_disabled:
            html.icon_button(
                makeactionuri(request, transactions, [
                    ("_do", "enable"),
                    ("_test_id", worst_result.test_id),
                ]),
                _("Reenable this test"),
                "enable_test",
            )
        else:
            html.icon_button(
                makeactionuri(request, transactions, [
                    ("_do", "disable"),
                    ("_test_id", worst_result.test_id),
                ]),
                _("Disable this test"),
                "disable_test",
            )

        # assume all have the same test meta information (title, help, ...)
        table.cell(_("Title"), css="title " + "stale" if is_test_disabled else "")
        html.write_text(test_results_by_site["test"]["title"])

        # Now loop all sites to display their results
        for site_id in site_ids:
            if is_test_disabled:
                table.cell(site_id, "")
                table.cell("", "")
                continue

            result = test_results_by_site["site_results"].get(site_id)
            if result is None:
                table.cell(site_id, css="state state-1")
                table.cell("", css="buttons")
                continue

            is_acknowledged = self._is_acknowledged(result)

            if is_acknowledged or result.status == -1:
                css = "state stale"
            else:
                css = "state state%d" % result.status

            table.cell(site_id, css=css)
            html.open_div(title=result.text)
            html.write_text(result.status_name())
            html.close_div()

            table.cell("", css="buttons")

            if result.status != 0:
                if is_acknowledged:
                    html.icon_button(
                        makeactionuri(request, transactions, [
                            ("_do", "unack"),
                            ("_site_id", result.site_id),
                            ("_status_id", result.status),
                            ("_test_id", result.test_id),
                        ]),
                        _("Unacknowledge this test result for site %s") % site_id,
                        "unacknowledge_test",
                    )
                else:
                    html.icon_button(
                        makeactionuri(request, transactions, [
                            ("_do", "ack"),
                            ("_site_id", result.site_id),
                            ("_status_id", result.status),
                            ("_test_id", result.test_id),
                        ]),
                        _("Acknowledge this test result for site %s") % site_id,
                        "acknowledge_test",
                    )
            else:
                html.write_text("")

        # Add toggleable notitication context
        table.row(class_="ac_test_details hidden", id_="test_result_details_%s" % test_id)
        table.cell(colspan=2 + 2 * len(site_ids))

        html.write_text(test_results_by_site["test"]["help"])

        if not is_test_disabled:
            html.open_table()
            for site_id in site_ids:
                result = test_results_by_site["site_results"].get(site_id)
                if result is None:
                    continue

                html.open_tr()
                html.td(escaping.escape_attribute(site_id))
                html.td("%s: %s" % (result.status_name(), result.text))
                html.close_tr()
            html.close_table()

        # This dummy row is needed for not destroying the odd/even row highlighting
        table.row(class_="hidden")
Esempio n. 24
0
def page_menu_host_entries(mode_name: str,
                           host: CREHost) -> Iterator[PageMenuEntry]:
    if mode_name != "edit_host":
        yield PageMenuEntry(
            title=_("Properties"),
            icon_name="edit",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "edit_host"),
                                                ("host", host.name())])),
        )

    if mode_name != "inventory":
        yield PageMenuEntry(
            title=_("Service configuration"),
            icon_name="services",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "inventory"),
                                                ("host", host.name())])),
        )

    if mode_name != "diag_host" and not host.is_cluster():
        yield PageMenuEntry(
            title=_("Connection tests"),
            icon_name="diagnose",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "diag_host"),
                                                ("host", host.name())])),
        )

    if mode_name != "object_parameters" and user.may("wato.rulesets"):
        yield PageMenuEntry(
            title=_("Effective parameters"),
            icon_name="rulesets",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "object_parameters"),
                                                ("host", host.name())])),
        )

    if mode_name == "object_parameters" or mode_name == "edit_host" and user.may(
            "wato.rulesets"):
        yield PageMenuEntry(
            title=_("Rules"),
            icon_name="rulesets",
            item=make_simple_link(
                makeuri_contextless(
                    request,
                    [
                        ("mode", "rule_search"),
                        ("filled_in", "search"),
                        ("search_p_ruleset_deprecated", "OFF"),
                        ("search_p_rule_host_list_USE", "ON"),
                        ("search_p_rule_host_list", host.name()),
                    ],
                    filename="wato.py",
                )),
        )

    yield make_host_status_link(host_name=host.name(), view_name="hoststatus")

    if user.may("wato.rulesets") and host.is_cluster():
        yield PageMenuEntry(
            title=_("Clustered services"),
            icon_name="rulesets",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "edit_ruleset"),
                                                ("varname",
                                                 "clustered_services")])),
        )

    if watolib.has_agent_bakery() and user.may("wato.download_agents"):
        yield PageMenuEntry(
            title=_("Monitoring agent"),
            icon_name="agents",
            item=make_simple_link(
                watolib.folder_preserving_link([("mode", "agent_of_host"),
                                                ("host", host.name())])),
        )

    if mode_name == "edit_host" and not host.locked():
        if user.may("wato.rename_hosts"):
            yield PageMenuEntry(
                title=_("Rename"),
                icon_name="rename_host",
                item=make_simple_link(
                    watolib.folder_preserving_link([("mode", "rename_host"),
                                                    ("host", host.name())])),
            )

        if user.may("wato.manage_hosts") and user.may("wato.clone_hosts"):
            yield PageMenuEntry(
                title=_("Clone"),
                icon_name="insert",
                item=make_simple_link(host.clone_url()),
            )

        yield PageMenuEntry(
            title=_("Delete"),
            icon_name="delete",
            item=make_simple_link(
                make_confirm_link(
                    url=makeactionuri(request, transactions,
                                      [("delete", "1")]),
                    message=_(
                        "Do you really want to delete the host <tt>%s</tt>?") %
                    host.name(),
                )),
        )

        if user.may("wato.auditlog"):
            yield PageMenuEntry(
                title=_("Audit log"),
                icon_name="auditlog",
                item=make_simple_link(
                    make_object_audit_log_url(host.object_ref())),
            )
Esempio n. 25
0
    def _show_configuration_variables(self) -> None:
        search = self._search

        at_least_one_painted = False
        html.open_div(class_="globalvars")
        for group, config_variables in self.iter_all_configuration_variables():
            header_is_painted = False  # needed for omitting empty groups

            for config_variable in config_variables:
                varname = config_variable.ident()
                valuespec = config_variable.valuespec()

                if self._show_only_modified and varname not in self._current_settings:
                    continue

                help_text = valuespec.help() or ""
                title_text = valuespec.title() or ""

                if (search and search not in group.title().lower() and search
                        not in config_variable.domain().ident().lower()
                        and search not in varname
                        and search not in help_text.lower()
                        and search not in title_text.lower()):
                    continue  # skip variable when search is performed and nothing matches
                at_least_one_painted = True

                if not header_is_painted:
                    # always open headers when searching
                    forms.header(group.title(),
                                 isopen=search or self._show_only_modified)
                    header_is_painted = True

                default_value = self._default_values[varname]

                edit_url = folder_preserving_link([
                    ("mode", self.edit_mode_name),
                    ("varname", varname),
                    ("site", request.var("site", "")),
                ])
                title = HTMLWriter.render_a(
                    title_text,
                    href=edit_url,
                    class_="modified"
                    if varname in self._current_settings else None,
                    title=escaping.strip_tags(help_text),
                )

                if varname in self._current_settings:
                    value = self._current_settings[varname]
                elif varname in self._global_settings:
                    value = self._global_settings[varname]
                else:
                    value = default_value

                try:
                    to_text = valuespec.value_to_html(value)
                except Exception:
                    logger.exception("error converting %r to text", value)
                    to_text = html.render_error(
                        _("Failed to render value: %r") % value)

                # Is this a simple (single) value or not? change styling in these cases...
                simple = True
                if "\n" in to_text or "<td>" in to_text:
                    simple = False
                forms.section(title, simple=simple)

                if varname in self._current_settings:
                    modified_cls = ["modified"]
                    value_title: Optional[str] = _(
                        "This option has been modified.")
                elif varname in self._global_settings:
                    modified_cls = ["modified globally"]
                    value_title = _(
                        "This option has been modified in global settings.")
                else:
                    modified_cls = []
                    value_title = None

                if is_a_checkbox(valuespec):
                    html.open_div(class_=["toggle_switch_container"] +
                                  modified_cls + (["on"] if value else []))
                    html.toggle_switch(
                        enabled=value,
                        help_txt=_("Immediately toggle this setting"),
                        href=makeactionuri(request, transactions,
                                           [("_action", "toggle"),
                                            ("_varname", varname)]),
                        class_=modified_cls,
                        title=value_title,
                    )
                    html.close_div()

                else:
                    html.a(to_text,
                           href=edit_url,
                           class_=modified_cls,
                           title=value_title)

            if header_is_painted:
                forms.end()
        if not at_least_one_painted and search:
            html.show_message(
                _("Did not find any global setting matching your search."))
        html.close_div()