Esempio n. 1
0
    def __call__(self, environ, start_response):
        # type: (Dict[str, str], Callable[..., Any]) -> _ScopedResponse
        if _wsgi_middleware_applied.get(False):
            return self.app(environ, start_response)

        _wsgi_middleware_applied.set(True)
        try:
            hub = Hub(Hub.current)

            with hub:
                with capture_internal_exceptions():
                    with hub.configure_scope() as scope:
                        scope.clear_breadcrumbs()
                        scope._name = "wsgi"
                        scope.add_event_processor(
                            _make_wsgi_event_processor(environ))

                span = Span.continue_from_environ(environ)
                span.op = "http.server"
                span.transaction = "generic WSGI request"

                with hub.start_span(span) as span:
                    try:
                        rv = self.app(
                            environ,
                            functools.partial(_sentry_start_response,
                                              start_response, span),
                        )
                    except BaseException:
                        reraise(*_capture_exception(hub))
        finally:
            _wsgi_middleware_applied.set(False)

        return _ScopedResponse(hub, rv)
Esempio n. 2
0
    def __call__(self, environ, start_response):
        # type: (Dict[str, str], Callable[..., Any]) -> _ScopedResponse
        if _wsgi_middleware_applied.get(False):
            return self.app(environ, start_response)

        _wsgi_middleware_applied.set(True)
        try:
            hub = Hub(Hub.current)
            with auto_session_tracking(hub, session_mode="request"):
                with hub:
                    with capture_internal_exceptions():
                        with hub.configure_scope() as scope:
                            scope.clear_breadcrumbs()
                            scope._name = "wsgi"
                            scope.add_event_processor(
                                _make_wsgi_event_processor(environ))

                    transaction = Transaction.continue_from_environ(
                        environ, op="http.server", name="generic WSGI request")

                    with hub.start_transaction(
                            transaction,
                            custom_sampling_context={"wsgi_environ": environ}):
                        try:
                            rv = self.app(
                                environ,
                                partial(_sentry_start_response, start_response,
                                        transaction),
                            )
                        except BaseException:
                            reraise(*_capture_exception(hub))
        finally:
            _wsgi_middleware_applied.set(False)

        return _ScopedResponse(hub, rv)
Esempio n. 3
0
    async def _run_app(self, scope, callback):
        # type: (Any, Any) -> Any
        if _asgi_middleware_applied.get(False):
            return await callback()

        _asgi_middleware_applied.set(True)
        try:
            hub = Hub(Hub.current)
            with hub:
                with hub.configure_scope() as sentry_scope:
                    sentry_scope.clear_breadcrumbs()
                    sentry_scope._name = "asgi"
                    processor = functools.partial(self.event_processor,
                                                  asgi_scope=scope)
                    sentry_scope.add_event_processor(processor)

                if scope["type"] in ("http", "websocket"):
                    span = Span.continue_from_headers(dict(scope["headers"]))
                    span.op = "{}.server".format(scope["type"])
                else:
                    span = Span()
                    span.op = "asgi.server"

                span.set_tag("asgi.type", scope["type"])
                span.transaction = "generic ASGI request"

                with hub.start_span(span) as span:
                    try:
                        return await callback()
                    except Exception as exc:
                        _capture_exception(hub, exc)
                        raise exc from None
        finally:
            _asgi_middleware_applied.set(False)
Esempio n. 4
0
    async def _run_app(self, scope, callback):
        # type: (Any, Any) -> Any
        is_recursive_asgi_middleware = _asgi_middleware_applied.get(False)

        if is_recursive_asgi_middleware:
            try:
                return await callback()
            except Exception as exc:
                _capture_exception(Hub.current, exc)
                raise exc from None

        _asgi_middleware_applied.set(True)
        try:
            hub = Hub(Hub.current)
            with auto_session_tracking(hub, session_mode="request"):
                with hub:
                    with hub.configure_scope() as sentry_scope:
                        sentry_scope.clear_breadcrumbs()
                        sentry_scope._name = "asgi"
                        processor = partial(self.event_processor,
                                            asgi_scope=scope)
                        sentry_scope.add_event_processor(processor)

                    ty = scope["type"]

                    if ty in ("http", "websocket"):
                        transaction = Transaction.continue_from_headers(
                            self._get_headers(scope),
                            op="{}.server".format(ty),
                        )
                    else:
                        transaction = Transaction(op="asgi.server")

                    transaction.name = _DEFAULT_TRANSACTION_NAME
                    transaction.set_tag("asgi.type", ty)

                    with hub.start_transaction(
                            transaction,
                            custom_sampling_context={"asgi_scope": scope}):
                        # XXX: Would be cool to have correct span status, but we
                        # would have to wrap send(). That is a bit hard to do with
                        # the current abstraction over ASGI 2/3.
                        try:
                            return await callback()
                        except Exception as exc:
                            _capture_exception(hub, exc)
                            raise exc from None
        finally:
            _asgi_middleware_applied.set(False)
