예제 #1
0
    def _show_failed_notifications(self):
        if not self.parameters()["show_failed_notifications"]:
            return

        failed_notifications = notifications.number_of_failed_notifications(
            after=notifications.acknowledged_time()
        )
        if not failed_notifications:
            return

        html.open_div(class_="spacertop")
        html.open_div(class_="tacticalalert")

        confirm_url = makeuri_contextless(request, [], filename="clear_failed_notifications.py")
        html.icon_button(confirm_url, _("Confirm failed notifications"), "delete", target="main")

        view_url = makeuri_contextless(
            request,
            [("view_name", "failed_notifications")],
            filename="view.py",
        )

        html.a(_("%d failed notifications") % failed_notifications, target="main", href=view_url)
        html.close_div()
        html.close_div()
예제 #2
0
파일: mobile.py 프로젝트: LinuxHaus/checkmk
def jqm_page_navfooter(items: NavigationBar, current: str, page_id: str) -> None:
    html.close_div()  # close content
    html.open_div(
        **{
            "data-role": "footer",
            "data-position": "fixed",
            "data-tap-toggle": "false",
            "data-hide-during-focus": "",
        }
    )
    html.open_div(**{"data-role": "navbar"})
    html.open_ul()

    for href, title, icon, custom_css in items:
        href = makeuri(request, [("page", href), ("search", "Search")])
        if current == href:
            custom_css += " ui-state-persist ui-btn-active"
        else:
            html.open_li()
            html.a(
                title,
                href=href,
                class_=custom_css,
                **{
                    "data-transition": "slide",
                    "data-icon": icon,
                    "data-iconpos": "bottom",
                },
            )
            html.close_li()
    html.close_ul()
    html.close_div()
    html.close_div()
    html.close_div()  # close page-div
예제 #3
0
    def _create_status_box(
        self,
        site_ids: Collection[livestatus.SiteId],
        css_class: str,
        site_status: str,
    ):
        html.open_div(class_="spacertop")
        html.open_div(class_=css_class)
        message_template = ungettext("%d site is %s.", "%d sites are %s.", len(site_ids))
        message = message_template % (len(site_ids), site_status)
        tooltip_template = ungettext(
            "Associated hosts, services and events are not included "
            "in the Tactical Overview. The %s site is %s.",
            "Associated hosts, services and events are not included "
            "in the Tactical Overview. The %s sites are %s.",
            len(site_ids),
        )
        tooltip = tooltip_template % (site_status, ", ".join(site_ids))

        if user.may("wato.sites"):
            url = makeuri_contextless(request, [("mode", "sites")], filename="wato.py")
            html.icon_button(url, tooltip, "sites", target="main")
            html.a(message, target="main", href=url)
        else:
            html.icon("sites", tooltip)
            html.write_text(message)
        html.close_div()
        html.close_div()
예제 #4
0
    def show(self):
        failed_notifications = notifications.number_of_failed_notifications(
            after=notifications.acknowledged_time())
        if not failed_notifications:
            return

        html.open_div(class_="has_failed_notifications")
        html.open_div(class_="failed_notifications_inner")

        confirm_url = makeuri_contextless(
            request, [], filename="clear_failed_notifications.py")
        html.icon_button(confirm_url,
                         _("Clear failed notifications"),
                         "closetimewarp",
                         target="main")

        view_url = makeuri_contextless(
            request,
            [("view_name", "failed_notifications")],
            filename="view.py",
        )
        html.a(_("%d failed notifications") % failed_notifications,
               href=view_url)

        html.close_div()
        html.close_div()
예제 #5
0
파일: tags.py 프로젝트: LinuxHaus/checkmk
def _show_affected_folders(affected_folders: List[CREFolder]) -> None:
    html.open_ul()
    for folder in affected_folders:
        html.open_li()
        html.a(folder.alias_path(), href=folder.edit_url())
        html.close_li()
    html.close_ul()
