Esempio n. 1
0
    def handle_page(self) -> None:
        """The page handler, called by the page registry"""
        response.set_content_type("application/json")
        try:
            action_response = self.page()
            resp = {
                "result_code": 0,
                "result": action_response,
                "severity": "success"
            }
        except MKMissingDataError as e:
            resp = {"result_code": 1, "result": str(e), "severity": "success"}
        except MKException as e:
            resp = {"result_code": 1, "result": str(e), "severity": "error"}

        except Exception as e:
            if active_config.debug:
                raise
            logger.exception("error calling AJAX page handler")
            handle_exception_as_gui_crash_report(
                plain_error=True,
                show_crash_link=getattr(g, "may_see_crash_reports", False),
            )
            resp = {"result_code": 1, "result": str(e), "severity": "error"}

        response.set_data(json.dumps(resp))
Esempio n. 2
0
def move_snapin() -> None:
    response.set_content_type("application/json")
    if not user.may("general.configure_sidebar"):
        return None

    snapin_id = request.var("name")
    if snapin_id is None:
        return None

    user_config = UserSidebarConfig(user, active_config.sidebar)

    try:
        snapin = user_config.get_snapin(snapin_id)
    except KeyError:
        return None

    before_id = request.var("before")
    before_snapin: Optional[UserSidebarSnapin] = None
    if before_id:
        try:
            before_snapin = user_config.get_snapin(before_id)
        except KeyError:
            pass

    user_config.move_snapin_before(snapin, before_snapin)
    user_config.save()
    return None
Esempio n. 3
0
    def page(self):
        check_csrf_token()
        response.set_content_type("application/json")
        if not user.may("general.configure_sidebar"):
            return None

        snapin_id = request.var("name")
        if snapin_id is None:
            return None

        state = request.var("state")
        if state not in [
                SnapinVisibility.OPEN.value, SnapinVisibility.CLOSED.value,
                "off"
        ]:
            raise MKUserError("state", "Invalid state: %s" % state)

        user_config = UserSidebarConfig(user, active_config.sidebar)

        try:
            snapin = user_config.get_snapin(snapin_id)
        except KeyError:
            return None

        if state == "off":
            user_config.remove_snapin(snapin)
        else:
            snapin.visible = SnapinVisibility(state)

        user_config.save()
        return None
Esempio n. 4
0
 def _ajax_tag_tree_enter(self):
     response.set_content_type("application/json")
     self._load()
     path = request.get_str_input_mandatory("path").split(
         "|") if request.var("path") else []
     self._cwds[self._current_tree_id] = path
     self._save_user_settings()
     response.set_data("OK")
Esempio n. 5
0
def page_api() -> None:
    try:
        if not request.has_var("output_format"):
            response.set_content_type("application/json")
            output_format = "json"
        else:
            output_format = request.get_ascii_input_mandatory(
                "output_format", "json").lower()

        if output_format not in _FORMATTERS:
            response.set_content_type("text/plain")
            raise MKUserError(
                None,
                "Only %s are supported as output formats" %
                " and ".join('"%s"' % f for f in _FORMATTERS),
            )

        # TODO: Add some kind of helper for boolean-valued variables?
        pretty_print = False
        pretty_print_var = request.get_str_input_mandatory(
            "pretty_print", "no").lower()
        if pretty_print_var not in ("yes", "no"):
            raise MKUserError(None, 'pretty_print must be "yes" or "no"')
        pretty_print = pretty_print_var == "yes"

        api_call = _get_api_call()
        _check_permissions(api_call)
        request_object = _get_request(api_call)
        _check_formats(output_format, api_call, request_object)
        _check_request_keys(api_call, request_object)
        resp = _execute_action(api_call, request_object)

    except MKAuthException as e:
        resp = {
            "result_code":
            1,
            "result":
            _("Authorization Error. Insufficent permissions for '%s'") % e,
        }
    except MKException as e:
        resp = {
            "result_code":
            1,
            "result":
            _("Checkmk exception: %s\n%s") %
            (e, "".join(traceback.format_exc())),
        }
    except Exception:
        if active_config.debug:
            raise
        logger.exception("error handling web API call")
        resp = {
            "result_code": 1,
            "result": _("Unhandled exception: %s") % traceback.format_exc(),
        }

    response.set_data(
        _FORMATTERS[output_format][1 if pretty_print else 0](resp))
