Ejemplo n.º 1
0
def render_graph_container_html(graph_recipe, graph_data_range,
                                graph_render_options):
    graph_render_options = artwork.add_default_render_options(
        graph_render_options)

    # Estimate size of graph. This will not be the exact size of the graph, because
    # this does calculate the size of the canvas area and does not take e.g. the legend
    # into account. We would need the graph_artwork to calculate that, but this is something
    # we don't have in this early stage.
    size = graph_render_options["size"]
    graph_width = size[0] * html_size_per_ex
    graph_height = size[1] * html_size_per_ex

    content = html.render_div("", class_="title") \
            + html.render_div("",
                class_="content",
                style="width:%dpx;height:%dpx" % (graph_width, graph_height))

    output = html.render_div(html.render_div(content, class_=["graph", "loading_graph"]),
                             class_="graph_load_container") \

    output += html.render_javascript(
        "cmk.graphs.load_graph_content(%s, %s, %s)" % (
            json.dumps(graph_recipe),
            json.dumps(graph_data_range),
            json.dumps(graph_render_options),
        ))

    if "cmk.graphs.register_delayed_graph_listener" not in html.final_javascript_code:
        html.final_javascript("cmk.graphs.register_delayed_graph_listener()")

    return output
Ejemplo n.º 2
0
    def render(self, row, cell):
        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 config.debug:
                raise
            return " ".join(classes), _("Exception: %s") % e

        content = html.render_div(HTML(h), class_=["content"]) \
                + html.render_div(title, class_=["title"]) \
                + html.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), \
            html.render_a(content=content, href=url, title=escaping.strip_tags(title),
                          class_=["disabled" if disabled else None])
Ejemplo n.º 3
0
def render_color_icon(color: str) -> HTML:
    return html.render_div(
        '',
        class_="color",
        # NOTE: When we drop support for IE11 we can use #%s4c instead of rgba(...)
        style="background-color: rgba(%d, %d, %d, 0.3); border-color: %s;" %
        (*hex_color_to_rgb_color(color), color))
Ejemplo n.º 4
0
    def _show_main_menu_content(self) -> None:
        for menu_item in self._get_main_menu_items():
            if isinstance(menu_item.icon, dict):
                active_icon: Icon = {
                    "icon": menu_item.icon["icon"] + "_active",
                    "emblem": menu_item.icon["emblem"]
                }
            else:
                active_icon = menu_item.icon + "_active"

            html.open_li()
            html.popup_trigger(
                (html.render_icon(menu_item.icon) +
                 html.render_icon(active_icon, class_="active") +
                 html.render_div(menu_item.title)),
                ident="mega_menu_" + menu_item.name,
                method=MethodInline(self._get_mega_menu_content(menu_item)),
                cssclass=menu_item.name,
                popup_group="main_menu_popup",
                hover_switch_delay=150,  # ms
                onopen=menu_item.onopen,
            )
            html.div("",
                     id_="popup_shadow",
                     onclick="cmk.popup_menu.close_popup()")
            html.close_li()
Ejemplo n.º 5
0
def _render_tag_group(tg_id, tag, object_type, with_link, label_type,
                      label_source):
    span = html.render_tag(html.render_div(
        html.render_span("%s:%s" % (tg_id, tag), class_=["tagify__tag-text"])),
                           class_=["tagify--noAnim", label_source])
    if not with_link:
        return span

    if label_type == "tag_group":
        type_filter_vars = [
            ("%s_tag_0_grp" % object_type, tg_id),
            ("%s_tag_0_op" % object_type, "is"),
            ("%s_tag_0_val" % object_type, tag),
        ]
    elif label_type == "label":
        type_filter_vars = [
            ("%s_label" % object_type,
             json.dumps([{
                 "value": "%s:%s" % (tg_id, tag)
             }]).decode("utf-8")),
        ]

    else:
        raise NotImplementedError()

    url = html.makeuri_contextless([
        ("filled_in", "filter"),
        ("search", "Search"),
        ("view_name", "searchhost" if object_type == "host" else "searchsvc"),
    ] + type_filter_vars,
                                   filename="view.py")
    return html.render_a(span, href=url)
Ejemplo n.º 6
0
    def _get_popup_trigger_content(self, active_icon: Icon, menu_item: MainMenuItem) -> HTML:
        content = html.render_icon(menu_item.icon) + html.render_icon(active_icon, class_="active")

        if not user.get_attribute("nav_hide_icons_title"):
            content += html.render_div(menu_item.title)

        return content