예제 #6
0
파일: werks.py 프로젝트: LinuxHaus/checkmk
    def page(self) -> cmk.gui.pages.PageResult:
        breadcrumb = make_simple_page_breadcrumb(
            mega_menu_registry["help_links"], _("Info"))
        make_header(
            html,
            self._title(),
            breadcrumb=breadcrumb,
        )

        html.open_div(id_="info_title")
        html.h1(_("Your monitoring machine"))
        html.a(
            HTMLWriter.render_img(theme.url("images/tribe29.svg")),
            "https://tribe29.com",
            target="_blank",
        )
        html.close_div()

        html.div(None, id_="info_underline")

        html.open_div(id_="info_intro_text")
        html.span(_("Open. Effective. Awesome."))
        html.span(
            _("May we present? Monitoring as it's supposed to be: "
              "incredibly quick to install, infinetely scalable, highly customizable and "
              "designed for admins."))
        html.span(
            _("Visit our %s to learn more about Checkmk and about the %s.") % (
                HTMLWriter.render_a(
                    _("website"), "https://checkmk.com", target="_blank"),
                HTMLWriter.render_a(
                    _("latest version"),
                    "https://checkmk.com/product/latest-version",
                    target="_blank",
                ),
            ))
        html.close_div()

        version_major_minor = re.sub(r".\d+$", "",
                                     Version(__version__).version_base)
        if version_major_minor:
            current_version_link = "https://checkmk.com/product/checkmk-%s" % version_major_minor
        else:
            current_version_link = "https://checkmk.com/product/latest-version"

        html.open_div(id="info_image")
        html.open_a(href=current_version_link, target="_blank")
        html.img(theme.url("images/monitoring-machine.png"))
        html.close_a()
        html.close_div()

        html.close_div()

        html.open_div(id_="info_footer")
        html.span(
            _("© %s tribe29 GmbH. All Rights Reserved.") % time.strftime("%Y"))
        html.a(_("License agreement"),
               href="https://checkmk.com/legal.html",
               target="_blank")
        html.close_div()
예제 #7
0
파일: mobile.py 프로젝트: LinuxHaus/checkmk
def jqm_header_button(pos: str, url: str, title: str, icon: str = "") -> None:
    html.a(
        "",
        href=url,
        class_="ui-btn-%s" % pos,
        title=title,
        **{"data-direction": "reverse", "data-icon": icon, "data-iconpos": "notext"},
    )
예제 #8
0
    def show(self, breadcrumb: Breadcrumb) -> None:
        html.open_div(class_="breadcrumb")

        for item in breadcrumb:
            if item.url:
                html.a(escape_to_html(str(item.title)), href=item.url)
            else:
                html.span(escape_to_html(str(item.title)))

        html.close_div()
예제 #9
0
파일: tags.py 프로젝트: LinuxHaus/checkmk
def _show_affected_rulesets(affected_rulesets: List[Ruleset]) -> None:
    html.open_ul()
    for ruleset in affected_rulesets:
        html.open_li()
        html.a(
            ruleset.title(),
            href=folder_preserving_link([("mode", "edit_ruleset"),
                                         ("varname", ruleset.name)]),
        )
        html.close_li()
    html.close_ul()
