Exemplo n.º 1
0
def test_sorted_sites(mocker):
    mocker.patch.object(config.user,
                        "authorized_sites",
                        return_value={
                            'site1': {
                                'alias': 'Site 1'
                            },
                            'site3': {
                                'alias': 'Site 3'
                            },
                            'site5': {
                                'alias': 'Site 5'
                            },
                            'site23': {
                                'alias': 'Site 23'
                            },
                            'site6': {
                                'alias': 'Site 6'
                            },
                            'site12': {
                                'alias': 'Site 12'
                            },
                        })
    expected = [('site1', 'Site 1'), ('site12', 'Site 12'),
                ('site23', 'Site 23'), ('site3', 'Site 3'),
                ('site5', 'Site 5'), ('site6', 'Site 6')]
    assert config.sorted_sites() == expected
Exemplo n.º 2
0
    def show(self):
        # type: () -> None
        items = self._core_toggles()
        sites.update_site_states_from_dead_sites()

        site_status_info = {}  # type: Dict[sites.SiteId, List]
        try:
            sites.live().set_prepend_site(True)
            for row in sites.live().query("GET status\nColumns: %s" %
                                          " ".join([i[0] for i in items])):
                site_id, values = row[0], row[1:]
                site_status_info[site_id] = values
        finally:
            sites.live().set_prepend_site(False)

        for site_id, site_alias in config.sorted_sites():
            if not config.is_single_local_site():
                html.begin_foldable_container("master_control", site_id, True,
                                              site_alias)

            try:
                self._show_master_control_site(site_id, site_status_info,
                                               items)
            except Exception as e:
                logger.exception("error rendering master control for site %s",
                                 site_id)
                write_snapin_exception(e)
            finally:
                if not config.is_single_local_site():
                    html.end_foldable_container()
Exemplo n.º 3
0
    def show(self) -> None:
        items = self._core_toggles()
        sites.update_site_states_from_dead_sites()

        site_status_info: Dict[sites.SiteId, List] = {}
        try:
            sites.live().set_prepend_site(True)
            for row in sites.live().query("GET status\nColumns: %s" %
                                          " ".join([i[0] for i in items])):
                site_id, values = row[0], row[1:]
                site_status_info[site_id] = values
        finally:
            sites.live().set_prepend_site(False)

        for site_id, site_alias in config.sorted_sites():
            container: ContextManager[bool] = foldable_container(
                treename="master_control",
                id_=site_id,
                isopen=True,
                title=site_alias,
                icon="foldable_sidebar"
            ) if not config.is_single_local_site() else nullcontext(False)
            with container:
                try:
                    self._show_master_control_site(site_id, site_status_info,
                                                   items)
                except Exception as e:
                    logger.exception(
                        "error rendering master control for site %s", site_id)
                    write_snapin_exception(e)
Exemplo n.º 4
0
    def _collect_sites_data(cls) -> List[ABCElement]:
        sites.update_site_states_from_dead_sites()

        site_states = sites.states()
        site_state_titles = sites.site_state_titles()
        site_stats = cls._get_site_stats()

        elements: List[ABCElement] = []
        for site_id, _sitealias in config.sorted_sites():
            site_spec = config.site(site_id)
            site_status = site_states.get(site_id, sites.SiteStatus({}))
            state: Optional[str] = site_status.get("state")

            if state is None:
                state = "missing"

            if state != "online":
                elements.append(
                    IconElement(
                        title=site_spec["alias"],
                        css_class="site_%s" % state,
                        tooltip=site_state_titles[state],
                    ))
                continue

            stats = site_stats[site_id]
            parts = []
            total = 0
            for title, css_class, count in [
                (_("hosts are down or have critical services"), "critical",
                 stats.hosts_down_or_have_critical),
                (_("hosts are unreachable or have unknown services"), "unknown",
                 stats.hosts_unreachable_or_have_unknown),
                (_("hosts are up but have services in warning state"), "warning",
                 stats.hosts_up_and_have_warning),
                (_("hosts are in scheduled downtime"), "downtime", stats.hosts_in_downtime),
                (_("hosts are up and have no service problems"), "ok",
                 stats.hosts_up_without_problem),
            ]:
                parts.append(Part(title=title, css_class=css_class, count=count))
                total += count

            total_part = Part(title=_("Total number of hosts"), css_class="", count=total)

            elements.append(
                SiteElement(
                    title=site_spec["alias"],
                    url_add_vars={
                        "name": "site",
                        "site": site_id,
                    },
                    parts=parts,
                    total=total_part,
                    tooltip=cls._render_tooltip(site_spec["alias"], parts, total_part),
                ))

        #return elements + cls._test_elements()
        return elements
