コード例 #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 _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()
                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)
コード例 #3
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_METHOD, flask.request.method)
            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)
コード例 #4
0
ファイル: trace.py プロジェクト: gosuai/opencensus-python
def _execute(func, handler, args, kwargs):
    with tracer_stack_context():
        config = handler.settings.get(CONFIG_KEY, None)
        if not config or utils.disable_tracing_url(
                handler.request.path, config.get(BLACKLIST_PATHS, None)):
            tracer = NoopTracer()
            setattr(handler.request, TRACER, tracer)
            return func(*args, **kwargs)

        propagator = config[PROPAGATOR_KEY]
        span_context = propagator.from_headers(handler.request.headers)

        tracer = tracer_module.Tracer(span_context=span_context,
                                      sampler=config[SAMPLER_KEY],
                                      exporter=config[EXPORTER_KEY],
                                      propagator=propagator)

        setattr(handler.request, TRACER, tracer)
        span = tracer.start_span()
        span.name = '[{}]{}'.format(_get_class_name(handler),
                                    handler.request.method)
        span.span_kind = span_module.SpanKind.SERVER
        tracer.add_attribute_to_current_span(
            attribute_key=HTTP_METHOD, attribute_value=handler.request.method)
        tracer.add_attribute_to_current_span(
            attribute_key=HTTP_URL, attribute_value=handler.request.path)

        return func(*args, **kwargs)
コード例 #5
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)

            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_METHOD,
                attribute_value=request.method)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_URL,
                attribute_value=request.path)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #6
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 blacklisted
        if utils.disable_tracing_url(request.path, self._blacklist_paths):
            return

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

        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_METHOD, attribute_value=request.method)
            tracer.add_attribute_to_current_span(attribute_key=HTTP_URL,
                                                 attribute_value=request.path)
        except Exception:  # pragma: NO COVER
            log.error('Failed to trace request', exc_info=True)
コード例 #7
0
    def do_trace_request(self, request):
        if utils.disable_tracing_url(request.url, self.blacklist_paths):
            return

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

        tracer = noop_tracer_module.NoopTracer()
        if span_context.from_header and span_context.trace_options.enabled:
            tracer = tracer_module.ContextTracer(span_context=span_context,
                                                 exporter=self.exporter)
        elif self.sampler.should_sample(span_context.trace_id):
            tracer = tracer_module.ContextTracer(exporter=self.exporter)

        span = tracer.start_span()

        route = request.app.router.get(request)
        # Set the span name as the name of the current module name
        span.name = '[sanic] {} {}'.format(request.method, route[3])
        tracer.add_attribute_to_current_span('http.nethod', request.method)
        tracer.add_attribute_to_current_span('http.host', request.host)
        tracer.add_attribute_to_current_span('http.scheme', request.scheme)
        tracer.add_attribute_to_current_span('http.url', request.url)
        tracer.add_attribute_to_current_span('http.client.ip', request.ip)

        for header in ['user-agent', 'x-forwarded-for', 'x-real-ip']:
            if header in request.headers:
                tracer.add_attribute_to_current_span('http.headers.' + header,
                                                     request.headers[header])

        request['tracer'] = tracer

        asyncio_context.set_opencensus_tracer(tracer)
コード例 #8
0
    def test_blacklist_path(self):
        from django.test import RequestFactory

        from opencensus.trace.ext.django import middleware
        from opencensus.trace.tracers import base
        from opencensus.trace.tracers import noop_tracer
        from opencensus.trace.ext import utils
        from opencensus.trace import execution_context

        execution_context.clear()

        blacklist_paths = [
            'test_blacklist_path',
        ]
        params = {
            'BLACKLIST_PATHS': [
                'test_blacklist_path',
            ],
            'TRANSPORT':
            'opencensus.trace.exporters.transports.sync.SyncTransport',
        }
        patch_params = mock.patch(
            'opencensus.trace.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, base.NullContextManager)

        # 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, base.NullContextManager)
コード例 #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,
                                                 str(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 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 blacklisted
        if utils.disable_tracing_url(request.path, self._blacklist_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)
コード例 #11
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
コード例 #12
0
    def do_trace_response(self, request, response):
        """A function to be run after each request.
        """
        # Do not trace if the url is blacklisted
        if utils.disable_tracing_url(request.url, self.blacklist_paths):
            return
        if 'tracer' not in request:
            return

        tracer = request['tracer']
        tracer.add_attribute_to_current_span('http.status_code',
                                             str(response.status))
        if response.status >= 500:
            tracer.add_attribute_to_current_span('error', True)

        tracer.end_span()
        tracer.finish()
コード例 #13
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_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
コード例 #14
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)