Пример #1
0
def _process_notify_message(msg):
    msg['id'] = utils.gen_id()
    msg['time'] = time.time()

    if isinstance(msg['dest'], str):
        dest_what = msg['dest']
    else:
        dest_what = msg['dest'][0]

    if dest_what == 'broadcast':
        recipients = list(config.multisite_users.keys())
    elif dest_what == 'online':
        recipients = userdb.get_online_user_ids()
    elif dest_what == 'list':
        recipients = msg['dest'][1]
    else:
        recipients = []

    num_recipients = len(recipients)

    num_success = {}
    for method in msg['methods']:
        num_success[method] = 0

    # Now loop all notitification methods to send the notifications
    errors: Dict[str, List[Tuple]] = {}
    for user_id in recipients:
        for method in msg['methods']:
            try:
                handler = _notify_methods()[method]['handler']
                handler(user_id, msg)
                num_success[method] = num_success[method] + 1
            except MKInternalError as e:
                errors.setdefault(method, []).append((user_id, e))

    message = _('The notification has been sent via<br>')
    message += "<table>"
    for method in msg['methods']:
        message += "<tr><td>%s</td><td>to %d of %d recipients</td></tr>" %\
                        (_notify_methods()[method]["title"], num_success[method], num_recipients)
    message += "</table>"

    message += _('<p>Sent notification to: %s</p>') % ', '.join(recipients)
    message += '<a href="%s">%s</a>' % (html.makeuri(
        []), _('Back to previous page'))
    html.show_message(HTML(message))

    if errors:
        error_message = HTML()
        for method, method_errors in errors.items():
            error_message += _(
                "Failed to send %s notifications to the following users:"
            ) % method
            table_rows = HTML()
            for user, exception in method_errors:
                table_rows += html.render_tr(
                    html.render_td(html.render_tt(user)) +
                    html.render_td(exception))
            error_message += html.render_table(table_rows) + html.render_br()
        html.show_error(error_message)
 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
    def _forge_tooltip_and_url(self, time_frame, properties, context):
        mode_properties = properties["render_mode"][1]
        time_range = self._int_time_range_from_rangespec(
            mode_properties["time_range"])
        ending_timestamp = min(time_frame["ending_timestamp"], time_range[1])
        from_time_str = date_and_time(time_frame["timestamp"])
        to_time_str = date_and_time(ending_timestamp)
        # TODO: Can this be simplified by passing a list as argument to html.render_table()?
        tooltip = html.render_table(
            html.render_tr(
                html.render_td(_("From:")) + html.render_td(from_time_str)) +
            html.render_tr(
                html.render_td(_("To:")) + html.render_td(to_time_str)) +
            html.render_tr(
                html.render_td("%ss:" %
                               properties["log_target"].capitalize()) +
                html.render_td(time_frame["value"])))

        args: HTTPVariables = []
        # Generic filters
        args.append(("filled_in", "filter"))
        args.append(("_show_filter_form", "0"))
        args.append(("view_name", "events"))
        args.append(("logtime_from", str(time_frame["timestamp"])))
        args.append(("logtime_from_range", "unix"))
        args.append(("logtime_until", str(ending_timestamp)))
        args.append(("logtime_until_range", "unix"))
        args.append(("logclass%d" % self.log_class, "on"))

        # Only include "end user notitification entries. Exclude entries related to the internal
        # raw notification events.
        args.append(("is_log_notification_phase", "0"))

        if properties["log_target"] in ("host", "both"):
            #args.append(("logst_h0", "on"))
            args.append(("logst_h1", "on"))
            args.append(("logst_h2", "on"))

        if properties["log_target"] in ("service", "both"):
            #args.append(("logst_s0", "on"))
            args.append(("logst_s1", "on"))
            args.append(("logst_s2", "on"))
            args.append(("logst_s3", "on"))

        # Exclude e.g. "SERVICE NOTIFICATION RESULT" type
        args.append(
            ("log_type", self._get_log_type_expr(properties["log_target"])))

        # Context
        for fil in context.values():
            for k, f in fil.items():
                args.append((k, f))

        return tooltip, makeuri_contextless(request, args, filename="view.py")
