Ejemplo n.º 1
0
def filter_cre_choices():
    return sorted([(sitename, config.site(sitename)["alias"])
                   for sitename, state in sites.states().items()
                   if state["state"] == "online"],
                  key=lambda a: a[1].lower())
Ejemplo n.º 2
0
    def _show_master_control_site(self, site_id, site_status_info, items):
        # type: (sites.SiteId, Dict[sites.SiteId, List], List[Tuple[str, str]]) -> None
        site_state = sites.states().get(site_id)

        if not site_state:
            html.show_error(_("Site state is unknown"))
            return

        if site_state["state"] == "dead":
            html.show_error(site_state["exception"])
            return

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

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

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

        try:
            site_info = site_status_info[site_id]
        except KeyError:
            html.show_error(_("Site state is unknown"))
            return

        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

            if 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()
Ejemplo n.º 3
0
def _synchronize_profiles_to_sites(logger, profiles_to_synchronize):
    if not profiles_to_synchronize:
        return

    remote_sites = [(site_id, get_site_config(site_id)) for site_id in get_login_slave_sites()]

    logger.info(
        "Credentials changed for %s. Trying to sync to %d sites"
        % (", ".join(profiles_to_synchronize.keys()), len(remote_sites))
    )

    states = sites.states()

    pool = ThreadPool()
    jobs = []
    for site_id, site in remote_sites:
        jobs.append(
            pool.apply_async(
                _sychronize_profile_worker, (states, site_id, site, profiles_to_synchronize)
            )
        )

    results = []
    start_time = time.time()
    while time.time() - start_time < 30:
        for job in jobs[:]:
            try:
                results.append(job.get(timeout=0.5))
                jobs.remove(job)
            except mp_TimeoutError:
                pass
        if not jobs:
            break

    contacted_sites = {x[0] for x in remote_sites}
    working_sites = {result.site_id for result in results}
    for site_id in contacted_sites - working_sites:
        results.append(
            SynchronizationResult(
                site_id, error_text=_("No response from update thread"), failed=True
            )
        )

    for result in results:
        if result.error_text:
            logger.info("  FAILED [%s]: %s" % (result.site_id, result.error_text))
            if active_config.wato_enabled:
                add_change(
                    "edit-users",
                    _("Password changed (sync failed: %s)") % result.error_text,
                    add_user=False,
                    sites=[result.site_id],
                    need_restart=False,
                )

    pool.terminate()
    pool.join()

    num_failed = sum([1 for result in results if result.failed])
    num_disabled = sum([1 for result in results if result.disabled])
    num_succeeded = sum([1 for result in results if result.succeeded])
    logger.info(
        "  Disabled: %d, Succeeded: %d, Failed: %d" % (num_disabled, num_succeeded, num_failed)
    )
Ejemplo 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
Ejemplo n.º 5
0
 def _livestatus_get_last_program_start(self, site_id: SiteId) -> int:
     return sites.states().get(site_id, sites.SiteStatus({})).get(
         "program_start", 0)