Esempio n. 1
0
    def run(self):

        self._logger.log(VERBOSE, "Initializing application...")
        environ = dict(create_environ(), REQUEST_URI='')

        this_html = htmllib.html(Request(environ))
        # Currently the htmllib.html constructor enables the timeout by default. This side effect
        # should really be cleaned up.
        this_html.disable_request_timeout()

        with AppContext(DummyApplication(environ, None)), RequestContext(
                this_html,
                display_options=DisplayOptions(),
                prefix_logs_with_url=False):
            self._initialize_gui_environment()
            self._initialize_base_environment()

            self._logger.log(VERBOSE, "Updating Checkmk configuration...")
            for step_func, title in self._steps():
                self._logger.log(VERBOSE, " + %s..." % title)
                try:
                    step_func()
                except Exception:
                    self._logger.error(" + \"%s\" failed" % title,
                                       exc_info=True)
                    if self._arguments.debug:
                        raise

        self._logger.log(VERBOSE, "Done")
Esempio n. 2
0
    def __call__(self, environ: WSGIEnvironment,
                 start_response: StartResponse) -> WSGIResponse:
        req = http.Request(environ)

        output_format = get_output_format(
            req.get_ascii_input_mandatory("output_format", "html").lower())
        mime_type = get_mime_type_from_output_format(output_format)

        resp = Response(headers=default_response_headers(req),
                        mimetype=mime_type)
        funnel = OutputFunnel(resp)

        timeout_manager = TimeoutManager()
        timeout_manager.enable_timeout(req.request_timeout)

        theme = Theme()
        config_obj = config_module.make_config_object(
            config_module.get_default_config())

        with AppContext(self), RequestContext(
                req=req,
                resp=resp,
                funnel=funnel,
                config_obj=config_obj,
                user=LoggedInNobody(),
                html_obj=htmllib.html(req, resp, funnel, output_format),
                timeout_manager=timeout_manager,
                display_options=DisplayOptions(),
                theme=theme,
        ), patch_json(json):
            config_module.initialize()
            theme.from_config(config.ui_theme)
            return self.wsgi_app(environ, start_response)
Esempio n. 3
0
    def __call__(self, environ, start_response):
        req = http.Request(environ)

        output_format = get_output_format(
            req.get_ascii_input_mandatory("output_format", "html").lower())
        mime_type = get_mime_type_from_output_format(output_format)

        resp = Response(headers=default_response_headers(req),
                        mimetype=mime_type)
        funnel = OutputFunnel(resp)

        timeout_manager = TimeoutManager()
        timeout_manager.enable_timeout(req.request_timeout)

        theme = Theme()

        with AppContext(self), RequestContext(
                req=req,
                resp=resp,
                funnel=funnel,
                html_obj=htmllib.html(req, resp, funnel, output_format),
                timeout_manager=timeout_manager,
                display_options=DisplayOptions(),
                theme=theme,
        ), patch_json(json):
            config.initialize()
            theme.from_config(config.ui_theme, config.theme_choices())
            return self.wsgi_app(environ, start_response)
Esempio n. 4
0
def mock_livestatus(with_context=False):
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)

    app_context: ContextManager
    req_context: ContextManager
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(
            req=req,
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=live.enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        yield live
Esempio n. 5
0
 def __call__(self, environ, start_response) -> Response:
     req = http.Request(environ)
     with AppContext(self), RequestContext(req=req,
                                           display_options=DisplayOptions(),
                                           html_obj=htmllib.html(req)):
         config.initialize()
         return _process_request(environ, start_response)
Esempio n. 6
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), \
             RequestContext(req=req, display_options=DisplayOptions()), \
             cmk.utils.store.cleanup_locks(), \
             sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
Esempio n. 7
0
def module_wide_request_context():
    # This one is kind of an hack because some other test-fixtures touch the user object AFTER the
    # request context has already ended. If we increase our scope this won't matter, but it is of
    # course wrong. These other fixtures have to be fixed.
    environ = create_environ()
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(Request(environ)), display_options=DisplayOptions()):
        yield
Esempio n. 8
0
 def _SearchContext(self) -> Iterator[None]:
     _request = Request(create_environ())
     with RequestContext(
             html_obj=html(_request),
             req=_request,
             display_options=DisplayOptions(),
     ), UserContext(self._user_id):
         yield