예제 #10
0
파일: mobile.py 프로젝트: LinuxHaus/checkmk
def page_index() -> None:
    title = _("Checkmk Mobile")
    mobile_html_head(title)
    jqm_page_header(
        title,
        right_button=("javascript:document.location.reload();", _("Reload"), "refresh"),
        id_="data",
    )
    items = []
    for view_name, view_spec in views.get_permitted_views().items():
        if view_spec.get("mobile") and not view_spec.get("hidden"):

            datasource = data_source_registry[view_spec["datasource"]]()
            context = visuals.active_context_from_request(datasource.infos, view_spec["context"])

            view = views.View(view_name, view_spec, context)
            view.row_limit = views.get_limit()
            view.only_sites = visuals.get_only_sites_from_context(context)
            view.user_sorters = views.get_user_sorters()
            view.want_checkboxes = views.get_want_checkboxes()

            url = "mobile_view.py?view_name=%s" % view_name
            count = ""
            if not view_spec.get("mustsearch"):
                painter_options = PainterOptions.get_instance()
                painter_options.load(view_name)
                count = '<span class="ui-li-count">%d</span>' % views.get_row_count(view)

            topic = PagetypeTopics.get_topic(view_spec.get("topic", ""))
            items.append((topic.title(), url, "%s %s" % (view_spec["title"], count)))

    jqm_page_index(_("Checkmk Mobile"), items)
    # Link to non-mobile GUI

    html.hr()
    html.open_ul(**{"data-role": "listview", "data-theme": "b", "data-inset": "true"})
    html.open_li()
    html.a(
        _("Classical web GUI"),
        href="index.py?mobile=",
        **{"data-ajax": "false", "data-transition": "fade"},
    )
    html.close_li()
    html.close_ul()

    html.open_ul(**{"data-role": "listview", "data-theme": "f", "data-inset": "true"})
    html.open_li()
    html.a(_("Logout"), href="logout.py", **{"data-ajax": "false", "data-transition": "fade"})
    html.close_li()
    html.close_ul()
    mobile_html_foot()
예제 #11
0
파일: tags.py 프로젝트: LinuxHaus/checkmk
def _show_affected_hosts(affected_hosts: List[CREHost]) -> None:
    html.open_ul()
    html.open_li()
    for nr, host in enumerate(affected_hosts):
        if nr > 20:
            html.write_text(_("... (%d more)") % (len(affected_hosts) - 20))
            break

        if nr > 0:
            html.write_text(", ")

        html.a(host.name(), href=host.edit_url())
    html.close_li()
    html.close_ul()
예제 #12
0
파일: werks.py 프로젝트: LinuxHaus/checkmk
def render_unacknowleged_werks():
    werks = unacknowledged_incompatible_werks()
    if werks and not request.has_var("show_unack"):
        html.open_div(class_=["warning"])
        html.write_text(
            _("<b>Warning:</b> There are %d unacknowledged incompatible werks:"
              ) % len(werks))
        html.br()
        html.br()
        html.a(
            _("Show unacknowledged incompatible werks"),
            href=makeuri_contextless(request, [("show_unack", "1"),
                                               ("wo_compatibility", "3")]),
        )
        html.close_div()
예제 #13
0
 def _show_tree_nodes(self, maps, children):
     for map_name, map_cfg in maps.items():
         html.open_li()
         if map_name in children:
             with foldable_container(
                 treename="nagvis",
                 id_=map_name,
                 isopen=False,
                 title=map_cfg["alias"],
                 title_url=map_cfg["url"],
                 title_target="main",
                 indent=False,
                 icon="foldable_sidebar",
             ):
                 self._show_tree_nodes(children[map_name], children)
         else:
             html.a(map_cfg["alias"], href=map_cfg["url"], target="main", class_="link")
         html.close_li()
예제 #14
0
    def _show_popup(self, entry: PageMenuEntry) -> None:
        assert isinstance(entry.item, PageMenuPopup)

        if entry.name is None:
            raise ValueError('Missing "name" attribute on entry "%s"' % entry.title)

        classes = ["page_menu_popup"]
        classes += [c for c in entry.item.css_classes if c is not None]
        if isinstance(entry.item, PageMenuSidePopup):
            classes.append("side_popup")

        popup_id = "popup_%s" % entry.name
        html.open_div(id_=popup_id, class_=classes)

        html.open_div(class_="head")
        html.h3(entry.title)
        html.a(
            html.render_icon("close"),
            class_="close_popup",
            href="javascript:void(0)",
            onclick="cmk.page_menu.close_popup(this)",
        )
        html.close_div()

        if (
            isinstance(entry.item, PageMenuSidePopup)
            and entry.item.content
            and "side_popup_content" not in entry.item.content
        ):
            raise RuntimeError(
                'Add a div container with the class "side_popup_content" to the popup content'
            )

        html.open_div(class_="content")
        html.write_html(entry.item.content)
        html.close_div()
        html.close_div()

        if isinstance(entry.item, PageMenuSidePopup):
            html.final_javascript(
                "cmk.page_menu.side_popup_add_simplebar_scrollbar(%s);" % json.dumps(popup_id)
            )