Пример #4
0
def render_time_range_selection(graph_recipe, graph_render_options) -> HTML:
    now = int(time.time())
    graph_render_options = copy.deepcopy(graph_render_options)
    rows = []
    for timerange_attrs in config.graph_timeranges:
        duration = timerange_attrs["duration"]
        assert isinstance(duration, int)
        graph_render_options.update({
            "size": (20, 4),
            "font_size":
            6.0,  # pt
            "onclick":
            "cmk.graphs.change_graph_timerange(graph, %d)" % duration,
            "fixed_timerange":
            True,  # Do not follow timerange changes of other graphs
            "title":
            timerange_attrs["title"],
            "show_legend":
            False,
            "show_controls":
            False,
            "preview":
            True,
            "resizable":
            False,
            "interaction":
            False,
        })

        timerange = now - duration, now
        graph_data_range = {
            "time_range":
            timerange,
            "step":
            2 * estimate_graph_step_for_html(timerange, graph_render_options),
        }

        graph_artwork = artwork.compute_graph_artwork(graph_recipe,
                                                      graph_data_range,
                                                      graph_render_options)
        rows.append(
            html.render_td(
                render_graph_html(graph_artwork, graph_data_range,
                                  graph_render_options),
                title=_("Change graph timerange to: %s") %
                timerange_attrs["title"],
            ))
    return html.render_table(HTML().join(
        html.render_tr(content) for content in rows),
                             class_="timeranges")
Пример #5
0
    def action(self) -> ActionResult:
        renaming_config = self._vs_renaming_config().from_html_vars("")
        self._vs_renaming_config().validate_value(renaming_config, "")
        renamings = self._collect_host_renamings(renaming_config)

        if not renamings:
            flash(_("No matching host names"))
            return None

        warning = self._renaming_collision_error(renamings)
        if warning:
            flash(warning)
            return None

        message = html.render_b(
            _("Do you really want to rename to following hosts?"
              "This involves a restart of the monitoring core!"))

        rows = []
        for _folder, host_name, target_name in renamings:
            rows.append(
                html.render_tr(
                    html.render_td(host_name) +
                    html.render_td(" → %s" % target_name)))
        message += html.render_table(HTML().join(rows))

        nr_rename = len(renamings)
        c = _confirm(
            _("Confirm renaming of %d %s") %
            (nr_rename, ungettext("host", "hosts", nr_rename)),
            message,
        )
        if c:
            title = _("Renaming of %s") % ", ".join("%s → %s" % x[1:]
                                                    for x in renamings)
            host_renaming_job = RenameHostsBackgroundJob(title=title)
            host_renaming_job.set_function(rename_hosts_background_job,
                                           renamings)

            try:
                host_renaming_job.start()
            except background_job.BackgroundJobAlreadyRunning as e:
                raise MKGeneralException(
                    _("Another host renaming job is already running: %s") % e)

            return redirect(host_renaming_job.detail_url())
        if c is False:  # not yet confirmed
            return FinalizeRequest(code=200)
        return None  # browser reload
Пример #6
0
    def _forge_tooltip_and_url(self, time_frame, properties, context):
        mode_properties = properties["render_mode"][1]
        time_range = self._int_time_range_from_rangespec(
            mode_properties["time_range"])
        ending_timestamp = min(time_frame["ending_timestamp"], time_range[1])
        from_time_str = date_and_time(time_frame["timestamp"])
        to_time_str = date_and_time(ending_timestamp)
        # TODO: Can this be simplified by passing a list as argument to html.render_table()?
        tooltip = html.render_table(
            html.render_tr(
                html.render_td(_("From:")) + html.render_td(from_time_str)) +
            html.render_tr(
                html.render_td(_("To:")) + html.render_td(to_time_str)) +
            html.render_tr(
                html.render_td("%ss:" %
                               properties["log_target"].capitalize()) +
                html.render_td(time_frame["value"])))

        args: HTTPVariables = []
        # Generic filters
        args.append(("filled_in", "filter"))
        args.append(("view_name", "events"))
        args.append(("logtime_from", str(time_frame["timestamp"])))
        args.append(("logtime_from_range", "unix"))
        args.append(("logtime_until", str(ending_timestamp)))
        args.append(("logtime_until_range", "unix"))
        args.append(("logclass%d" % self.log_class, "on"))

        # Target filters
        if properties["log_target"] == "host":
            args.append(("logst_h0", "on"))
            args.append(("logst_h1", "on"))
            args.append(("logst_h2", "on"))
        elif properties["log_target"] == "service":
            args.append(("logst_s0", "on"))
            args.append(("logst_s1", "on"))
            args.append(("logst_s2", "on"))
            args.append(("logst_s3", "on"))

        # Context
        for fil in context.values():
            for k, f in fil.items():
                args.append((k, f))

        return tooltip, makeuri_contextless(request, args, filename="view.py")
