コード例 #1
0
    def test_disable_tracing_url_default(self):
        url = 'http://127.0.0.1:8080/_ah/health'
        disable_tracing = utils.disable_tracing_url(url)
        self.assertTrue(disable_tracing)

        url = 'http://127.0.0.1:8080/mysql'
        disable_tracing = utils.disable_tracing_url(url)
        self.assertFalse(disable_tracing)
コード例 #2
0
    def _before_request(self, request):
        if utils.disable_tracing_url(request.path, self._blacklist_paths):
            return

        try:
            span_context = self.propagator.from_headers(request.headers)

            tracer = tracer_module.Tracer(span_context=span_context,
                                          sampler=self.sampler,
                                          exporter=self.exporter,
                                          propagator=self.propagator)

            span = tracer.start_span()

            # Set the span name as the name of the current module name
            span.name = '[{}]{}'.format(request.method, request.path)

            span.span_kind = span_module.SpanKind.SERVER
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_HOST, attribute_value=request.host_url)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_METHOD, attribute_value=request.method)
            tracer.add_attribute_to_current_span(attribute_key=HTTP_PATH,
                                                 attribute_value=request.path)
            tracer.add_attribute_to_current_span(attribute_key=HTTP_ROUTE,
                                                 attribute_value=request.path)
            tracer.add_attribute_to_current_span(attribute_key=HTTP_URL,
                                                 attribute_value=request.url)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #3
0
    def process_exception(self, request, exception):
        # Do not trace if the url is excluded
        if utils.disable_tracing_url(request.path, self.excludelist_paths):
            return

        try:
            if hasattr(exception, '__traceback__'):
                tb = exception.__traceback__
            else:
                _, _, tb = sys.exc_info()

            span = _get_django_span()
            span.add_attribute(
                attribute_key=ERROR_NAME,
                attribute_value=exception.__class__.__name__)
            span.add_attribute(
                attribute_key=ERROR_MESSAGE,
                attribute_value=str(exception))
            span.add_attribute(
                attribute_key=STACKTRACE,
                attribute_value='\n'.join(traceback.format_tb(tb)))

            _set_django_attributes(span, request)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #4
0
    def _before_request(self):
        """A function to be run before each request.

        See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
        """
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return

        try:
            span_context = self.propagator.from_headers(flask.request.headers)

            tracer = tracer_module.Tracer(span_context=span_context,
                                          sampler=self.sampler,
                                          exporter=self.exporter,
                                          propagator=self.propagator)

            span = tracer.start_span()
            span.span_kind = span_module.SpanKind.SERVER
            # Set the span name as the name of the current module name
            span.name = '[{}]{}'.format(flask.request.method,
                                        flask.request.url)
            tracer.add_attribute_to_current_span(HTTP_HOST, flask.request.host)
            tracer.add_attribute_to_current_span(HTTP_METHOD,
                                                 flask.request.method)
            tracer.add_attribute_to_current_span(HTTP_PATH, flask.request.path)
            tracer.add_attribute_to_current_span(HTTP_URL,
                                                 str(flask.request.url))
            execution_context.set_opencensus_attr('blacklist_hostnames',
                                                  self.blacklist_hostnames)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #5
0
    def _teardown_request(self, exception):
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return

        try:
            tracer = execution_context.get_opencensus_tracer()

            if exception is not None:
                span = execution_context.get_current_span()
                if span is not None:
                    span.status = status.Status(
                        code=code_pb2.UNKNOWN,
                        message=str(exception)
                    )
                    # try attaching the stack trace to the span, only populated
                    # if the app has 'PROPAGATE_EXCEPTIONS', 'DEBUG', or
                    # 'TESTING' enabled
                    exc_type, _, exc_traceback = sys.exc_info()
                    if exc_traceback is not None:
                        span.stack_trace = (
                            stack_trace.StackTrace.from_traceback(
                                exc_traceback
                            )
                        )

            tracer.end_span()
            tracer.finish()
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #6
0
    def process_response(self, request, response):
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(request.path, self._blacklist_paths):
            return response

        try:
            span = _get_django_span()
            span.add_attribute(attribute_key=HTTP_STATUS_CODE,
                               attribute_value=str(response.status_code))
            set_attributes_method = settings.params.get(
                JAEGER_SET_ATTRIBUTES, '')
            try:
                set_attributes = import_from_string(set_attributes_method,
                                                    JAEGER_SET_ATTRIBUTES)
            except (ImportError, Exception):
                _set_django_attributes(span, request)
            else:
                set_attributes(span, request)

            tracer = _get_current_tracer()
            tracer.end_span()
            tracer.finish()
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
        finally:
            return response