예제 #15
0
파일: tags.py 프로젝트: LinuxHaus/checkmk
def _show_aux_tag_used_by_tags(tags: Set[cmk.utils.tags.GroupedTag]) -> None:
    if not tags:
        return

    html.open_ul()
    html.open_li()
    builtin_config = cmk.utils.tags.BuiltinTagConfig()
    for index, tag in enumerate(sorted(tags, key=lambda t: t.choice_title)):
        if index > 0:
            html.write_text(", ")

        # Builtin tag groups can not be edited
        if builtin_config.tag_group_exists(tag.group.id):
            html.write_text(_u(tag.choice_title))
        else:
            edit_url = folder_preserving_link([("mode", "edit_tag"),
                                               ("edit", tag.group.id)])
            html.a(_u(tag.choice_title), href=edit_url)
    html.close_li()
    html.close_ul()
예제 #16
0
    def _show_ruleset(self, varname):
        if varname not in rulespec_registry:
            return

        rulespec = rulespec_registry[varname]
        url = makeuri_contextless(request, [("mode", "edit_ruleset"),
                                            ("varname", varname)])
        html.open_tr()
        html.th(_("Parameter rule set"))
        html.open_td()
        html.icon_button(url, _("Edit parameter rule set for this check type"),
                         "check_parameters")
        html.a(rulespec.title, url)
        html.close_td()
        html.close_tr()
        html.open_tr()
        html.th(_("Example for Parameters"))
        html.open_td()
        vs = rulespec.valuespec
        vs.render_input("dummy", vs.default_value())
        html.close_td()
        html.close_tr()
예제 #17
0
    def _download_table(self, title: str, paths: List[str]) -> None:
        forms.header(title)
        forms.container()
        for path in paths:
            os_path = path
            relpath = path.replace(cmk.utils.paths.agents_dir + "/", "")
            filename = path.split("/")[-1]

            file_size = os.stat(os_path).st_size

            # FIXME: Rename classes etc. to something generic
            html.open_div(class_="ruleset")
            html.open_div(style="width:300px;", class_="text")
            html.a(filename, href="agents/%s" % relpath, download=filename)
            html.span("." * 200, class_="dots")
            html.close_div()
            html.div(cmk.utils.render.fmt_bytes(file_size),
                     style="width:60px;",
                     class_="rulecount")
            html.close_div()
            html.close_div()
        forms.end()
예제 #18
0
    def _show_table(self, api_request):
        html.open_table(class_="allhosts")
        html.open_tbody()

        for map_cfg in api_request["maps"]:
            html.open_tr()
            html.open_td()
            html.div(
                "",
                class_=[
                    "statebullet",
                    self._state_class(map_cfg),
                    self._sub_state_class(map_cfg),
                    self._stale_class(map_cfg),
                ],
                title=self._state_title(map_cfg),
            )
            html.a(map_cfg["alias"], href=map_cfg["url"], class_="link", target="main")
            html.close_td()
            html.close_tr()

        html.close_tbody()
        html.close_table()
예제 #19
0
    def _show_leaf(self, tree, show_host):
        site, host = tree[2]["host"]
        service = tree[2].get("service")

        # Four cases:
        # (1) zbghora17 . Host status   (show_host == True, service is None)
        # (2) zbghora17 . CPU load      (show_host == True, service is not None)
        # (3) Host Status               (show_host == False, service is None)
        # (4) CPU load                  (show_host == False, service is not None)

        if show_host or not service:
            host_url = makeuri_contextless(
                request,
                [("view_name", "hoststatus"), ("site", site), ("host", host)],
                filename="view.py",
            )

        if service:
            service_url = makeuri_contextless(
                request,
                [("view_name", "service"), ("site", site), ("host", host),
                 ("service", service)],
                filename="view.py",
            )

        with self._show_node(tree, show_host):
            self._assume_icon(site, host, service)

            if show_host:
                html.a(host.replace(" ", "&nbsp;"), href=host_url)
                html.b(HTML("&diams;"), class_="bullet")

            if not service:
                html.a(_("Host&nbsp;status"), href=host_url)
            else:
                html.a(service.replace(" ", "&nbsp;"), href=service_url)