Esempio n. 5
0
            async def inner():
                # type: () -> Any
                hub = Hub.current
                if hub.get_integration(AioHttpIntegration) is None:
                    return await old_handle(self, request, *args, **kwargs)

                weak_request = weakref.ref(request)

                with Hub(Hub.current) as hub:
                    with hub.configure_scope() as scope:
                        scope.clear_breadcrumbs()
                        scope.add_event_processor(
                            _make_request_processor(weak_request))

                    span = Span.continue_from_headers(request.headers)
                    span.op = "http.server"
                    # If this transaction name makes it to the UI, AIOHTTP's
                    # URL resolver did not find a route or died trying.
                    span.transaction = "generic AIOHTTP request"

                    with hub.start_span(span):
                        try:
                            response = await old_handle(self, request)
                        except HTTPException as e:
                            span.set_http_status(e.status_code)
                            raise
                        except Exception:
                            # This will probably map to a 500 but seems like we
                            # have no way to tell. Do not set span status.
                            reraise(*_capture_exception(hub))

                        span.set_http_status(response.status)
                        return response
Esempio n. 6
0
    def __call__(self, environ, start_response):
        hub = Hub(Hub.current)

        with hub:
            with capture_internal_exceptions():
                with hub.configure_scope() as scope:
                    scope._name = "wsgi"
                    scope.add_event_processor(
                        _make_wsgi_event_processor(environ))

            try:
                rv = self.app(environ, start_response)
            except Exception:
                reraise(*_capture_exception(hub))

        return _ScopedResponse(hub, rv)
Esempio n. 7
0
def _handle_request_impl(self):
    # type: (RequestHandler) -> Generator[None, None, None]
    hub = Hub.current
    integration = hub.get_integration(TornadoIntegration)

    if integration is None:
        yield

    weak_handler = weakref.ref(self)

    with Hub(hub) as hub:
        with hub.configure_scope() as scope:
            scope.clear_breadcrumbs()
            processor = _make_event_processor(weak_handler)  # type: ignore
            scope.add_event_processor(processor)

        transaction = Transaction.continue_from_headers(
            self.request.headers,
            op="http.server",
            # Like with all other integrations, this is our
            # fallback transaction in case there is no route.
            # sentry_urldispatcher_resolve is responsible for
            # setting a transaction name later.
            name="generic Tornado request",
        )

        with hub.start_transaction(
            transaction, custom_sampling_context={"tornado_request": self.request}
        ):
            yield
Esempio n. 8
0
            async def inner():
                # type: () -> Any
                hub = Hub.current
                if hub.get_integration(AioHttpIntegration) is None:
                    return await old_handle(self, request, *args, **kwargs)

                weak_request = weakref.ref(request)

                with Hub(Hub.current) as hub:
                    with hub.configure_scope() as scope:
                        scope.clear_breadcrumbs()
                        scope.add_event_processor(
                            _make_request_processor(weak_request))

                    # If this transaction name makes it to the UI, AIOHTTP's
                    # URL resolver did not find a route or died trying.
                    with hub.start_span(transaction="generic AIOHTTP request"):
                        try:
                            response = await old_handle(self, request)
                        except HTTPException:
                            raise
                        except Exception:
                            reraise(*_capture_exception(hub))

                        return response
Esempio n. 9
0
async def cobraHandlerWrapper(websocket, path, app, redisUrls: str):
    userAgent = websocket.requestHeaders.get('User-Agent',
                                             'unknown-user-agent')

    with Hub(Hub.current):
        with configure_scope() as scope:
            scope.set_tag("user_agent", userAgent)
            await cobraHandler(websocket, path, app, redisUrls, userAgent)
