Example #1
0
    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()
Example #2
0
def query_limit_exceeded_warn(limit: Optional[int], user_config: LoggedInUser) -> None:
    """Compare query reply against limits, warn in the GUI about incompleteness"""
    text = HTML(_("Your query produced more than %d results. ") % limit)

    if request.get_ascii_input("limit", "soft") == "soft" and user_config.may(
        "general.ignore_soft_limit"
    ):
        text += HTMLWriter.render_a(
            _("Repeat query and allow more results."),
            target="_self",
            href=makeuri(request, [("limit", "hard")]),
        )
    elif request.get_ascii_input("limit") == "hard" and user_config.may(
        "general.ignore_hard_limit"
    ):
        text += HTMLWriter.render_a(
            _("Repeat query without limit."),
            target="_self",
            href=makeuri(request, [("limit", "none")]),
        )

    text += escaping.escape_to_html_permissive(
        " " + _("<b>Note:</b> the shown results are incomplete and do not reflect the sort order.")
    )
    html.show_warning(text)
Example #3
0
def test_render_a(request_context):
    a = HTMLWriter.render_a("bla", href="blu", class_=["eee"], target="_blank")
    assert compare_html(a, '<a href="blu" target="_blank" class="eee">bla</a>')

    a = HTMLWriter.render_a(
        "b<script>alert(1)</script>la",
        href="b<script>alert(1)</script>lu",
        class_=["eee"],
        target="_blank",
    )
    assert compare_html(
        a,
        '<a href="b&lt;script&gt;alert(1)&lt;/script&gt;lu" target="_blank" '
        'class="eee">b&lt;script&gt;alert(1)&lt;/script&gt;la</a>',
    )
Example #4
0
 def paint(self, value, hostname):
     value = convert_cgroups_from_tuple(value)
     texts: List[HTML] = []
     self.load_data()
     if self._contactgroups is None:  # conditional caused by horrible API
         raise Exception("invalid contact groups")
     items = self._contactgroups.items()
     for name, cgroup in sorted(items, key=lambda x: x[1]["alias"]):
         if name in value["groups"]:
             display_name = cgroup.get("alias", name)
             texts.append(
                 HTMLWriter.render_a(
                     display_name,
                     href=makeuri_contextless(
                         request,
                         [("mode", "edit_contact_group"), ("edit", name)],
                         filename="wato.py",
                     ),
                 ))
     result: HTML = HTML(", ").join(texts)
     if texts and value["use"]:
         result += HTMLWriter.render_span(
             HTMLWriter.render_b("*"),
             title=
             _("These contact groups are also used in the monitoring configuration."
               ),
         )
     return "", result
Example #5
0
def render_object_ref_as_icon(
        object_ref: Optional[ObjectRef]) -> Optional[HTML]:
    if object_ref is None:
        return None

    url, title = _get_object_reference(object_ref)
    if not url:
        return None

    icons = {
        ObjectRefType.Host: "host",
        ObjectRefType.Folder: "folder",
        ObjectRefType.User: "******",
        ObjectRefType.Rule: "rule",
        ObjectRefType.Ruleset: "rulesets",
    }

    return HTMLWriter.render_a(
        content=html.render_icon(
            icons.get(object_ref.object_type, "link"),
            title="%s: %s" %
            (object_ref.object_type.name, title) if title else None,
        ),
        href=url,
    )
Example #6
0
def render_tree_folder(tree_id, folder, js_func):
    subfolders = folder.get(".folders", {}).values()
    is_leaf = len(subfolders) == 0

    # Suppress indentation for non-emtpy root folder
    if folder[".path"] == "" and is_leaf:
        html.open_ul()  # empty root folder
    elif folder and folder[".path"] != "":
        html.open_ul(style="padding-left:0px;")

    title = HTMLWriter.render_a(
        "%s (%d)" % (folder["title"], folder[".num_hosts"]),
        href="#",
        class_="link",
        onclick="%s(this, '%s');" % (js_func, folder[".path"]),
    )

    if not is_leaf:
        with foldable_container(
            treename=tree_id,
            id_="/" + folder[".path"],
            isopen=False,
            title=HTML(title),
            icon="foldable_sidebar",
            padding=6,
        ):
            for subfolder in sorted(subfolders, key=lambda x: x["title"].lower()):
                render_tree_folder(tree_id, subfolder, js_func)
    else:
        html.li(title)

    html.close_ul()