Ejemplo n.º 7
0
def render_html_graph_title(graph_artwork, graph_render_options):
    title = render_title_elements(_render_graph_title_elements(graph_artwork, graph_render_options))
    if title:
        return html.render_div(
            title,
            class_=["title", "inline" if graph_render_options["show_title"] == "inline" else None])
    return ""
Ejemplo n.º 8
0
def render_graph_error_html(msg_or_exc, title=None):
    if isinstance(msg_or_exc, MKGeneralException) and not config.debug:
        msg = "%s" % msg_or_exc

    elif isinstance(msg_or_exc, Exception):
        if config.debug:
            raise msg_or_exc
        msg = traceback.format_exc()
    else:
        msg = msg_or_exc

    if title is None:
        title = _("Cannot display graph")

    return html.render_div(html.render_div(title, class_="title") + html.render_pre(msg),
                           class_=["graph", "brokengraph"])
Ejemplo n.º 9
0
def _render_tag_group(tg_id: Union[TagID, str], tag: Union[TagValue, str],
                      object_type: str, with_link: bool, label_type: str,
                      label_source: str) -> HTML:
    span = html.render_tag(html.render_div(
        html.render_span("%s:%s" % (tg_id, tag), 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, tg_id),
            ("%s_tag_0_op" % object_type, "is"),
            ("%s_tag_0_val" % object_type, tag),
        ]
    elif label_type == "label":
        type_filter_vars = [
            ("%s_label" % object_type,
             json.dumps([{
                 "value": "%s:%s" % (tg_id, tag)
             }])),
        ]

    else:
        raise NotImplementedError()

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

    url = html.makeuri_contextless(url_vars + type_filter_vars,
                                   filename="view.py")
    return html.render_a(span, href=url)
Ejemplo n.º 10
0
def render_graph_content_html(graph_recipe, graph_data_range,
                              graph_render_options) -> HTML:
    output = HTML()
    try:
        graph_artwork = artwork.compute_graph_artwork(graph_recipe,
                                                      graph_data_range,
                                                      graph_render_options)
        main_graph_html = render_graph_or_error_html(graph_artwork,
                                                     graph_data_range,
                                                     graph_render_options)

        previews = graph_render_options["show_time_range_previews"]
        if graph_recipe['specification'][0] == 'forecast':
            previews = False

        if previews:
            output += html.render_div(
                main_graph_html + render_time_range_selection(
                    graph_recipe, graph_render_options),
                class_="graph_with_timeranges",
            )
        else:
            output += main_graph_html

    except livestatus.MKLivestatusNotFoundError:
        output += render_graph_error_html(
            _("Cannot fetch data via Livestatus"), _("Cannot create graph"))

    except Exception as e:
        output += render_graph_error_html(e, _("Cannot create graph"))
    return output
Ejemplo n.º 11
0
def render_metricometer(stack):
    if len(stack) not in (1, 2):
        raise MKGeneralException(
            _("Invalid Perf-O-Meter definition %r: only one or two entries are allowed") % stack)
    h = HTML().join(map(render_perfometer, stack))
    if len(stack) == 2:
        h = html.render_div(h, class_="stacked")
    return h
 def _create_tooltip(cls, timestamp, host_to_value_dict, additional_rows=None):
     table_rows = sorted(host_to_value_dict.items(), key=lambda item: item[1]) + additional_rows
     table_html = ""
     # TODO: cleanup str casting
     for a, b in table_rows:
         table_html += str(html.render_tr(html.render_td(a) + html.render_td(b)))
     table_html = str(html.render_table(table_html))
     tooltip = html.render_div(date_and_time(timestamp)) + table_html
     return tooltip
Ejemplo n.º 13
0
 def _tag_tree_bullet(self, state, path, leaf) -> HTML:
     code = html.render_div(
         " ",
         class_=["tagtree", "leafstatebullet" if leaf else "statebullet",
                 "state%d" % state])
     if not leaf:
         code += html.render_a(code,
                               href="javascript:virtual_host_tree_enter('%s');" % "|".join(path),
                               title=_("Display the tree only below this node"))
     return code + " "
Ejemplo n.º 14
0
    def _show_main_menu_content(self) -> None:
        html.open_li()
        html.popup_trigger(
            html.render_icon("main_search") + html.render_div(_("Search")),
            "mega_menu_search",
            method=MethodInline(self._get_search_menu_content()),
        )
        html.close_li()

        for menu_item in self._get_main_menu_items():
            html.open_li()
            html.popup_trigger(
                html.render_icon(menu_item.icon_name) +
                html.render_div(menu_item.title),
                ident="mega_menu_" + menu_item.name,
                method=MethodInline(self._get_mega_menu_content(menu_item)),
                cssclass=menu_item.name,
            )
            html.close_li()
Ejemplo n.º 15
0
def render_html_graph_title(graph_artwork, graph_render_options):
    title = HTML(" / ").join([
        (html.render_a(txt, href=url) if url else txt)
        for txt, url in _render_graph_title_elements(graph_artwork, graph_render_options)
    ])
    if title:
        return html.render_div(
            title,
            class_=["title", "inline" if graph_render_options["show_title"] == "inline" else None])
    return ""
Ejemplo n.º 16
0
def render_html_graph_title(graph_artwork, graph_render_options):
    title = text_with_links_to_user_translated_html(
        _render_graph_title_elements(graph_artwork, graph_render_options),
        separator=" / ",
    )
    if title:
        return html.render_div(
            title,
            class_=[
                "title", "inline"
                if graph_render_options["show_title"] == "inline" else None
            ])
    return ""
Ejemplo n.º 17
0
def render_graph_html_content(graph_artwork, graph_data_range,
                              graph_render_options):
    graph_render_options = artwork.add_default_render_options(
        graph_render_options)

    css = " preview" if graph_render_options["preview"] else ""
    output: RenderOutput = '<div class="graph%s" style="font-size: %.1fpt;%s">' % (
        css, graph_render_options["font_size"],
        _graph_padding_styles(graph_render_options))

    if graph_render_options["show_controls"]:
        output += render_graph_add_to_icon_for_popup(graph_artwork,
                                                     graph_data_range,
                                                     graph_render_options)

    v_axis_label = graph_artwork["vertical_axis"]["axis_label"]
    if v_axis_label:
        output += '<div class=v_axis_label>%s</div>' % v_axis_label

    # Add the floating elements
    if graph_render_options[
            "show_graph_time"] and not graph_render_options["preview"]:
        output += html.render_div(
            graph_artwork["time_axis"]["title"] or "",
            css=[
                "time", "inline"
                if graph_render_options["show_title"] == "inline" else None
            ])

    if graph_render_options["show_controls"] and graph_render_options[
            "resizable"]:
        output += '<img class=resize src="%s">' % html.theme_url(
            "images/resize_graph.png")

    output += render_html_graph_title(graph_artwork, graph_render_options)
    output += render_graph_canvas(graph_render_options)

    # Note: due to "omit_zero_metrics" the graph might not have any curves
    if show_graph_legend(graph_render_options, graph_artwork):
        output += render_graph_legend(graph_artwork, graph_render_options)

    model_params_repr = graph_artwork["definition"].get("model_params_repr")
    model_params_display = graph_artwork["definition"].get(
        'model_params', {}).get("display_model_parametrization")
    if model_params_repr and model_params_display:
        output += "<div align='center'><h2>Forecast Parametrization</h2>%s</div>" % model_params_repr

    output += '</div>'
    return output
Ejemplo n.º 18
0
 def _show_main_menu_content(self) -> None:
     for menu_item in self._get_main_menu_items():
         html.open_li()
         html.popup_trigger(
             (html.render_icon(menu_item.icon_name) + html.render_icon(
                 menu_item.icon_name + "_active", class_="active") +
              html.render_div(menu_item.title)),
             ident="mega_menu_" + menu_item.name,
             method=MethodInline(self._get_mega_menu_content(menu_item)),
             cssclass=menu_item.name,
             popup_group="main_menu_popup",
             hover_switch_delay=150,  # ms
             onopen=menu_item.onopen,
         )
         html.close_li()
Ejemplo n.º 19
0
def render_color_icon(color):
    return html.render_div('', class_="color", style="background-color: %s" % color)
Ejemplo n.º 20
0
def test_exception_handling(request_context):
    try:
        raise Exception("Test")
    except Exception as e:
        assert compare_html(html.render_div(str(e)), "<div>%s</div>" % e)
Ejemplo n.º 21
0
def render_color_icon(color):
    return html.render_div('',
                           class_="color",
                           style="background-color: %s4c; border-color: %s;" %
                           (color, color))
Ejemplo n.º 22
0
def test_exception_handling(register_builtin_html):
    try:
        raise Exception("Test")
    except Exception as e:
        assert compare_html(html.render_div(str(e)), "<div>%s</div>" % e)