Пример #7
0
def render_perfometer(data):
    tds = HTML().join(
        render_perfometer_td(percentage, color) for percentage, color in data)
    return html.render_table(html.render_tr(tds))
Пример #8
0
def _process_notify_message(msg):
    msg["id"] = utils.gen_id()
    msg["time"] = time.time()

    if isinstance(msg["dest"], str):
        dest_what = msg["dest"]
    else:
        dest_what = msg["dest"][0]

    if dest_what == "broadcast":
        recipients = list(config.multisite_users.keys())
    elif dest_what == "online":
        recipients = userdb.get_online_user_ids()
    elif dest_what == "list":
        recipients = msg["dest"][1]
    else:
        recipients = []

    num_recipients = len(recipients)

    num_success = {}
    for method in msg["methods"]:
        num_success[method] = 0

    # Now loop all notitification methods to send the notifications
    errors: Dict[str, List[Tuple]] = {}
    for user_id in recipients:
        for method in msg["methods"]:
            try:
                handler = _notify_methods()[method]["handler"]
                handler(user_id, msg)
                num_success[method] = num_success[method] + 1
            except MKInternalError as e:
                errors.setdefault(method, []).append((user_id, e))

    message = escape_html_permissive(_("The notification has been sent via"))
    message += html.render_br()

    parts = []
    for method in msg["methods"]:
        parts.append(
            html.render_tr(
                html.render_td(_notify_methods()[method]["title"])
                + html.render_td(
                    _("to %d of %d recipients") % (num_success[method], num_recipients)
                )
            )
        )
    message += html.render_table(HTML().join(parts))

    message += html.render_p(_("Sent notification to: %s") % ", ".join(recipients))
    message += html.render_a(_("Back to previous page"), href=makeuri(request, []))
    html.show_message(message)

    if errors:
        error_message = HTML()
        for method, method_errors in errors.items():
            error_message += _("Failed to send %s notifications to the following users:") % method
            table_rows = HTML()
            for user_id, exception in method_errors:
                table_rows += html.render_tr(
                    html.render_td(html.render_tt(user_id)) + html.render_td(exception)
                )
            error_message += html.render_table(table_rows) + html.render_br()
        html.show_error(error_message)
Пример #9
0
def _process_message_message(msg):
    msg["id"] = utils.gen_id()
    msg["time"] = time.time()

    if isinstance(msg["dest"], str):
        dest_what = msg["dest"]
    else:
        dest_what = msg["dest"][0]

    if dest_what == "all_users":
        recipients = list(config.multisite_users.keys())
    elif dest_what == "online":
        recipients = userdb.get_online_user_ids()
    elif dest_what == "list":
        recipients = msg["dest"][1]
    else:
        recipients = []

    num_recipients = len(recipients)

    num_success: Dict[str, int] = {}
    for method in msg["methods"]:
        num_success[method] = 0

    # Now loop all messaging methods to send the messages
    errors: Dict[str, List[Tuple]] = {}
    for user_id in recipients:
        for method in msg["methods"]:
            try:
                handler = _messaging_methods()[method]["handler"]
                handler(user_id, msg)
                num_success[method] = num_success[method] + 1
            except MKInternalError as e:
                errors.setdefault(method, []).append((user_id, e))

    message = escape_html_permissive(
        _("The message has successfully been sent..."))
    message += html.render_br()

    parts = []
    for method in msg["methods"]:
        parts.append(
            html.render_li(
                _messaging_methods()[method]["confirmation_title"] +
                (_(" for all recipients.") if num_success[method] ==
                 num_recipients else _(" for %d of %d recipients.") %
                 (num_success[method], num_recipients))))

    message += html.render_ul(HTML().join(parts))
    message += html.render_p(_("Recipients: %s") % ", ".join(recipients))
    html.show_message(message)

    if errors:
        error_message = HTML()
        for method, method_errors in errors.items():
            error_message += _(
                "Failed to send %s messages to the following users:") % method
            table_rows = HTML()
            for user_id, exception in method_errors:
                table_rows += html.render_tr(
                    html.render_td(html.render_tt(user_id)) +
                    html.render_td(str(exception)))
            error_message += html.render_table(table_rows) + html.render_br()
        html.show_error(error_message)