Example #7
0
def _render_manpage_list(titles, manpage_list, path_comp, heading):
    def translate(t):
        return titles.get(t, t)

    html.h3(heading)
    with table_element(searchable=False, sortable=False,
                       css="check_catalog") as table:
        for entry in sorted(manpage_list, key=lambda x: x["title"]):
            if not isinstance(entry, dict):
                continue
            table.row()
            url = makeuri(
                request,
                [
                    ("mode", "check_manpage"),
                    ("check_type", entry["name"]),
                    ("back", makeuri(request, [])),
                ],
            )
            table.cell(_("Type of Check"),
                       HTMLWriter.render_a(entry["title"], href=url),
                       css=["title"])
            table.cell(_("Plugin Name"),
                       HTMLWriter.render_tt(entry["name"]),
                       css=["name"])
            table.cell(_("Agents"),
                       ", ".join(map(translate, sorted(entry["agents"]))),
                       css=["agents"])
Example #8
0
def show_log_list():
    title = _("All problematic logfiles")
    breadcrumb = make_simple_page_breadcrumb(
        mega_menu_registry.menu_monitoring(), title)
    make_header(html, title, breadcrumb, _log_list_page_menu(breadcrumb))

    if request.has_var("_ack") and not request.var("_do_actions") == _("No"):
        do_log_ack(site=None, host_name=None, file_name=None)
        return

    for site, host_name, logs in all_logs():
        if not logs:
            continue

        all_logs_empty = not any(
            parse_file(site, host_name, file_name) for file_name in logs)

        if all_logs_empty:
            continue  # Logfile vanished

        html.h3(
            HTMLWriter.render_a(
                host_name,
                href=makeuri(
                    request,
                    [("site", site), ("host", host_name)],
                ),
            ),
            class_="table",
        )
        list_logs(site, host_name, logs)
    html.footer()
Example #9
0
def list_logs(site, host_name, logfile_names):
    with table_element(empty_text=_("No logs found for this host.")) as table:

        for file_name in logfile_names:
            table.row()
            file_display = form_file_to_ext(file_name)
            uri = makeuri(request, [("site", site), ("host", host_name),
                                    ("file", file_display)])
            logfile_link = HTMLWriter.render_a(file_display, href=uri)

            try:
                log_chunks = parse_file(site, host_name, file_name)
                if not log_chunks:
                    continue  # Logfile vanished

                worst_log = get_worst_chunk(log_chunks)
                last_log = get_last_chunk(log_chunks)
                state = worst_log["level"]
                state_name = form_level(state)

                table.cell(_("Level"), state_name, css=["state%d" % state])
                table.cell(_("Logfile"), logfile_link)
                table.cell(_("Last Entry"),
                           form_datetime(last_log["datetime"]))
                table.cell(_("Entries"), len(log_chunks), css=["number"])

            except Exception:
                if active_config.debug:
                    raise
                table.cell(_("Level"), "")
                table.cell(_("Logfile"), logfile_link)
                table.cell(_("Last Entry"), "")
                table.cell(_("Entries"), _("Corrupted"))
Example #10
0
    def _render_tree(self, tree):
        for group, attrs in tree.items():
            aggr_group_tree = "/".join(attrs["__path__"])
            fetch_url = makeuri_contextless(
                request,
                [
                    ("view_name", "aggr_all"),
                    ("aggr_group_tree", aggr_group_tree),
                ],
                filename="view.py",
            )

            if attrs.get("__children__"):
                with foldable_container(
                        treename="bi_aggregation_group_trees",
                        id_=aggr_group_tree,
                        isopen=False,
                        title=HTML(
                            HTMLWriter.render_a(
                                group,
                                href=fetch_url,
                                target="main",
                            )),
                        icon="foldable_sidebar",
                ):
                    self._render_tree(attrs["__children__"])
            else:
                html.open_ul()
                bulletlink(group, fetch_url)
                html.close_ul()
