예제 #1
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()
예제 #2
0
def test_output_funnel_context_raise(funnel: OutputFunnel) -> None:
    try:
        funnel.write(b"A")
        assert written(funnel) == b"A"
        with funnel.plugged():
            funnel.write(b"B")
            assert response_texts(funnel) == [["B"]]
            raise Exception("Test exception")
    except Exception as e:
        assert "%s" % e == "Test exception"
    finally:
        assert response_texts(funnel) == []
예제 #3
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()
예제 #4
0
파일: checkmk.py 프로젝트: bbaumer/checkmk
    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)
예제 #5
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)
예제 #6
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
예제 #7
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), display_options=DisplayOptions()), \
             cmk.utils.store.cleanup_locks(), \
             sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
예제 #8
0
def test_output_funnel_context_nesting(funnel: OutputFunnel) -> None:
    funnel.write(b"A")
    assert written(funnel) == b"A"
    with funnel.plugged():
        funnel.write(b"B")
        assert response_texts(funnel) == [["B"]]
        with funnel.plugged():
            funnel.write(b"C")
            assert response_texts(funnel) == [["B"], ["C"]]
        assert response_texts(funnel) == [["B", "C"]]
    assert written(funnel) == b"ABC"
예제 #9
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
예제 #10
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()),
             user=LoggedInNobody(),
             display_options=DisplayOptions(),
     ), cmk.utils.store.cleanup_locks(), sites.cleanup_connections():
         config.initialize()
         return app(environ, start_response)
예제 #11
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
예제 #12
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
예제 #13
0
def test_output_funnel_drain(funnel: OutputFunnel) -> None:
    with funnel.plugged():
        funnel.write(b"A")
        text = funnel.drain()
        assert text == "A"

        funnel.write(b"B")
        assert response_texts(funnel) == [["B"]]
    assert written(funnel) == b"B"
예제 #14
0
def test_output_funnel_2nd_plug(funnel: OutputFunnel) -> None:
    with funnel.plugged():
        funnel.write(b"B")
        assert response_texts(funnel) == [["B"]]
        with funnel.plugged():
            funnel.write(b"C")
            assert response_texts(funnel) == [["B"], ["C"]]
        assert response_texts(funnel) == [["B", "C"]]
    assert written(funnel) == b"BC"
예제 #15
0
def test_output_funnel_context_drain(funnel: OutputFunnel) -> None:
    funnel.write(b"A")
    assert written(funnel) == b"A"
    with funnel.plugged():
        funnel.write(b"B")
        assert response_texts(funnel) == [["B"]]
        code = funnel.drain()
        assert response_texts(funnel) == [[]]
    assert code == "B"
    assert written(funnel) == b"A"
예제 #16
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
예제 #17
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,
    )
예제 #18
0
def test_output_funnel_plugged(funnel: OutputFunnel) -> None:
    with funnel.plugged():
        funnel.write(b"B")
        assert response_texts(funnel) == [["B"]]
예제 #19
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)
예제 #20
0
def test_output_funnel_try_finally(funnel: OutputFunnel) -> None:
    try:
        funnel.write(b"try1\n")
        try:
            funnel.write(b"try2\n")
            raise Exception("Error")
        except Exception:
            funnel.write(b"except2\n")
            raise
        finally:
            funnel.write(b"finally2\n")
    except Exception as e:
        funnel.write(b"except1\n")
        funnel.write(str(e).encode("ascii") + b"\n")
    finally:
        funnel.write(b"finally1\n")
    assert written(
        funnel) == b"try1\ntry2\nexcept2\nfinally2\nexcept1\nError\nfinally1\n"
예제 #21
0
def test_output_funnel_not_plugged(funnel: OutputFunnel) -> None:
    funnel.write(b"A")
    assert written(funnel) == b"A"
예제 #22
0
def fixture_funnel() -> OutputFunnel:
    return OutputFunnel(Response())