Esempio n. 10
0
 async def wrap(*args, **kwargs):
     with Hub(Hub.current) as hub:
         with hub.push_scope() as scope:
             scope.add_event_processor(_process_ws)
             for key, builder in ext._scopes.items():
                 scope.set_extra(key, await builder())
             try:
                 return await dispatch_method(*args, **kwargs)
             except Exception as exc:
                 _capture_exception(hub, exc)
                 raise
Esempio n. 11
0
    def __call__(self, environ, start_response):
        # type: (Dict[str, str], Callable) -> _ScopedResponse
        hub = Hub(Hub.current)

        with hub:
            with capture_internal_exceptions():
                with hub.configure_scope() as scope:
                    scope.clear_breadcrumbs()
                    scope._name = "wsgi"
                    scope.set_span_context(
                        SpanContext.continue_from_environ(environ))
                    scope.add_event_processor(
                        _make_wsgi_event_processor(environ))

            try:
                rv = self.app(environ, start_response)
            except BaseException:
                reraise(*_capture_exception(hub))

        return _ScopedResponse(hub, rv)
Esempio n. 12
0
            async def sentry_execute_request_handler(self, *args, **kwargs):
                hub = Hub.current
                integration = hub.get_integration(TornadoIntegration)
                if integration is None:
                    return await old_execute(self, *args, **kwargs)

                weak_handler = weakref.ref(self)

                with Hub(hub) as hub:
                    with hub.configure_scope() as scope:
                        scope.add_event_processor(_make_event_processor(weak_handler))
                    return await old_execute(self, *args, **kwargs)
Esempio n. 13
0
        def inner(*args, **kwargs):
            with Hub(Hub.current) as hub:
                with hub.configure_scope() as scope:
                    scope.clear_breadcrumbs()

                try:
                    return f(*args, **kwargs)
                except Exception:
                    _capture_and_reraise()
                finally:
                    if flush:
                        _flush_client()
Esempio n. 14
0
        async def sentry_execute_request_handler(self, *args, **kwargs):
            # type: (Any, *Any, **Any) -> Any
            hub = Hub.current

            weak_handler = weakref.ref(self)

            with Hub(hub) as hub:
                with hub.configure_scope() as scope:
                    scope.clear_breadcrumbs()
                    processor = _make_event_processor(weak_handler)
                    scope.add_event_processor(processor)
                return await old_execute(self, *args, **kwargs)
Esempio n. 15
0
    def _run_app(self, scope, callback):
        # type: (Any, Any) -> Any
        if _asgi_middleware_applied.get(False):
            response = yield from callback()
            return response

        _asgi_middleware_applied.set(True)
        try:
            hub = Hub(Hub.current)
            with hub:
                with hub.configure_scope() as sentry_scope:
                    sentry_scope.clear_breadcrumbs()
                    sentry_scope._name = "asgi"
                    processor = functools.partial(self.event_processor,
                                                  asgi_scope=scope)
                    sentry_scope.add_event_processor(processor)

                if scope["type"] in ("http", "websocket"):
                    span = Span.continue_from_headers(dict(scope["headers"]))
                    span.op = "{}.server".format(scope["type"])
                else:
                    span = Span()
                    span.op = "asgi.server"

                span.set_tag("asgi.type", scope["type"])
                span.transaction = "generic ASGI request"

                with hub.start_span(span) as span:
                    # XXX: Would be cool to have correct span status, but we
                    # would have to wrap send(). That is a bit hard to do with
                    # the current abstraction over ASGI 2/3.
                    try:
                        response = yield from callback()
                        return response
                    except Exception as exc:
                        _capture_exception(hub, exc)
                        raise exc from None
        finally:
            _asgi_middleware_applied.set(False)
Esempio n. 16
0
            def sentry_execute_request_handler(self, *args, **kwargs):
                # type: (RequestHandler, *Any, **Any) -> Any
                hub = Hub.current
                integration = hub.get_integration(TornadoIntegration)
                if integration is None:
                    return old_execute(self, *args, **kwargs)

                weak_handler = weakref.ref(self)

                with Hub(hub) as hub:
                    with hub.configure_scope() as scope:
                        scope.add_event_processor(_make_event_processor(weak_handler))
                    result = yield from old_execute(self, *args, **kwargs)
                    return result