コード例 #7
0
 def _before_request(self):
     """A function to be run before each request.
     See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.before_request
     """
     # Do not record stats if the url is blacklisted
     if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
         return
コード例 #8
0
    def process_request(self, request):
        """Called on each request, before Django decides which view to execute.

        :type request: :class:`~django.http.request.HttpRequest`
        :param request: Django http request.
        """
        # Do not trace if the url is excludelisted
        if utils.disable_tracing_url(request.path, self.excludelist_paths):
            return

        # Add the request to thread local
        execution_context.set_opencensus_attr(REQUEST_THREAD_LOCAL_KEY,
                                              request)

        execution_context.set_opencensus_attr('excludelist_hostnames',
                                              self.excludelist_hostnames)

        try:
            # Start tracing this request
            span_context = self.propagator.from_headers(
                _DjangoMetaWrapper(_get_django_request().META))

            # Reload the tracer with the new span context
            tracer = tracer_module.Tracer(span_context=span_context,
                                          sampler=self.sampler,
                                          exporter=self.exporter,
                                          propagator=self.propagator)

            # Span name is being set at process_view
            span = tracer.start_span()
            span.span_kind = span_module.SpanKind.SERVER
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_HOST, attribute_value=request.get_host())
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_METHOD, attribute_value=request.method)
            tracer.add_attribute_to_current_span(attribute_key=HTTP_PATH,
                                                 attribute_value=str(
                                                     request.path))
            tracer.add_attribute_to_current_span(attribute_key=HTTP_ROUTE,
                                                 attribute_value=str(
                                                     request.path))
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_URL,
                attribute_value=str(request.build_absolute_uri()))

            # Add the span to thread local
            # in some cases (exceptions, timeouts) currentspan in
            # response event will be one of a child spans.
            # let's keep reference to 'django' span and
            # use it in response event
            execution_context.set_opencensus_attr(SPAN_THREAD_LOCAL_KEY, span)

        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #9
0
    def _after_request(self, request, response):
        if utils.disable_tracing_url(request.path, self._blacklist_paths):
            return

        try:
            tracer = execution_context.get_opencensus_tracer()
            tracer.add_attribute_to_current_span(HTTP_STATUS_CODE,
                                                 response.status_code)

            tracer.end_span()
            tracer.finish()
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #10
0
    def test_excludelist_path(self):
        from opencensus.ext.django import middleware

        execution_context.clear()

        excludelist_paths = ['test_excludelist_path']
        settings = type('Test', (object,), {})
        settings.OPENCENSUS = {
            'TRACE': {
                'SAMPLER': 'opencensus.trace.samplers.AlwaysOnSampler()',  # noqa
                'EXCLUDELIST_PATHS': excludelist_paths,
                'EXPORTER': mock.Mock(),
            }
        }
        patch_settings = mock.patch(
            'django.conf.settings',
            settings)

        with patch_settings:
            middleware_obj = middleware.OpencensusMiddleware()

        django_request = RequestFactory().get('/test_excludelist_path')
        disabled = utils.disable_tracing_url(django_request.path,
                                             excludelist_paths)
        self.assertTrue(disabled)
        self.assertEqual(middleware_obj.excludelist_paths, excludelist_paths)

        # test process_request
        middleware_obj.process_request(django_request)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()

        # process view
        view_func = mock.Mock()
        middleware_obj.process_view(django_request, view_func)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()

        assert isinstance(span, BlankSpan)

        # process response
        django_response = mock.Mock()
        django_response.status_code = 200

        middleware_obj.process_response(django_request, django_response)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()
        assert isinstance(span, BlankSpan)