예제 #20
0
def foldable_container(
    *,
    treename: str,
    id_: str,
    isopen: bool,
    title: HTMLContent,
    indent: Union[str, None, bool] = True,
    icon: Optional[str] = None,
    fetch_url: Optional[str] = None,
    title_url: Optional[str] = None,
    title_target: Optional[str] = None,
    padding: int = 15,
    save_state: bool = True,
) -> Iterator[bool]:
    isopen = user.get_tree_state(treename, id_, isopen)
    onclick = foldable_container_onclick(treename, id_, fetch_url, save_state)
    img_id = foldable_container_img_id(treename, id_)
    container_id = foldable_container_id(treename, id_)

    html.open_div(class_=["foldable", "open" if isopen else "closed"])
    html.open_div(class_="foldable_header",
                  onclick=None if title_url else onclick)

    if isinstance(title, HTML):  # custom HTML code
        html.write_text(title)

    else:
        html.open_b(class_=["treeangle", "title"])

        if title_url:
            html.a(title, href=title_url, target=title_target)
        else:
            html.write_text(title)
        html.close_b()

    if icon:
        html.img(
            id_=img_id,
            # Although foldable_sidebar is given via the argument icon it should not be displayed as big as an icon.
            class_=(["treeangle", "title"] +
                    (["icon"] if icon != "foldable_sidebar" else []) +
                    ["open" if isopen else "closed"]),
            src=theme.detect_icon_path(icon, "icon_"),
            onclick=onclick if title_url else None,
        )
    else:
        html.img(
            id_=img_id,
            class_=["treeangle", "open" if isopen else "closed"],
            src=theme.url("images/tree_closed.svg"),
            onclick=onclick if title_url else None,
        )

    html.close_div()

    indent_style = "padding-left: %dpx; " % (padding if indent else 0)
    if indent == "form":
        html.close_td()
        html.close_tr()
        html.close_table()
        indent_style += "margin: 0; "
    html.open_ul(id_=container_id,
                 class_=["treeangle", "open" if isopen else "closed"],
                 style=indent_style)

    yield isopen

    html.close_ul()
    html.close_div()