Esempio n. 17
0
    def __call__(self, environ, start_response):
        # type: (Dict[str, str], Callable) -> _ScopedResponse
        hub = Hub(Hub.current)

        with hub:
            with capture_internal_exceptions():
                with hub.configure_scope() as scope:
                    scope.clear_breadcrumbs()
                    scope._name = "wsgi"
                    scope.add_event_processor(
                        _make_wsgi_event_processor(environ))

            span = Span.continue_from_environ(environ)
            span.op = "http.server"
            span.transaction = "generic WSGI request"

            with hub.span(span):
                try:
                    rv = self.app(environ, start_response)
                except BaseException:
                    reraise(*_capture_exception(hub))

        return _ScopedResponse(hub, rv)
Esempio n. 18
0
            async def sentry_execute_request_handler(self, *args, **kwargs):
                # type: (Any, *Any, **Any) -> Any
                hub = Hub.current
                integration = hub.get_integration(TornadoIntegration)
                if integration is None:
                    return await old_execute(self, *args, **kwargs)

                weak_handler = weakref.ref(self)

                with Hub(hub) as hub:
                    with hub.configure_scope() as scope:
                        scope.clear_breadcrumbs()
                        processor = _make_event_processor(weak_handler)  # type: ignore
                        scope.add_event_processor(processor)
                    return await old_execute(self, *args, **kwargs)
Esempio n. 19
0
 async def wrap(*args, **kwargs):
     with Hub(Hub.current) as hub:
         with hub.push_scope() as scope:
             scope.add_event_processor(_process_http)
             for key, builder in ext._scopes.items():
                 scope.set_extra(key, await builder())
             try:
                 return await dispatch_method(*args, **kwargs)
             except HTTPResponse:
                 raise
             except Exception as exc:
                 scope.set_extra("body_params", await
                                 current.request.body_params)
                 _capture_exception(hub, exc)
                 raise
Esempio n. 20
0
        async def sentry_handle_request(self, request, *args, **kwargs):
            hub = Hub.current
            if hub.get_integration(SanicIntegration) is None:
                return old_handle_request(self, request, *args, **kwargs)

            weak_request = weakref.ref(request)

            with Hub(hub) as hub:
                with hub.configure_scope() as scope:
                    scope.add_event_processor(_make_request_processor(weak_request))

                response = old_handle_request(self, request, *args, **kwargs)
                if isawaitable(response):
                    response = await response

                return response
Esempio n. 21
0
    async def wrap(*args, **kwargs):
        with Hub(Hub.current) as hub:
            with hub.push_scope() as scope:
                scope.add_event_processor(_process_ws)
                for key, builder in ext._scopes.items():
                    scope.set_extra(key, await builder())

                txn = Transaction.continue_from_headers(
                    current.request._scope["headers"], op="websocket.server")
                txn.set_tag("asgi.type", "websocket")

                with hub.start_transaction(txn):
                    try:
                        return await dispatch_method(*args, **kwargs)
                    except Exception as exc:
                        _capture_exception(hub, exc)
                        raise
Esempio n. 22
0
    async def _run_app(self, scope, callback):
        hub = Hub.current
        with Hub(hub) as hub:
            with hub.configure_scope() as sentry_scope:
                sentry_scope._name = "asgi"
                sentry_scope.transaction = scope.get(
                    "path") or "unknown asgi request"

                processor = functools.partial(self.event_processor,
                                              asgi_scope=scope)
                sentry_scope.add_event_processor(processor)

            try:
                await callback()
            except Exception as exc:
                hub.capture_exception(exc)
                raise exc from None
Esempio n. 23
0
async def _hub_enter(request):
    # type: (Request) -> None
    hub = Hub.current
    request.ctx._sentry_do_integration = (
        hub.get_integration(SanicIntegration) is not None
    )

    if not request.ctx._sentry_do_integration:
        return

    weak_request = weakref.ref(request)
    request.ctx._sentry_hub = Hub(hub)
    request.ctx._sentry_hub.__enter__()

    with request.ctx._sentry_hub.configure_scope() as scope:
        scope.clear_breadcrumbs()
        scope.add_event_processor(_make_request_processor(weak_request))
