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 _show_tree(self): td_style = None if self._wrap_texts == "wrap" else "white-space: nowrap;" tree = self._get_tree() depth = status_tree_depth(tree) leaves = self._gen_table(tree, depth, len(self._row["aggr_hosts"]) > 1) html.open_table(class_=["aggrtree", "ltr"]) odd = "odd" for code, colspan, parents in leaves: html.open_tr() leaf_td = html.render_td(code, class_=["leaf", odd], style=td_style, colspan=colspan) odd = "even" if odd == "odd" else "odd" tds = [leaf_td] for rowspan, c in parents: tds.append(html.render_td(c, class_=["node"], style=td_style, rowspan=rowspan)) if self._mirror: tds.reverse() html.write_html(HTML("").join(tds)) html.close_tr() html.close_table()
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 show(self) -> None: only_sites = snapin_site_choice("mkeventd_performance", get_event_console_site_choices()) try: entries = self._mkeventd_performance_entries(only_sites) except Exception as e: html.show_error("%s" % e) return html.open_table(class_=["mkeventd_performance"]) for _index, left, right in entries: html.tr(html.render_td("%s:" % left) + html.render_td(right)) html.close_table()
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
def header(title: str, isopen: bool = True, table_id: str = "", narrow: bool = False, css: Optional[str] = None, show_more_toggle: bool = False, show_more_mode: bool = False) -> None: global g_header_open, g_section_open if g_header_open: end() id_ = ensure_str(base64.b64encode(ensure_binary(title))) treename = html.form_name or "nform" isopen = html.foldable_container_is_open(treename, id_, isopen) html.open_table(id_=table_id if table_id else None, class_=[ "nform", "narrow" if narrow else None, css if css else None, "open" if isopen else "closed", "more" if show_more_mode else None, ]) _begin_foldable_nform_container( treename=treename, id_=id_, isopen=isopen, title=title, show_more_toggle=show_more_toggle, ) html.tr(html.render_td('', colspan=2)) g_header_open = True g_section_open = False
def end() -> None: global g_header_open g_header_open = False section_close() html.tr(html.render_td('', colspan=2), class_=["bottom"]) html.close_tbody() html.close_table()
def end(): global g_header_open g_header_open = False if g_section_open: html.close_td() html.close_tr() html.end_foldable_container() html.tr(html.render_td('', colspan=2), class_=["bottom"]) html.close_tbody() html.close_table()
def render_perfometer_td(perc, color): # the hex color can have additional information about opacity # internet explorer has problems with the format of rgba, e.g.: #aaaaaa4d # the solution is to set the background-color value to rgb ('#aaaaaa') # and use the css opacity for the opacity hex value in float '4d' -> 0.3 opacity = None if len(color) == 9: opacity = int(color[7:], 16) / 255.0 color = color[:7] style = ["width: %d%%;" % int(float(perc)), "background-color: %s" % color] if opacity is not None: style += ["opacity: %s" % opacity] return html.render_td('', class_="inner", style=style)
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")
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")
def header( title: str, isopen: bool = True, table_id: str = "", narrow: bool = False, css: Optional[str] = None, show_table_head: bool = True, show_more_toggle: bool = False, show_more_mode: bool = False, help_text: Union[str, HTML, None] = None, ) -> None: global g_header_open, g_section_open if g_header_open: end() id_ = base64.b64encode(title.encode()).decode() treename = html.form_name or "nform" isopen = user.get_tree_state(treename, id_, isopen) container_id = foldable_container_id(treename, id_) html.open_table( id_=table_id if table_id else None, class_=[ "nform", "narrow" if narrow else None, css if css else None, "open" if isopen else "closed", "more" if user.get_show_more_setting("foldable_%s" % id_) or show_more_mode else None, ], ) if show_table_head: _table_head( treename=treename, id_=id_, isopen=isopen, title=title, show_more_toggle=show_more_toggle, help_text=help_text, ) html.open_tbody(id_=container_id, class_=["open" if isopen else "closed"]) html.tr(html.render_td("", colspan=2)) g_header_open = True g_section_open = False
def header(title, isopen=True, table_id="", narrow=False, css=None): # type: (str, bool, str, bool, Optional[str]) -> None global g_header_open, g_section_open if g_header_open: end() html.open_table(id_=table_id if table_id else None, class_=["nform", "narrow" if narrow else None, css if css else None]) html.begin_foldable_container(treename=html.form_name if html.form_name else "nform", id_=ensure_str(base64.b64encode(ensure_binary(title))), isopen=isopen, title=title, indent="nform") html.tr(html.render_td('', colspan=2)) g_header_open = True g_section_open = False
def header(title, isopen=True, table_id="", narrow=False, css=None): global g_header_open, g_section_open if g_header_open: end() html.open_table(id_=table_id if table_id else None, class_=["nform", "narrow" if narrow else None, css if css else None]) html.begin_foldable_container( treename=html.form_name if html.form_name else "nform", id_=base64.b64encode(title.encode("utf-8") if isinstance(title, six.text_type) else title), isopen=isopen, title=title, indent="nform") html.tr(html.render_td('', colspan=2)) g_header_open = True g_section_open = False
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")
def space() -> None: html.tr(html.render_td('', colspan=2, style="height:15px;"))
def render_perfometer_td(perc, color): style = ["width: %d%%;" % int(float(perc)), "background-color: %s" % color] return html.render_td('', class_="inner", style=style)
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)
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)