Esempio n. 6
0
def ajax_message_read():
    response.set_content_type("application/json")
    try:
        message.delete_gui_message(request.var("id"))
        html.write_text("OK")
    except Exception:
        if active_config.debug:
            raise
        html.write_text("ERROR")
Esempio n. 7
0
    def _ajax_tag_tree(self):
        response.set_content_type("application/json")
        self._load()
        new_tree = request.var("tree_id")

        if new_tree not in self._trees:
            raise MKUserError("conf",
                              _("This virtual host tree does not exist."))

        self._current_tree_id = new_tree
        self._save_user_settings()
        response.set_data("OK")
Esempio n. 8
0
    def _export_audit_log(self, audit: List[AuditLogStore.Entry]) -> ActionResult:
        response.set_content_type("text/csv")

        if self._options["display"] == "daily":
            filename = "wato-auditlog-%s_%s.csv" % (
                render.date(time.time()),
                render.time_of_day(time.time()),
            )
        else:
            filename = "wato-auditlog-%s_%s_days.csv" % (
                render.date(time.time()),
                self._options["display"][1],
            )

        response.headers["Content-Disposition"] = 'attachment; filename="%s"' % filename

        titles = [
            _("Date"),
            _("Time"),
            _("Object type"),
            _("Object"),
            _("User"),
            _("Action"),
            _("Summary"),
        ]

        if self._show_details:
            titles.append(_("Details"))

        resp = []

        resp.append(",".join(titles) + "\n")
        for entry in audit:
            columns = [
                render.date(int(entry.time)),
                render.time_of_day(int(entry.time)),
                entry.object_ref.object_type.name if entry.object_ref else "",
                entry.object_ref.ident if entry.object_ref else "",
                entry.user_id,
                entry.action,
                '"' + escaping.strip_tags(entry.text).replace('"', "'") + '"',
            ]

            if self._show_details:
                columns.append('"' + escaping.strip_tags(entry.diff_text).replace('"', "'") + '"')

            resp.append(",".join(columns) + "\n")

        response.set_data("".join(resp))

        return FinalizeRequest(code=200)
Esempio n. 9
0
    def page(self) -> None:
        if not user.may("wato.diagnostics"):
            raise MKAuthException(
                _("Sorry, you lack the permission for downloading diagnostics dumps."
                  ))

        site = SiteId(request.get_ascii_input_mandatory("site"))
        tarfile_name = request.get_ascii_input_mandatory("tarfile_name")
        file_content = self._get_diagnostics_dump_file(site, tarfile_name)

        response.set_content_type("application/x-tgz")
        response.headers[
            "Content-Disposition"] = "Attachment; filename=%s" % tarfile_name
        response.set_data(file_content)
Esempio n. 10
0
 def handle_page(self) -> None:
     try:
         response.set_content_type("application/cbor")
         response.set_data(cbor.encode(self.page()))
     except MKGeneralException as e:
         response.status_code = http_client.BAD_REQUEST
         response.set_data(str(e))
     except Exception as e:
         response.status_code = http_client.INTERNAL_SERVER_ERROR
         handle_exception_as_gui_crash_report(
             plain_error=True,
             show_crash_link=getattr(g, "may_see_crash_reports", False),
         )
         response.set_data(str(e))