예제 #21
0
    def _show_service_info(self, all_rulesets):
        assert self._service is not None

        serviceinfo = analyse_service(
            self._host.site_id(),
            self._hostname,
            self._service,
        ).service_info
        if not serviceinfo:
            return

        forms.header(_("Check origin and parameters"),
                     isopen=True,
                     narrow=True,
                     css="rulesettings")
        origin = serviceinfo["origin"]
        origin_txt = {
            "active": _("Active check"),
            "static": _("Manual check"),
            "auto": _("Inventorized check"),
            "classic": _("Classical check"),
        }[origin]
        self._render_rule_reason(_("Type of check"), None, "", "", False,
                                 origin_txt)

        # First case: discovered checks. They come from var/check_mk/autochecks/HOST.
        if origin == "auto":
            checkgroup = serviceinfo["checkgroup"]
            checktype = serviceinfo["checktype"]
            if not checkgroup:
                self._render_rule_reason(
                    _("Parameters"),
                    None,
                    "",
                    "",
                    True,
                    _("This check is not configurable via WATO"),
                )

            # Logwatch needs a special handling, since it is not configured
            # via checkgroup_parameters but via "logwatch_rules" in a special
            # WATO module.
            elif checkgroup == "logwatch":
                rulespec = rulespec_registry["logwatch_rules"]
                self._output_analysed_ruleset(
                    all_rulesets,
                    rulespec,
                    svc_desc_or_item=serviceinfo["item"],
                    svc_desc=self._service,
                    known_settings=serviceinfo["parameters"],
                )

            else:
                # Note: some discovered checks have a check group but
                # *no* ruleset for discovered checks. One example is "ps".
                # That can be configured as a manual check or created by
                # inventory. But in the later case all parameters are set
                # by the inventory. This will be changed in a later version,
                # but we need to address it anyway.
                grouprule = "checkgroup_parameters:" + checkgroup
                if grouprule not in rulespec_registry:
                    try:
                        rulespec = rulespec_registry["static_checks:" +
                                                     checkgroup]
                    except KeyError:
                        self._render_rule_reason(
                            _("Parameters"),
                            None,
                            "",
                            "",
                            True,
                            _("This check is not configurable via WATO"),
                        )
                        return

                    url = folder_preserving_link([
                        ("mode", "edit_ruleset"),
                        ("varname", "static_checks:" + checkgroup),
                        ("host", self._hostname),
                    ])
                    assert isinstance(rulespec.valuespec, Tuple)
                    self._render_rule_reason(
                        _("Parameters"),
                        url,
                        _("Determined by discovery"),
                        None,
                        False,
                        rulespec.valuespec._elements[2].value_to_html(
                            serviceinfo["parameters"]),
                    )

                else:
                    rulespec = rulespec_registry[grouprule]
                    self._output_analysed_ruleset(
                        all_rulesets,
                        rulespec,
                        svc_desc_or_item=serviceinfo["item"],
                        svc_desc=self._service,
                        known_settings=serviceinfo["parameters"],
                    )

        elif origin == "static":
            checkgroup = serviceinfo["checkgroup"]
            checktype = serviceinfo["checktype"]
            if not checkgroup:
                html.write_text(_("This check is not configurable via WATO"))
            else:
                rulespec = rulespec_registry["static_checks:" + checkgroup]
                itemspec = rulespec.item_spec
                if itemspec:
                    item_text = itemspec.value_to_html(serviceinfo["item"])
                    assert rulespec.item_spec is not None
                    title = rulespec.item_spec.title()
                else:
                    item_text = serviceinfo["item"]
                    title = _("Item")
                self._render_rule_reason(title, None, "", "", False, item_text)
                self._output_analysed_ruleset(
                    all_rulesets,
                    rulespec,
                    svc_desc_or_item=serviceinfo["item"],
                    svc_desc=self._service,
                    known_settings=self._PARAMETERS_OMIT,
                )
                assert isinstance(rulespec.valuespec, Tuple)
                html.write_text(rulespec.valuespec._elements[2].value_to_html(
                    serviceinfo["parameters"]))
                html.close_td()
                html.close_tr()
                html.close_table()

        elif origin == "active":
            checktype = serviceinfo["checktype"]
            rulespec = rulespec_registry["active_checks:" + checktype]
            self._output_analysed_ruleset(
                all_rulesets,
                rulespec,
                svc_desc_or_item=None,
                svc_desc=None,
                known_settings=serviceinfo["parameters"],
            )

        elif origin == "classic":
            ruleset = all_rulesets.get("custom_checks")
            origin_rule_result = self._get_custom_check_origin_rule(
                ruleset, self._hostname, self._service)
            if origin_rule_result is None:
                raise MKUserError(
                    None,
                    _("Failed to determine origin rule of %s / %s") %
                    (self._hostname, self._service),
                )
            rule_folder, rule_index, rule = origin_rule_result

            url = folder_preserving_link([("mode", "edit_ruleset"),
                                          ("varname", "custom_checks"),
                                          ("host", self._hostname)])
            forms.section(HTMLWriter.render_a(_("Command Line"), href=url))
            url = folder_preserving_link([
                ("mode", "edit_rule"),
                ("varname", "custom_checks"),
                ("rule_folder", rule_folder.path()),
                ("rule_id", rule.id),
                ("host", self._hostname),
            ])

            html.open_table(class_="setting")
            html.open_tr()

            html.open_td(class_="reason")
            html.a("%s %d %s %s" %
                   (_("Rule"), rule_index + 1, _("in"), rule_folder.title()),
                   href=url)
            html.close_td()
            html.open_td(class_=["settingvalue", "used"])
            if "command_line" in serviceinfo:
                html.tt(serviceinfo["command_line"])
            else:
                html.write_text(_("(no command line, passive check)"))
            html.close_td()

            html.close_tr()
            html.close_table()

        self._show_labels(serviceinfo.get("labels", {}), "service",
                          serviceinfo.get("label_sources", {}))