Example #11
0
    def render(self, row: Row, cell: Cell) -> CellSpec:
        classes = ["perfometer"]
        if is_stale(row):
            classes.append("stale")

        try:
            title, h = Perfometer(row).render()
            if title is None and h is None:
                return "", ""
        except Exception as e:
            logger.exception("error rendering performeter")
            if active_config.debug:
                raise
            return " ".join(classes), _("Exception: %s") % e

        assert h is not None
        content = (HTMLWriter.render_div(HTML(h), class_=["content"]) +
                   HTMLWriter.render_div(title, class_=["title"]) +
                   HTMLWriter.render_div("", class_=["glass"]))

        # pnpgraph_present: -1 means unknown (path not configured), 0: no, 1: yes
        if display_options.enabled(
                display_options.X) and row["service_pnpgraph_present"] != 0:
            url = cmk_graph_url(row, "service")
            disabled = False
        else:
            url = "javascript:void(0)"
            disabled = True

        return " ".join(classes), HTMLWriter.render_a(
            content=content,
            href=url,
            title=escaping.strip_tags(title),
            class_=["disabled"] if disabled else [],
        )
Example #12
0
def render_object_ref(
        object_ref: Optional[ObjectRef]) -> Union[str, HTML, None]:
    url, title = _get_object_reference(object_ref)
    if title and not url:
        return title
    if not title:
        return None
    return HTMLWriter.render_a(title, href=url)
Example #13
0
 def paint(self, value, hostname):
     parts = [
         HTMLWriter.render_a(
             hn, "wato.py?" + urlencode_vars([("mode", "edit_host"),
                                              ("host", hn)]))
         for hn in value
     ]
     return "", HTML(", ").join(parts)
Example #14
0
def text_with_links_to_user_translated_html(
    elements: Iterable[Tuple[str, Optional[str]]],
    separator: str = "",
) -> HTML:
    return HTML(separator).join(
        HTMLWriter.render_a(user_translation, href=url, title=user_translation
                            ) if url else escape_to_html_permissive(
                                user_translation, escape_links=False)
        for txt, url in elements for user_translation in [_u(txt)] if txt)
Example #15
0
 def render(self, row, cell):
     url = makeuri_contextless(
         request,
         [
             ("crash_id", row["crash_id"]),
             ("site", row["site"]),
         ],
         filename="crash.py",
     )
     return (None, HTMLWriter.render_a(row["crash_id"], href=url))
Example #16
0
    def _render_rule_reason(self, title, title_url, reason, reason_url,
                            is_default, setting: Union[str, HTML]) -> None:
        if title_url:
            title = HTMLWriter.render_a(title, href=title_url)
        forms.section(title)

        if reason:
            reason = HTMLWriter.render_a(reason, href=reason_url)

        html.open_table(class_="setting")
        html.open_tr()
        if is_default:
            html.td(HTMLWriter.render_i(reason), class_="reason")
            html.td(setting, class_=["settingvalue", "unused"])
        else:
            html.td(reason, class_="reason")
            html.td(setting, class_=["settingvalue", "used"])
        html.close_tr()
        html.close_table()
Example #17
0
 def _show_row_cells(self, table: Table, name: GroupName,
                     group: GroupSpec) -> None:
     super()._show_row_cells(table, name, group)
     table.cell(_("Members"))
     html.write_html(
         HTML(", ").join([
             HTMLWriter.render_a(
                 alias,
                 href=folder_preserving_link([("mode", "edit_user"),
                                              ("edit", userid)]),
             ) for userid, alias in self._members.get(name, [])
         ]))
Example #18
0
def test_HTMLWriter(request_context):
    with output_funnel.plugged():

        with output_funnel.plugged():
            html.open_div()
            text = output_funnel.drain()
            assert text.rstrip("\n").rstrip(" ") == "<div>"

        with output_funnel.plugged():
            # html.open_div().write("test").close_div()
            html.open_div()
            html.write_text("test")
            html.close_div()
            assert compare_html(output_funnel.drain(), "<div>test</div>")

        with output_funnel.plugged():
            # html.open_table().open_tr().td("1").td("2").close_tr().close_table()
            html.open_table()
            html.open_tr()
            html.td("1")
            html.td("2")
            html.close_tr()
            html.close_table()
            assert compare_html(
                output_funnel.drain(),
                "<table><tr><td>1</td><td>2</td></tr></table>")

        with output_funnel.plugged():
            html.div("test", **{"</div>malicious_code<div>": "trends"})
            assert compare_html(
                output_funnel.drain(),
                "<div &lt;/div&gt;malicious_code&lt;div&gt;=trends>test</div>",
            )

        a = "\u2665"
        with output_funnel.plugged():
            assert HTMLWriter.render_a("test", href="www.test.case")
            HTMLWriter.render_a("test", href="www.test.case")
            HTMLWriter.render_a("test", href="www.test.case")
            HTMLWriter.render_a("test", href="www.test.case")
            try:
                assert HTMLWriter.render_a(
                    "test",
                    href=str("www.test.case"),
                    id_=str("something"),
                    class_=str("test_%s") % a,
                )
            except Exception as e:
                traceback.print_exc()
                print(e)