Exemplo n.º 5
0
    def show(self) -> None:
        html.open_table(cellspacing="0", class_="sitestate")

        sites.update_site_states_from_dead_sites()

        for sitename, _sitealias in config.sorted_sites():
            site = config.site(sitename)

            state = sites.states().get(sitename,
                                       sites.SiteStatus({})).get("state")

            if state is None:
                state = "missing"
                switch = "missing"
                text = sitename

            else:
                if state == "disabled":
                    switch = "on"
                    text = site["alias"]
                else:
                    switch = "off"
                    text = render_link(
                        site["alias"],
                        "view.py?view_name=sitehosts&site=%s" % sitename)

            html.open_tr()
            html.open_td(class_="left")
            html.write(text)
            html.close_td()
            html.open_td(class_="state")
            if switch == "missing":
                html.status_label(content=state,
                                  status=state,
                                  title=_("Site is missing"))
            else:
                url = makeactionuri_contextless(request,
                                                transactions, [
                                                    ("_site_switch", "%s:%s" %
                                                     (sitename, switch)),
                                                ],
                                                filename="switch_site.py")
                html.status_label_button(
                    content=state,
                    status=state,
                    title=_("enable this site")
                    if state == "disabled" else _("disable this site"),
                    onclick="cmk.sidebar.switch_site(%s)" % (json.dumps(url)))
            html.close_tr()
        html.close_table()
Exemplo n.º 6
0
    def show(self):
        items = [
            ("enable_notifications", _("Notifications")),
            ("execute_service_checks", _("Service checks")),
            ("execute_host_checks", _("Host checks")),
            ("enable_flap_detection", _("Flap Detection")),
            ("enable_event_handlers", _("Event handlers")),
            ("process_performance_data", _("Performance data")),
            ("enable_event_handlers", _("Alert handlers")),
        ]

        sites.update_site_states_from_dead_sites()

        site_status_info = {}
        try:
            sites.live().set_prepend_site(True)
            for row in sites.live().query("GET status\nColumns: %s" %
                                          " ".join([i[0] for i in items])):
                site_id, values = row[0], row[1:]
                site_status_info[site_id] = values
        finally:
            sites.live().set_prepend_site(False)

        def _render_master_control_site(site_id):
            site_state = sites.states().get(site_id)
            if site_state["state"] == "dead":
                html.show_error(site_state["exception"])

            elif site_state["state"] == "disabled":
                html.show_message(_("Site is disabled"))

            elif site_state["state"] == "unknown":
                if site_state.get("exception"):
                    html.show_error(site_state["exception"])
                else:
                    html.show_error(_("Site state is unknown"))

            else:
                is_cmc = site_state["program_version"].startswith("Check_MK ")

                try:
                    site_info = site_status_info[site_id]
                except KeyError:
                    site_info = None

                html.open_table(class_="master_control")
                for i, (colname, title) in enumerate(items):
                    # Do not show event handlers on Check_MK Micro Core
                    if is_cmc and title == _("Event handlers"):
                        continue
                    elif not is_cmc and title == _("Alert handlers"):
                        continue

                    colvalue = site_info[i]
                    url = html.makeactionuri_contextless(
                        [
                            ("site", site_id),
                            ("switch", colname),
                            ("state", "%d" % (1 - colvalue)),
                        ],
                        filename="switch_master_state.py")
                    onclick = "cmk.ajax.get_url('%s', cmk.utils.update_contents, 'snapin_master_control')" % url

                    html.open_tr()
                    html.td(title, class_="left")
                    html.open_td()
                    html.toggle_switch(
                        enabled=colvalue,
                        help_txt=_("Switch '%s' to '%s'") %
                        (title, _("off") if colvalue else _("on")),
                        onclick=onclick,
                    )
                    html.close_td()
                    html.close_tr()

                html.close_table()

        for site_id, site_alias in config.sorted_sites():
            if not config.is_single_local_site():
                html.begin_foldable_container("master_control", site_id, True,
                                              site_alias)

            try:
                _render_master_control_site(site_id)
            except Exception as e:
                logger.exception("error rendering master control for site %s",
                                 site_id)
                write_snapin_exception(e)
            finally:
                if not config.is_single_local_site():
                    html.end_foldable_container()
Exemplo n.º 7
0
 def _get_user_sites(self, request):
     return config.sorted_sites()