コード例 #11
0
    def test_blacklist_path(self):
        from opencensus.ext.django import middleware

        execution_context.clear()

        blacklist_paths = [
            'test_blacklist_path',
        ]
        params = {
            'BLACKLIST_PATHS': [
                'test_blacklist_path',
            ],
            'TRANSPORT': 'opencensus.common.transports.sync.SyncTransport',
        }
        patch_params = mock.patch(
            'opencensus.ext.django.middleware.settings.params', params)

        with patch_params:
            middleware_obj = middleware.OpencensusMiddleware()

        django_request = RequestFactory().get('/test_blacklist_path')
        disabled = utils.disable_tracing_url(django_request.path,
                                             blacklist_paths)
        self.assertTrue(disabled)
        self.assertEqual(middleware_obj._blacklist_paths, blacklist_paths)

        # test process_request
        middleware_obj.process_request(django_request)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()

        # process view
        view_func = mock.Mock()
        middleware_obj.process_view(django_request, view_func)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()

        assert isinstance(span, BlankSpan)

        # process response
        django_response = mock.Mock()
        django_response.status_code = 200

        middleware_obj.process_response(django_request, django_response)

        tracer = middleware._get_current_tracer()
        span = tracer.current_span()
        assert isinstance(span, BlankSpan)
コード例 #12
0
    def _after_request(self, response):
        """A function to be run after each request.

        See: http://flask.pocoo.org/docs/0.12/api/#flask.Flask.after_request
        """
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return response

        try:
            tracer = execution_context.get_opencensus_tracer()
            tracer.add_attribute_to_current_span(HTTP_STATUS_CODE,
                                                 str(response.status_code))
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
        finally:
            return response
コード例 #13
0
    def process_view(self, request, view_func, *args, **kwargs):
        """Process view is executed before the view function, here we get the
        function name add set it as the span name.
        """

        # Do not trace if the url is excludelisted
        if utils.disable_tracing_url(request.path, self.excludelist_paths):
            return

        try:
            # Get the current span and set the span name to the current
            # function name of the request.
            tracer = _get_current_tracer()
            span = tracer.current_span()
            span.name = utils.get_func_name(view_func)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #14
0
    async def dispatch(self, request: Request, call_next):

        # Do not trace if the url is in the exclude list
        if utils.disable_tracing_url(str(request.url), self.excludelist_paths):
            return await call_next(request)

        try:
            span_context = self.propagator.from_headers(request.headers)

            tracer = tracer_module.Tracer(
                span_context=span_context,
                sampler=self.sampler,
                exporter=self.exporter,
                propagator=self.propagator,
            )
        except Exception:  # pragma: NO COVER
            module_logger.error("Failed to trace request", exc_info=True)
            return await call_next(request)

        try:
            span = tracer.start_span()
            span.span_kind = span_module.SpanKind.SERVER
            span.name = "[{}]{}".format(request.method, request.url)

            tracer.add_attribute_to_current_span(HTTP_HOST,
                                                 request.url.hostname)
            tracer.add_attribute_to_current_span(HTTP_METHOD, request.method)
            tracer.add_attribute_to_current_span(HTTP_PATH, request.url.path)
            tracer.add_attribute_to_current_span(HTTP_ROUTE, request.url.path)
            tracer.add_attribute_to_current_span(HTTP_URL, str(request.url))

            execution_context.set_opencensus_attr("excludelist_hostnames",
                                                  self.excludelist_hostnames)
        except Exception:  # pragma: NO COVER
            module_logger.error("Failed to trace request", exc_info=True)

        response = await call_next(request)
        try:
            tracer.add_attribute_to_current_span(HTTP_STATUS_CODE,
                                                 response.status_code)
        except Exception:  # pragma: NO COVER
            module_logger.error("Failed to trace response", exc_info=True)
        finally:
            tracer.end_span()
            return response
コード例 #15
0
    def process_response(self, request, response):
        # Do not trace if the url is excludelisted
        if utils.disable_tracing_url(request.path, self.excludelist_paths):
            return response

        try:
            span = _get_django_span()
            span.add_attribute(attribute_key=HTTP_STATUS_CODE,
                               attribute_value=response.status_code)

            _set_django_attributes(span, request)

            tracer = _get_current_tracer()
            tracer.end_span()
            tracer.finish()
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
        finally:
            return response
コード例 #16
0
    def test_disable_tracing_url_explicit(self):
        url = 'http://127.0.0.1:8080/test_no_tracing'
        blacklist_paths = ['test_no_tracing']

        disable_tracing = utils.disable_tracing_url(url, blacklist_paths)
        self.assertTrue(disable_tracing)
コード例 #17
0
    def _after_request(self, response):
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
            return response

        return response
コード例 #18
0
 def _teardown_request(self, exception):
     # Do not trace if the url is blacklisted
     if utils.disable_tracing_url(flask.request.url, self.blacklist_paths):
         return