Esempio n. 11
0
def ajax_snapin():
    """Renders and returns the contents of the requested sidebar snapin(s) in JSON format"""
    response.set_content_type("application/json")
    user_config = UserSidebarConfig(user, active_config.sidebar)

    snapin_id = request.var("name")
    snapin_ids = ([snapin_id] if snapin_id else
                  request.get_str_input_mandatory("names", "").split(","))

    snapin_code: List[str] = []
    for snapin_id in snapin_ids:
        try:
            snapin_instance = user_config.get_snapin(snapin_id).snapin_type()
        except KeyError:
            continue  # Skip not existing snapins

        if not snapin_instance.may_see():
            continue

        # When restart snapins are about to be refreshed, only render
        # them, when the core has been restarted after their initial
        # rendering
        if not snapin_instance.refresh_regularly(
        ) and snapin_instance.refresh_on_restart():
            since = request.get_float_input_mandatory("since", 0)
            newest = since
            for site in sites.states().values():
                prog_start = site.get("program_start", 0)
                if prog_start > newest:
                    newest = prog_start
            if newest <= since:
                # no restart
                snapin_code.append("")
                continue

        with output_funnel.plugged():
            try:
                snapin_instance.show()
            except Exception as e:
                write_snapin_exception(e)
                e_message = (
                    _("Exception during element refresh (element '%s')") %
                    snapin_instance.type_name())
                logger.error("%s %s: %s", request.requested_url, e_message,
                             traceback.format_exc())
            finally:
                snapin_code.append(output_funnel.drain())

    response.set_data(json.dumps(snapin_code))
Esempio n. 12
0
def ajax_set_snapin_site():
    response.set_content_type("application/json")
    ident = request.var("ident")
    if ident not in snapin_registry:
        raise MKUserError(None, _("Invalid ident"))

    site = request.var("site")
    site_choices = dict([(SiteId(""), _("All sites"))] +
                        user_sites.get_configured_site_choices())

    if site not in site_choices:
        raise MKUserError(None, _("Invalid site"))

    snapin_sites = user.load_file("sidebar_sites", {}, lock=True)
    snapin_sites[ident] = site
    user.save_file("sidebar_sites", snapin_sites)
Esempio n. 13
0
    def page(self):
        if not user.may("wato.automation"):
            raise MKAuthException(
                _("This account has no permission for automation."))

        response.set_content_type("text/plain")
        _set_version_headers()

        # Parameter was added with 1.5.0p10
        if not request.has_var("_version"):
            raise MKGeneralException(
                _("Your central site is incompatible with this remote site"))

        # - _version and _edition_short were added with 1.5.0p10 to the login call only
        # - x-checkmk-version and x-checkmk-edition were added with 2.0.0p1
        # Prefer the headers and fall back to the request variables for now.
        central_version = (request.headers["x-checkmk-version"]
                           if "x-checkmk-version" in request.headers else
                           request.get_ascii_input_mandatory("_version"))
        central_edition_short = (
            request.headers["x-checkmk-edition"]
            if "x-checkmk-edition" in request.headers else
            request.get_ascii_input_mandatory("_edition_short"))

        if not compatible_with_central_site(
                central_version,
                central_edition_short,
                cmk_version.__version__,
                cmk_version.edition().short,
        ):
            raise MKGeneralException(
                _("Your central site (Version: %s, Edition: %s) is incompatible with this "
                  "remote site (Version: %s, Edition: %s)") % (
                      central_version,
                      central_edition_short,
                      cmk_version.__version__,
                      cmk_version.edition().short,
                  ))

        response.set_data(
            repr({
                "version": cmk_version.__version__,
                "edition_short": cmk_version.edition().short,
                "login_secret": _get_login_secret(create_on_demand=True),
            }))