Example #19
0
    def page(self):
        with table_element("roles") as table:

            users = userdb.load_users()
            for rid, role in sorted(self._roles.items(), key=lambda a: (a[1]["alias"], a[0])):
                table.row()

                # Actions
                table.cell(_("Actions"), css=["buttons"])
                edit_url = folder_preserving_link([("mode", "edit_role"), ("edit", rid)])
                clone_url = make_action_link([("mode", "roles"), ("_clone", rid)])
                delete_url = make_confirm_link(
                    url=make_action_link([("mode", "roles"), ("_delete", rid)]),
                    message=_("Do you really want to delete the role %s?") % rid,
                )
                html.icon_button(edit_url, _("Properties"), "edit")
                html.icon_button(clone_url, _("Clone"), "clone")
                if not role.get("builtin"):
                    html.icon_button(delete_url, _("Delete this role"), "delete")

                # ID
                table.cell(_("Name"), rid)

                # Alias
                table.cell(_("Alias"), role["alias"])

                # Type
                table.cell(_("Type"), _("builtin") if role.get("builtin") else _("custom"))

                # Modifications
                table.cell(
                    _("Modifications"),
                    HTMLWriter.render_span(
                        str(len(role["permissions"])),
                        title=_("That many permissions do not use the factory defaults."),
                    ),
                )

                # Users
                table.cell(
                    _("Users"),
                    HTML(", ").join(
                        [
                            HTMLWriter.render_a(
                                user.get("alias", user_id),
                                folder_preserving_link([("mode", "edit_user"), ("edit", user_id)]),
                            )
                            for (user_id, user) in users.items()
                            if rid in user["roles"]
                        ]
                    ),
                )
Example #20
0
def _render_tag_group(
    tag_group_id_or_label_key: Union[TaggroupID, str],
    tag_id_or_label_value: Union[TagID, str],
    object_type: str,
    with_link: bool,
    label_type: str,
    label_source: str,
) -> HTML:
    span = HTMLWriter.render_tag(
        HTMLWriter.render_div(
            HTMLWriter.render_span(
                "%s:%s"
                % (
                    tag_group_id_or_label_key,
                    tag_id_or_label_value,
                ),
                class_=["tagify__tag-text"],
            )
        ),
        class_=["tagify--noAnim", label_source],
    )
    if not with_link:
        return span

    if label_type == "tag_group":
        type_filter_vars: HTTPVariables = [
            ("%s_tag_0_grp" % object_type, tag_group_id_or_label_key),
            ("%s_tag_0_op" % object_type, "is"),
            ("%s_tag_0_val" % object_type, tag_id_or_label_value),
        ]
    elif label_type == "label":
        type_filter_vars = [
            (
                "%s_label" % object_type,
                json.dumps(
                    [{"value": "%s:%s" % (tag_group_id_or_label_key, tag_id_or_label_value)}]
                ),
            ),
        ]

    else:
        raise NotImplementedError()

    url_vars: HTTPVariables = [
        ("filled_in", "filter"),
        ("search", "Search"),
        ("view_name", "searchhost" if object_type == "host" else "searchsvc"),
    ]

    url = makeuri_contextless(request, url_vars + type_filter_vars, filename="view.py")
    return HTMLWriter.render_a(span, href=url)
Example #21
0
 def _tag_tree_bullet(self, state, path, leaf) -> HTML:
     code = HTMLWriter.render_div(
         "&nbsp;",
         class_=["tagtree"] + (["leaf"] if leaf else []) +
         ["statebullet", "state%d" % state],
     )
     if not leaf:
         code = HTMLWriter.render_a(
             code,
             href="javascript:virtual_host_tree_enter('%s');" %
             "|".join(path),
             title=_("Display the tree only below this node"),
         )
     return code + " "
Example #22
0
def get_host_list_links(site: SiteId, hosts: List[Union[str]]) -> List[str]:
    entries = []
    for host in hosts:
        args: HTTPVariables = [
            ("view_name", "hoststatus"),
            ("site", site),
            ("host", host),
        ]

        if request.var("display_options"):
            args.append(("display_options", request.var("display_options")))

        url = makeuri_contextless(request, args, filename="view.py")
        link = str(HTMLWriter.render_a(host, href=url))
        entries.append(link)
    return entries