Esempio n. 24
0
async def _legacy_handle_request(self, request, *args, **kwargs):
    # type: (Any, Request, *Any, **Any) -> Any
    hub = Hub.current
    if hub.get_integration(SanicIntegration) is None:
        return old_handle_request(self, request, *args, **kwargs)

    weak_request = weakref.ref(request)

    with Hub(hub) as hub:
        with hub.configure_scope() as scope:
            scope.clear_breadcrumbs()
            scope.add_event_processor(_make_request_processor(weak_request))

        response = old_handle_request(self, request, *args, **kwargs)
        if isawaitable(response):
            response = await response

        return response
Esempio n. 25
0
            async def inner():
                hub = Hub.current
                if hub.get_integration(AioHttpIntegration) is None:
                    return old_handle(self, request, *args, **kwargs)

                weak_request = weakref.ref(request)

                with Hub(Hub.current) as hub:
                    with hub.configure_scope() as scope:
                        scope.add_event_processor(_make_request_processor(weak_request))

                    try:
                        response = await old_handle(self, request)
                    except HTTPException:
                        raise
                    except Exception:
                        reraise(*_capture_exception(hub))

                    return response
Esempio n. 26
0
        async def sentry_app_handle(self, request, *args, **kwargs):
            # type: (Any, Request, *Any, **Any) -> Any
            hub = Hub.current
            if hub.get_integration(AioHttpIntegration) is None:
                return await old_handle(self, request, *args, **kwargs)

            weak_request = weakref.ref(request)

            with Hub(hub) as hub:
                # Scope data will not leak between requests because aiohttp
                # create a task to wrap each request.
                with hub.configure_scope() as scope:
                    scope.clear_breadcrumbs()
                    scope.add_event_processor(
                        _make_request_processor(weak_request))

                transaction = Transaction.continue_from_headers(
                    request.headers,
                    op="http.server",
                    # If this transaction name makes it to the UI, AIOHTTP's
                    # URL resolver did not find a route or died trying.
                    name="generic AIOHTTP request",
                )
                with hub.start_transaction(
                        transaction,
                        custom_sampling_context={"aiohttp_request": request}):
                    try:
                        response = await old_handle(self, request)
                    except HTTPException as e:
                        transaction.set_http_status(e.status_code)
                        raise
                    except (asyncio.CancelledError, ConnectionResetError):
                        transaction.set_status("cancelled")
                        raise
                    except Exception:
                        # This will probably map to a 500 but seems like we
                        # have no way to tell. Do not set span status.
                        reraise(*_capture_exception(hub))

                    transaction.set_http_status(response.status)
                    return response
Esempio n. 27
0
        def sentry_patched_perform_job(self, job, *args, **kwargs):
            hub = Hub.current
            integration = hub.get_integration(RqIntegration)

            if integration is None:
                return old_perform_job(self, job, *args, **kwargs)

            with Hub(hub) as hub:
                with hub.configure_scope() as scope:
                    scope.add_event_processor(
                        _make_event_processor(weakref.ref(job)))
                    rv = old_perform_job(self, job, *args, **kwargs)

            if self.is_horse:
                # We're inside of a forked process and RQ is
                # about to call `os._exit`. Make sure that our
                # events get sent out.
                #
                # Closing the client should not affect other jobs since
                # we're in a different process
                hub.client.close()

            return rv
Esempio n. 28
0
def capture_message(message, level):
    with Hub(Hub.current) as hub:
        _capture_message(hub, message, level=level)
Esempio n. 29
0
def capture_exception(exception):
    with Hub(Hub.current) as hub:
        _capture_exception(hub, exception)
Esempio n. 30
0
logger = logging.getLogger(__name__)

_client = Client(
    dsn=SENTRY_DSN,
    default_integrations=False,
    integrations=[
        ExcepthookIntegration(),
        DedupeIntegration(),
        StdlibIntegration(),
        ModulesIntegration(),
        ArgvIntegration(),
    ],
    max_breadcrumbs=5,
    attach_stacktrace=True,
)
_hub = Hub(_client)


def report(msg=None, **kw):
    if not _hub:
        return
    try:
        extra = kw.pop('extra', {})

        with sentry_sdk.push_scope() as scope:
            for k, v in extra.items():
                scope.set_extra(k, v)
            scope.level = kw.pop('level', logging.ERROR)

            if 'user' in kw:
                scope.user = kw.get('user')