Esempio n. 9
0
def mock_livestatus(
    with_context: bool = False,
    with_html: bool = False
) -> Generator[MockLiveStatusConnection, None, None]:
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)
    resp = http.Response()

    app_context: ContextManager
    req_context: ContextManager
    if with_html:
        html_obj = None
    else:
        html_obj = HTMLGenerator(
            request=req,
            output_funnel=OutputFunnel(resp),
            output_format="html",
            mobile=is_mobile(req, resp),
        )
    if with_context:
        app_context = AppContext(None, stack=app_stack())
        req_context = RequestContext(
            html_obj=html_obj,
            req=req,
            resp=resp,
            funnel=OutputFunnel(resp),
            config_obj=make_config_object(get_default_config()),
            user=LoggedInNobody(),
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
            stack=request_stack(),
            url_filter=PrependURLFilter(),
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, mock.patch(
            "cmk.gui.sites._get_enabled_and_disabled_sites",
            new=live.enabled_and_disabled_sites), mock.patch(
                "livestatus.MultiSiteConnection.expect_query",
                new=live.expect_query,
                create=True), mock.patch(
                    "livestatus.SingleSiteConnection._create_socket",
                    new=live.create_socket), mock.patch.dict(
                        os.environ, {
                            "OMD_ROOT": "/",
                            "OMD_SITE": "NO_SITE"
                        }):

        # We don't want to be polluted by other tests.
        omd_site.cache_clear()
        yield live
        # We don't want to pollute other tests.
        omd_site.cache_clear()
Esempio n. 10
0
def with_request_context():
    environ = create_environ()
    resp = Response()
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(req=Request(environ),
                           resp=resp,
                           funnel=OutputFunnel(resp),
                           display_options=DisplayOptions()):
        yield
Esempio n. 11
0
 def __call__(self, environ, start_response):
     req = http.Request(environ)
     with AppContext(self), RequestContext(
             req=req,
             html_obj=htmllib.html(req),
             display_options=DisplayOptions(),
     ):
         config.initialize()
         html.init_modes()
         return self.wsgi_app(environ, start_response)
Esempio n. 12
0
def with_request_context():
    environ = create_environ()
    resp = Response()
    with AppContext(session_wsgi_app(debug=False)), RequestContext(
            req=Request(environ),
            resp=resp,
            funnel=OutputFunnel(resp),
            config_obj=make_config_object(get_default_config()),
            display_options=DisplayOptions(),
    ):
        yield
Esempio n. 13
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     resp = http.Response()
     with AppContext(app), \
             RequestContext(req=req, resp=resp, funnel=OutputFunnel(resp),
                            config_obj=config.make_config_object(config.get_default_config()),
                            display_options=DisplayOptions()), \
             cmk.utils.store.cleanup_locks(), \
             sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
Esempio n. 14
0
def request_context(environ: Mapping[str, Any]) -> Iterator[None]:
    this_html = html(Request(environ))

    # Currently the htmllib.html constructor enables the timeout by default. This side effect
    # should really be cleaned up.
    this_html.disable_request_timeout()

    with RequestContext(
            this_html,
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
    ):
        yield
Esempio n. 15
0
def with_request_context():
    environ = create_environ()
    resp = Response()
    with AppContext(session_wsgi_app(debug=False), stack=app_stack()), RequestContext(
        req=Request(environ),
        resp=resp,
        funnel=OutputFunnel(resp),
        config_obj=make_config_object(get_default_config()),
        user=LoggedInNobody(),
        display_options=DisplayOptions(),
        stack=request_stack(),
        url_filter=PrependURLFilter(),
    ):
        yield
Esempio n. 16
0
def request_context(environ: Mapping[str, Any]) -> Iterator[None]:
    req = Request(environ)
    resp = Response(mimetype="text/html")
    funnel = OutputFunnel(resp)
    with RequestContext(
            req=req,
            resp=resp,
            funnel=funnel,
            html_obj=html(req, resp, funnel, output_format="html"),
            display_options=DisplayOptions(),
            theme=Theme(),
            prefix_logs_with_url=False,
    ):
        yield
Esempio n. 17
0
def mock_livestatus(
    with_context: bool = False,
    with_html: bool = False
) -> Generator[MockLiveStatusConnection, None, None]:
    live = MockLiveStatusConnection()

    env = EnvironBuilder().get_environ()
    req = http.Request(env)
    resp = http.Response()

    app_context: ContextManager
    req_context: ContextManager
    if with_html:
        html_obj = None
    else:
        html_obj = html(
            request=req,
            response=resp,
            output_funnel=OutputFunnel(resp),
            output_format="html",
        )
    if with_context:
        app_context = AppContext(None)
        req_context = RequestContext(
            html_obj=html_obj,
            req=req,
            resp=resp,
            funnel=OutputFunnel(resp),
            display_options=DisplayOptions(),
            prefix_logs_with_url=False,
        )
    else:
        app_context = contextlib.nullcontext()
        req_context = contextlib.nullcontext()

    with app_context, req_context, \
         mock.patch("cmk.gui.sites._get_enabled_and_disabled_sites",
                    new=live.enabled_and_disabled_sites), \
         mock.patch("livestatus.MultiSiteConnection.set_prepend_site",
                    new=live.set_prepend_site), \
         mock.patch("livestatus.MultiSiteConnection.expect_query",
                    new=live.expect_query, create=True), \
         mock.patch("livestatus.SingleSiteConnection._create_socket", new=live.create_socket), \
         mock.patch.dict(os.environ, {'OMD_ROOT': '/', 'OMD_SITE': 'NO_SITE'}):

        # We don't want to be polluted by other tests.
        version.omd_site.cache_clear()
        yield live
        # We don't want to pollute other tests.
        version.omd_site.cache_clear()
Esempio n. 18
0
 def _SearchContext(self) -> Iterator[None]:
     _request = Request(create_environ())
     _response = Response()
     _funnel = OutputFunnel(_response)
     _theme = Theme()
     _theme.from_config(config.ui_theme, config.theme_choices())
     with RequestContext(
             req=_request,
             resp=_response,
             funnel=_funnel,
             html_obj=html(_request,
                           _response,
                           _funnel,
                           output_format="html"),
             display_options=DisplayOptions(),
             theme=_theme,
     ), UserContext(self._user_id):
         yield
Esempio n. 19
0
def make_request_context(
        environ: Optional[Mapping[str, Any]] = None) -> RequestContext:
    req = Request(
        dict(create_environ(), REQUEST_URI="") if environ is None else environ)
    resp = Response(mimetype="text/html")
    funnel = OutputFunnel(resp)
    return RequestContext(
        req=req,
        resp=resp,
        funnel=funnel,
        config_obj=make_config_object(get_default_config()),
        user=LoggedInNobody(),
        html_obj=html(req, resp, funnel, output_format="html"),
        display_options=DisplayOptions(),
        timeout_manager=TimeoutManager(),
        theme=Theme(),
        prefix_logs_with_url=False,
    )
Esempio n. 20
0
def register_builtin_html():
    """This fixture registers a global htmllib.html() instance just like the regular GUI"""
    environ = create_environ()
    with AppContext(DummyApplication(environ, None)), \
            RequestContext(htmllib.html(Request(environ)), display_options=DisplayOptions()):
        yield
Esempio n. 21
0
    def _wsgi_app(self, environ: WSGIEnvironment,
                  start_response: StartResponse) -> WSGIResponse:
        urls = self.url_map.bind_to_environ(environ)
        endpoint: Optional[Endpoint] = None
        try:
            result: Tuple[str, Mapping[str,
                                       Any]] = urls.match(return_rule=False)
            endpoint_ident, matched_path_args = result  # pylint: disable=unpacking-non-sequence
            wsgi_app = self.endpoints[endpoint_ident]
            if isinstance(wsgi_app, Authenticate):
                endpoint = wsgi_app.endpoint

            # Remove _path again (see Submount above), so the validators don't go crazy.
            path_args = {
                key: value
                for key, value in matched_path_args.items() if key != "_path"
            }

            # This is an implicit dependency, as we only know the args at runtime, but the
            # function at setup-time.
            environ[ARGS_KEY] = path_args

            req = Request(environ)
            resp = Response()
            with AppContext(self, stack=app_stack()), RequestContext(
                    req=req,
                    resp=resp,
                    funnel=OutputFunnel(resp),
                    config_obj=config.make_config_object(
                        config.get_default_config()),
                    endpoint=endpoint,
                    user=LoggedInNobody(),
                    display_options=DisplayOptions(),
                    stack=request_stack(),
                    url_filter=PrependURLFilter(),
            ), cmk.utils.store.cleanup_locks(), sites.cleanup_connections():
                config.initialize()
                load_dynamic_permissions()
                return wsgi_app(environ, start_response)
        except ProblemException as exc:
            return exc(environ, start_response)
        except HTTPException as exc:
            # We don't want to log explicit HTTPExceptions as these are intentional.
            assert isinstance(exc.code, int)
            return problem(
                status=exc.code,
                title=http.client.responses[exc.code],
                detail=str(exc),
            )(environ, start_response)
        except MKException as exc:
            if self.debug:
                raise

            return problem(
                status=EXCEPTION_STATUS.get(type(exc), 500),
                title="An exception occurred.",
                detail=str(exc),
            )(environ, start_response)
        except Exception as exc:
            crash = APICrashReport.from_exception()
            crash_reporting.CrashReportStore().save(crash)
            logger.exception("Unhandled exception (Crash-ID: %s)",
                             crash.ident_to_text())
            if self.debug:
                raise

            request = Request(environ)
            site = config.omd_site()
            query_string = urllib.parse.urlencode([
                ("crash_id", (crash.ident_to_text())),
                ("site", site),
            ])
            crash_url = f"{request.host_url}{site}/check_mk/crash.py?{query_string}"
            crash_details = {
                "crash_id": (crash.ident_to_text()),
                "crash_report": {
                    "href": crash_url,
                    "method": "get",
                    "rel": "cmk/crash-report",
                    "type": "text/html",
                },
            }
            if user.may("general.see_crash_reports"):
                crash_details["stack_trace"] = traceback.format_exc().split(
                    "\n")

            return problem(
                status=500,
                title=http.client.responses[500],
                detail=str(exc),
                ext=crash_details,
            )(environ, start_response)
Esempio n. 22
0
 def with_context(environ, start_response):
     req = http.Request(environ)
     with AppContext(app), RequestContext(req=req,
                                          display_options=DisplayOptions()):
         config.initialize()
         return app(environ, start_response)