예제 #22
0
    def _output_analysed_ruleset(self,
                                 all_rulesets,
                                 rulespec,
                                 svc_desc_or_item,
                                 svc_desc,
                                 known_settings=None):
        if known_settings is None:
            known_settings = self._PARAMETERS_UNKNOWN

        def rule_url(rule: Rule) -> str:
            return folder_preserving_link([
                ("mode", "edit_rule"),
                ("varname", varname),
                ("rule_folder", rule.folder.path()),
                ("rule_id", rule.id),
                ("host", self._hostname),
                (
                    "item",
                    mk_repr(svc_desc_or_item).decode()
                    if svc_desc_or_item else "",
                ),
                ("service", mk_repr(svc_desc).decode() if svc_desc else ""),
            ])

        varname = rulespec.name
        valuespec = rulespec.valuespec

        url = folder_preserving_link([
            ("mode", "edit_ruleset"),
            ("varname", varname),
            ("host", self._hostname),
            ("item", mk_repr(svc_desc_or_item).decode()),
            ("service", mk_repr(svc_desc).decode()),
        ])

        forms.section(HTMLWriter.render_a(rulespec.title, url))

        ruleset = all_rulesets.get(varname)
        setting, rules = ruleset.analyse_ruleset(self._hostname,
                                                 svc_desc_or_item, svc_desc)

        html.open_table(class_="setting")
        html.open_tr()
        html.open_td(class_="reason")

        # Show reason for the determined value
        if len(rules) == 1:
            rule_folder, rule_index, rule = rules[0]
            url = rule_url(rule)
            html.a(_("Rule %d in %s") % (rule_index + 1, rule_folder.title()),
                   href=rule_url(rule))

        elif len(rules) > 1:
            html.a("%d %s" % (len(rules), _("Rules")), href=url)

        else:
            html.span(_("Default value"))
        html.close_td()

        # Show the resulting value or factory setting
        html.open_td(
            class_=["settingvalue", "used" if len(rules) > 0 else "unused"])

        if isinstance(known_settings,
                      dict) and "tp_computed_params" in known_settings:
            computed_at = known_settings["tp_computed_params"]["computed_at"]
            html.write_text(
                _("Timespecific parameters computed at %s") %
                cmk.utils.render.date_and_time(computed_at))
            html.br()
            known_settings = known_settings["tp_computed_params"]["params"]

        # In some cases we now the settings from a check_mk automation
        if known_settings is self._PARAMETERS_OMIT:
            return

        # Special handling for logwatch: The check parameter is always None. The actual
        # patterns are configured in logwatch_rules. We do not have access to the actual
        # patterns here but just to the useless "None". In order not to complicate things
        # we simply display nothing here.
        if varname == "logwatch_rules":
            pass

        elif known_settings is not self._PARAMETERS_UNKNOWN:
            try:
                html.write_text(valuespec.value_to_html(known_settings))
            except Exception as e:
                if active_config.debug:
                    raise
                html.write_text(
                    _("Invalid parameter %r: %s") % (known_settings, e))

        else:
            # For match type "dict" it can be the case the rule define some of the keys
            # while other keys are taken from the factory defaults. We need to show the
            # complete outcoming value here.
            if rules and ruleset.match_type() == "dict":
                if (rulespec.factory_default is not Rulespec.NO_FACTORY_DEFAULT
                        and rulespec.factory_default
                        is not Rulespec.FACTORY_DEFAULT_UNUSED):
                    fd = rulespec.factory_default.copy()
                    fd.update(setting)
                    setting = fd

            if valuespec and not rules:  # show the default value
                if rulespec.factory_default is Rulespec.FACTORY_DEFAULT_UNUSED:
                    # Some rulesets are ineffective if they are empty
                    html.write_text(_("(unused)"))

                elif rulespec.factory_default is not Rulespec.NO_FACTORY_DEFAULT:
                    # If there is a factory default then show that one
                    setting = rulespec.factory_default
                    html.write_text(valuespec.value_to_html(setting))

                elif ruleset.match_type() in ("all", "list"):
                    # Rulesets that build lists are empty if no rule matches
                    html.write_text(_("(no entry)"))

                else:
                    # Else we use the default value of the valuespec
                    html.write_text(
                        valuespec.value_to_html(valuespec.default_value()))

            # We have a setting
            elif valuespec:
                if ruleset.match_type() == "all":
                    for s in setting:
                        html.write_text(valuespec.value_to_html(s))
                else:
                    html.write_text(valuespec.value_to_html(setting))

            # Binary rule, no valuespec, outcome is True or False
            else:
                icon_name = "rule_%s%s" % ("yes" if setting else "no",
                                           "_off" if not rules else "")
                html.icon(icon_name, title=_("yes") if setting else _("no"))
        html.close_td()
        html.close_tr()
        html.close_table()