Example #23
0
def insert_manpage_links(text: str) -> HTML:
    parts = text.replace(",", " ").split()
    new_parts: List[HTML] = []
    check_regex = re.compile(r"[-_\.a-z0-9]")
    for part in parts:
        if check_regex.match(part) and os.path.exists(
                cmk.utils.paths.check_manpages_dir + "/" + part):
            url = makeuri_contextless(
                request,
                [
                    ("mode", "check_manpage"),
                    ("check_type", part),
                ],
                filename="wato.py",
            )
            new_parts.append(HTMLWriter.render_a(content=part, href=url))
        else:
            new_parts.append(escape_to_html(part))
    return HTML(" ").join(new_parts)
Example #24
0
def render_link(text: Union[str, HTML],
                url: str,
                target: str = "main",
                onclick: Optional[str] = None) -> HTML:
    # Convert relative links into absolute links. We have three kinds
    # of possible links and we change only [3]
    # [1] protocol://hostname/url/link.py
    # [2] /absolute/link.py
    # [3] relative.py
    if not (":" in url[:10]
            ) and not url.startswith("javascript") and url[0] != "/":
        url = url_prefix() + "check_mk/" + url
    return HTMLWriter.render_a(
        text,
        href=url,
        class_="link",
        target=target or "",
        onfocus="if (this.blur) this.blur();",
        onclick=onclick or None,
    )
Example #25
0
def paint_aggr_hosts(row, link_to_view):
    h = []
    for site, host in row["aggr_hosts"]:
        url = makeuri(request, [("view_name", link_to_view), ("site", site), ("host", host)])
        h.append(HTMLWriter.render_a(host, url))
    return "", HTML(" ").join(h)
Example #26
0
    def _render_tag_tree_level(self, tree_spec, path, cwd, title,
                               tree) -> None:
        if not self._is_tag_subdir(
                path=path, cwd=cwd) and not self._is_tag_subdir(path=cwd,
                                                                cwd=path):
            return

        container: ContextManager[bool] = nullcontext(False)
        if path != cwd and self._is_tag_subdir(path, cwd):
            bullet = self._tag_tree_bullet(self._tag_tree_worst_state(tree),
                                           path, False)
            if self._tag_tree_has_svc_problems(tree):
                bullet += html.render_icon_button(
                    self._tag_tree_url(tree_spec, path, "svcproblems"),
                    _("Show the service problems contained in this branch"),
                    "svc_problems",
                    target="main",
                )

            if path:
                container = foldable_container(
                    treename="tag-tree",
                    id_=".".join(map(str, path)),
                    isopen=False,
                    title=bullet + title,
                    icon="foldable_sidebar",
                )

        with container:
            for (node_title, node_value), subtree in sorted(
                    tree.get("_children", {}).items()):
                subpath = path + [node_value or ""]
                url = self._tag_tree_url(tree_spec, subpath, "allhosts")

                if "_num_hosts" in subtree:
                    node_title += " (%d)" % subtree["_num_hosts"]

                node_title = HTMLWriter.render_a(node_title,
                                                 href=url,
                                                 target="main")

                if "_children" not in subtree:
                    if self._is_tag_subdir(path, cwd):
                        html.write_html(
                            self._tag_tree_bullet(subtree.get("_state", 0),
                                                  subpath, True))
                        if subtree.get("_svc_problems"):
                            url = self._tag_tree_url(tree_spec, subpath,
                                                     "svcproblems")
                            html.icon_button(
                                url,
                                _("Show the service problems contained in this branch"
                                  ),
                                "svc_problems",
                                target="main",
                            )
                        html.write_html(node_title)
                        html.br()
                else:
                    self._render_tag_tree_level(tree_spec, subpath, cwd,
                                                node_title, subtree)
Example #27
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()
Example #28
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", {}))
Example #29
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()
Example #30
0
def render_werk_id(werk, with_link) -> Union[HTML, str]:
    if with_link:
        url = makeuri_contextless(request, [("werk", werk["id"])],
                                  filename="werk.py")
        return HTMLWriter.render_a("#%04d" % werk["id"], href=url)
    return "#%04d" % werk["id"]