Esempio n. 14
0
    def _ajax_switch_masterstate(self) -> None:
        response.set_content_type("text/plain")

        if not user.may("sidesnap.master_control"):
            return

        if not transactions.check_transaction():
            return

        site = SiteId(request.get_ascii_input_mandatory("site"))
        column = request.get_ascii_input_mandatory("switch")
        state = request.get_integer_input_mandatory("state")
        commands = {
            ("enable_notifications", 1): "ENABLE_NOTIFICATIONS",
            ("enable_notifications", 0): "DISABLE_NOTIFICATIONS",
            ("execute_service_checks", 1): "START_EXECUTING_SVC_CHECKS",
            ("execute_service_checks", 0): "STOP_EXECUTING_SVC_CHECKS",
            ("execute_host_checks", 1): "START_EXECUTING_HOST_CHECKS",
            ("execute_host_checks", 0): "STOP_EXECUTING_HOST_CHECKS",
            ("enable_flap_detection", 1): "ENABLE_FLAP_DETECTION",
            ("enable_flap_detection", 0): "DISABLE_FLAP_DETECTION",
            ("process_performance_data", 1): "ENABLE_PERFORMANCE_DATA",
            ("process_performance_data", 0): "DISABLE_PERFORMANCE_DATA",
            ("enable_event_handlers", 1): "ENABLE_EVENT_HANDLERS",
            ("enable_event_handlers", 0): "DISABLE_EVENT_HANDLERS",
        }

        command = commands.get((column, state))
        if not command:
            html.write_text(_("Command %s/%d not found") % (column, state))
            return

        sites.live().command("[%d] %s" % (int(time.time()), command), site)
        sites.live().set_only_sites([site])
        sites.live().query(
            "GET status\nWaitTrigger: program\nWaitTimeout: 10000\nWaitCondition: %s = %d\nColumns: %s\n"
            % (column, state, column)
        )
        sites.live().set_only_sites()

        self.show()
Esempio n. 15
0
    def _ajax_switch_site(self):
        response.set_content_type("application/json")
        # _site_switch=sitename1:on,sitename2:off,...
        if not user.may("sidesnap.sitestatus"):
            return

        if not transactions.check_transaction():
            return

        switch_var = request.var("_site_switch")
        if switch_var:
            for info in switch_var.split(","):
                sitename_str, onoff = info.split(":")
                sitename = SiteId(sitename_str)
                if sitename not in site_config.sitenames():
                    continue

                if onoff == "on":
                    user.enable_site(sitename)
                else:
                    user.disable_site(sitename)

            user.save_site_config()
Esempio n. 16
0
    def _ajax_speedometer(self):
        response.set_content_type("application/json")
        try:
            # Try to get values from last call in order to compute
            # driftig speedometer-needle and to reuse the scheduled
            # check reate.
            # TODO: Do we need a get_float_input_mandatory?
            last_perc = float(request.get_str_input_mandatory("last_perc"))
            scheduled_rate = float(request.get_str_input_mandatory("scheduled_rate"))
            last_program_start = request.get_integer_input_mandatory("program_start")

            # Get the current rates and the program start time. If there
            # are more than one site, we simply add the start times.
            data = sites.live().query_summed_stats(
                "GET status\n" "Columns: service_checks_rate program_start"
            )
            current_rate = data[0]
            program_start = data[1]

            # Recompute the scheduled_rate only if it is not known (first call)
            # or if one of the sites has been restarted. The computed value cannot
            # change during the monitoring since it just reflects the configuration.
            # That way we save CPU resources since the computation of the
            # scheduled checks rate needs to loop over all hosts and services.
            if last_program_start != program_start:
                # These days, we configure the correct check interval for Checkmk checks.
                # We do this correctly for active and for passive ones. So we can simply
                # use the check_interval of all services. Hosts checks are ignored.
                #
                # Manually added services without check_interval could be a problem, but
                # we have no control there.
                scheduled_rate = (
                    sites.live().query_summed_stats(
                        "GET services\n" "Stats: suminv check_interval\n"
                    )[0]
                    / 60.0
                )

            percentage = 100.0 * current_rate / scheduled_rate
            title = _(
                "Scheduled service check rate: %.1f/s, current rate: %.1f/s, that is "
                "%.0f%% of the scheduled rate"
            ) % (scheduled_rate, current_rate, percentage)

        except Exception as e:
            scheduled_rate = 0.0
            program_start = 0
            percentage = 0
            last_perc = 0.0
            title = _("No performance data: %s") % e

        response.set_data(
            json.dumps(
                {
                    "scheduled_rate": scheduled_rate,
                    "program_start": program_start,
                    "percentage": percentage,
                    "last_perc": last_perc,
                    "title": title,
                }
            )
        )
Esempio n. 17
0
 def page(self):
     check_csrf_token()
     response.set_content_type("application/json")
     user_config = UserSidebarConfig(user, active_config.sidebar)
     user_config.folded = request.var("fold") == "yes"
     user_config.save()