예제 #23
0
    def _show_rows(self):
        rows = self._get_rows()

        if bool([r for r in rows if r.stats is None]):
            html.center(_("No data from any site"))
            return

        html.open_table(class_=["tacticaloverview"], cellspacing="2", cellpadding="0", border="0")

        show_stales = self.parameters()["show_stale"] and user.may(
            "general.see_stales_in_tactical_overview"
        )
        has_stale_objects = bool([r for r in rows if r.what != "events" and r.stats[-1]])

        for row in rows:
            if row.what == "events":
                amount, problems, unhandled_problems = row.stats
                stales = 0

                # no events open and disabled in local site: don't show events
                if amount == 0 and not active_config.mkeventd_enabled:
                    continue
            else:
                amount, problems, unhandled_problems, stales = row.stats

            context_vars = get_context_url_variables(row.context)

            html.open_tr()
            html.th(row.title)
            html.th(_("Problems"), class_="show_more_mode")
            html.th(
                HTMLWriter.render_span(_("Unhandled"), class_="more")
                + HTMLWriter.render_span(_("Unhandled p."), class_="less")
            )
            if show_stales and has_stale_objects:
                html.th(_("Stale"))
            html.close_tr()

            td_class = "col4" if has_stale_objects else "col3"

            html.open_tr()
            url = makeuri_contextless(request, row.views.total + context_vars, filename="view.py")
            html.open_td(class_=["total", td_class])
            html.a("%s" % amount, href=url, target="main")
            html.close_td()

            for value, ty in [(problems, "handled"), (unhandled_problems, "unhandled")]:
                url = makeuri_contextless(
                    request,
                    getattr(row.views, ty) + context_vars,
                    filename="view.py",
                )
                html.open_td(
                    class_=[td_class]
                    + ([] if value == 0 else ["states prob"])
                    + ["show_more_mode" if ty == "handled" else "basic"]
                )
                link(str(value), url)
                html.close_td()

            if show_stales and has_stale_objects:
                if row.views.stale:
                    url = makeuri_contextless(
                        request,
                        row.views.stale + context_vars,
                        filename="view.py",
                    )
                    html.open_td(class_=[td_class] + ([] if stales == 0 else ["states prob"]))
                    link(str(stales), url)
                    html.close_td()
                else:
                    html.td(HTMLWriter.render_span("0"))

            html.close_tr()
        html.close_table()
예제 #24
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(
            HTMLWriter.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")
예제 #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()