Exemple #1
0
    def test_finish_sampled(self):
        from opencensus.trace.tracers import context_tracer

        sampler = mock.Mock()
        sampler.should_sample.return_value = True
        tracer = tracer_module.Tracer(sampler=sampler)
        assert isinstance(tracer.tracer, context_tracer.ContextTracer)
        mock_tracer = mock.Mock()
        tracer.tracer = mock_tracer
        tracer.finish()
        self.assertTrue(mock_tracer.finish.called)
def trigger_http_endpoint(path, method, message={}):
    #include other methods if necessary
    httpEndpoint = os.environ[path]
    tracer = tracer_module.Tracer(exporter=exporter)
    with tracer.span(name=httpEndpoint) as tracerObj:
        headers = {
            'content-type': 'application/json',
            "content-length": str(len(message))
        }
        r = requests.post(httpEndpoint, data=json.dumps(message), headers=headers)
    print(r.status_code)
Exemple #3
0
    def get_tracer_context_tracer(self):
        from opencensus.trace.tracers import context_tracer

        sampler = mock.Mock()
        sampler.should_sample.return_value = True
        tracer = tracer_module.Tracer(sampler=sampler)

        result = tracer.get_tracer()

        assert isinstance(result, context_tracer.ContextTracer)
        self.assertTrue(tracer.span_context.trace_options.enabled)
Exemple #4
0
    def test_tracer(self):
        import json

        from opencensus.trace import tracer as tracer_module
        from opencensus.trace.samplers import always_on
        from opencensus.trace.exporters import file_exporter
        from opencensus.trace.propagation import google_cloud_format

        trace_id = 'f8739df974a4481f98748cd92b27177d'
        span_id = '6e0c63257de34c92'
        trace_option = 1

        trace_header = '{}/{};o={}'.format(trace_id, span_id, trace_option)

        sampler = always_on.AlwaysOnSampler()
        exporter = file_exporter.FileExporter()
        propagator = google_cloud_format.GoogleCloudFormatPropagator()
        span_context = propagator.from_header(header=trace_header)

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

        with tracer.span(name='root_span') as root:
            func_to_trace()
            parent_span_id = root.span_id
            with root.span(name='child_span'):
                func_to_trace()

        tracer.finish()

        file = open(file_exporter.DEFAULT_FILENAME, 'r')
        trace_json = json.loads(file.read())

        spans = trace_json.get('spans')

        self.assertEqual(trace_json.get('traceId'), trace_id)
        self.assertEqual(len(spans), 2)

        self.assertSetEqual(
            {ss['displayName']['value'] for ss in spans},
            {'child_span', 'root_span'})

        for span in spans:
            if span['displayName']['value'] == 'root_span':
                self.assertEqual(span['parentSpanId'], span_id)
                self.assertEqual(span['childSpanCount'], 1)
            else:
                self.assertEqual(span['displayName']['value'], 'child_span')
                self.assertEqual(span['parentSpanId'], parent_span_id)
                self.assertEqual(span['childSpanCount'], 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)

        execution_context.set_opencensus_attr('blacklist_hostnames',
                                              self.blacklist_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)
    def setUp(self):
        super(TestClient, self).setUp()
        self.exporter = CapturingExporter()
        self.tracer = tracer_module.Tracer(
            sampler=AlwaysOnSampler(),
            exporter=self.exporter,
            propagator=GoogleCloudFormatPropagator())

        self.stack_context = tracer_stack_context()
        self.stack_context.__enter__()
        execution_context.set_opencensus_tracer(self.tracer)
Exemple #7
0
 def test_to_header(self):
     with ContextHelper() as ctx:
         og_header = {"traceparent": "00-2578531519ed94423ceae67588eff2c9-231ebdc614cb9ddd-01"}
         ctx = tracer_module.trace_context_http_header_format.TraceContextPropagator().from_headers(og_header)
         trace = tracer_module.Tracer(sampler=AlwaysOnSampler(), span_context=ctx)
         wrapped_class = OpenCensusSpan()
         headers = wrapped_class.to_header()
         new_header = {
             "traceparent": "00-2578531519ed94423ceae67588eff2c9-{}-01".format(wrapped_class.span_instance.span_id)
         }
         assert headers == new_header
Exemple #8
0
 def test_start_finish(self):
     with ContextHelper() as ctx:
         tracer = tracer_module.Tracer(sampler=AlwaysOnSampler())
         parent = OpenCensusSpan()
         wrapped_class = parent.span()
         assert wrapped_class.span_instance.end_time is None
         wrapped_class.start()
         wrapped_class.finish()
         assert wrapped_class.span_instance.start_time is not None
         assert wrapped_class.span_instance.end_time is not None
         parent.finish()
Exemple #9
0
    def test_should_sample_force_not_trace(self):

        span_context = mock.Mock()
        span_context.trace_options.enabled = False
        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        tracer = tracer_module.Tracer(span_context=span_context,
                                      sampler=sampler)
        sampled = tracer.should_sample()

        self.assertFalse(sampled)
Exemple #10
0
    def test_end_span_not_sampled(self):
        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        span_context = mock.Mock()
        span_context.trace_options.enabled = False
        tracer = tracer_module.Tracer(sampler=sampler,
                                      span_context=span_context)

        tracer.end_span()

        self.assertFalse(span_context.span_id.called)
Exemple #11
0
    def test_current_span_sampled(self):
        from opencensus.trace import execution_context

        sampler = mock.Mock()
        sampler.should_sample.return_value = True
        tracer = tracer_module.Tracer(sampler=sampler)
        span = mock.Mock()
        execution_context.set_current_span(span)

        result = tracer.current_span()

        self.assertEqual(result, span)
Exemple #12
0
def test_distributed_tracing_policy_solo(should_set_sdk_context):
    """Test policy with no other policy and happy path"""
    with ContextHelper():
        exporter = MockExporter()
        trace = tracer_module.Tracer(sampler=AlwaysOnSampler(), exporter=exporter)
        with trace.span("parent"):
            if should_set_sdk_context:
                tracing_context.current_span.set(OpenCensusSpan(trace.current_span()))
            policy = DistributedTracingPolicy()

            request = HttpRequest("GET", "http://127.0.0.1/temp?query=query")
            request.headers["x-ms-client-request-id"] = "some client request id"

            pipeline_request = PipelineRequest(request, PipelineContext(None))
            policy.on_request(pipeline_request)

            response = HttpResponse(request, None)
            response.headers = request.headers
            response.status_code = 202
            response.headers["x-ms-request-id"] = "some request id"

            ctx = trace.span_context
            header = trace.propagator.to_headers(ctx)
            assert request.headers.get("traceparent") == header.get("traceparent")

            policy.on_response(pipeline_request, PipelineResponse(request, response, PipelineContext(None)))
            time.sleep(0.001)
            policy.on_request(pipeline_request)
            policy.on_exception(pipeline_request)

        trace.finish()
        exporter.build_tree()
        parent = exporter.root
        network_span = parent.children[0]
        assert network_span.span_data.name == "/temp"
        assert network_span.span_data.attributes.get("http.method") == "GET"
        assert network_span.span_data.attributes.get("component") == "http"
        assert network_span.span_data.attributes.get("http.url") == "http://127.0.0.1/temp?query=query"
        assert network_span.span_data.attributes.get("http.user_agent") is None
        assert network_span.span_data.attributes.get("x-ms-request-id") == "some request id"
        assert network_span.span_data.attributes.get("x-ms-client-request-id") == "some client request id"
        assert network_span.span_data.attributes.get("http.status_code") == 202

        network_span = parent.children[1]
        assert network_span.span_data.name == "/temp"
        assert network_span.span_data.attributes.get("http.method") == "GET"
        assert network_span.span_data.attributes.get("component") == "http"
        assert network_span.span_data.attributes.get("http.url") == "http://127.0.0.1/temp?query=query"
        assert network_span.span_data.attributes.get("x-ms-client-request-id") == "some client request id"
        assert network_span.span_data.attributes.get("http.user_agent") is None
        assert network_span.span_data.attributes.get("x-ms-request-id") == None
        assert network_span.span_data.attributes.get("http.status_code") == 504
Exemple #13
0
    def test_current_span_not_sampled(self):
        from opencensus.trace.tracers import base

        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        span_context = mock.Mock()
        span_context.trace_options.enabled = False
        tracer = tracer_module.Tracer(sampler=sampler,
                                      span_context=span_context)

        span = tracer.current_span()

        assert isinstance(span, base.NullContextManager)
Exemple #14
0
 def test_decorator_has_different_name(self):
     with ContextHelper():
         exporter = MockExporter()
         trace = tracer_module.Tracer(sampler=AlwaysOnSampler(), exporter=exporter)
         with trace.span("overall"):
             client = MockClient()
             client.check_name_is_different()
         trace.finish()
         exporter.build_tree()
         parent = exporter.root
         assert len(parent.children) == 2
         assert parent.children[0].span_data.name == "MockClient.__init__"
         assert parent.children[1].span_data.name == "different name"
Exemple #15
0
 def test_links(self):
     with ContextHelper() as ctx:
         trace = tracer_module.Tracer(sampler=AlwaysOnSampler())
         og_header = {
             "traceparent":
             "00-2578531519ed94423ceae67588eff2c9-231ebdc614cb9ddd-01"
         }
         wrapped_class = OpenCensusSpan()
         OpenCensusSpan.link_from_headers(og_header)
         assert len(wrapped_class.span_instance.links) == 1
         link = wrapped_class.span_instance.links[0]
         assert link.trace_id == "2578531519ed94423ceae67588eff2c9"
         assert link.span_id == "231ebdc614cb9ddd"
Exemple #16
0
    def __call__(self, *args, **kwargs):
        kwds = kwargs.pop("kwds")

        span_context_binary = kwargs.pop("span_context_binary")
        propagator = binary_format.BinaryFormatPropagator()
        kwargs["span_context"] = propagator.from_header(span_context_binary)

        _tracer = tracer.Tracer(**kwargs)
        execution_context.set_opencensus_tracer(_tracer)
        with _tracer.span(name=threading.current_thread().name):
            result = self.func(*args, **kwds)
        execution_context.clean()
        return result
Exemple #17
0
    def test_current_span_not_sampled(self):
        from opencensus.trace.blank_span import BlankSpan

        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        span_context = mock.Mock()
        span_context.trace_options.enabled = False
        tracer = tracer_module.Tracer(
            sampler=sampler, span_context=span_context)

        span = tracer.current_span()

        assert isinstance(span, BlankSpan)
Exemple #18
0
def prerun_task_span(task_id=None, task=None, *args, **kwargs):
    if settings.STACKDRIVER_TRACE_PROJECT_ID:
        exporter = stackdriver_exporter.StackdriverExporter(
            project_id=settings.STACKDRIVER_TRACE_PROJECT_ID,
            transport=BackgroundThreadTransport)
        sampler = probability.ProbabilitySampler(
            rate=settings.CELERY_TRACE_SAMPLING_RATE)
        tracer = tracer_module.Tracer(exporter=exporter, sampler=sampler)
        span = tracer.start_span()
        span.name = '[celery]{0}'.format(task.name)
        execution_context.set_opencensus_tracer(tracer)
        span.add_attribute('args', str(kwargs['args']))
        span.add_attribute('kwargs', str(kwargs['kwargs']))
        execution_context.set_current_span(span)
    def test_trace_decorator(self):
        tracer = tracer_module.Tracer()

        return_value = "test"

        @tracer.trace_decorator()
        def test_decorator():
            return return_value

        returned = test_decorator()

        self.assertEqual(len(tracer.tracer._spans_list), 1)
        self.assertEqual(tracer.tracer._spans_list[0].name, 'test_decorator')
        self.assertEqual(returned, return_value)
Exemple #20
0
    def test_finish_not_sampled(self):
        from opencensus.trace.tracers import noop_tracer

        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        span_context = mock.Mock()
        span_context.trace_options.enabled = False
        tracer = tracer_module.Tracer(
            span_context=span_context, sampler=sampler)
        assert isinstance(tracer.tracer, noop_tracer.NoopTracer)
        mock_tracer = mock.Mock()
        tracer.tracer = mock_tracer
        tracer.finish()
        self.assertTrue(mock_tracer.finish.called)
    def test_span_not_sampled(self):
        from opencensus.trace.tracers import base

        sampler = mock.Mock()
        sampler.should_sample.return_value = False
        tracer = tracer_module.Tracer(sampler=sampler)

        span = tracer.span()

        # Test nested span not sampled
        child_span = span.span()

        assert isinstance(span, base.NullContextManager)
        assert isinstance(child_span, base.NullContextManager)
Exemple #22
0
    def test_constructor_default(self):
        from opencensus.trace.propagation import google_cloud_format
        from opencensus.trace.exporters import print_exporter
        from opencensus.trace.samplers.always_on import AlwaysOnSampler
        from opencensus.trace.span_context import SpanContext
        from opencensus.trace.tracers import context_tracer

        tracer = tracer_module.Tracer()

        assert isinstance(tracer.span_context, SpanContext)
        assert isinstance(tracer.sampler, AlwaysOnSampler)
        assert isinstance(tracer.exporter, print_exporter.PrintExporter)
        assert isinstance(tracer.propagator,
                          google_cloud_format.GoogleCloudFormatPropagator)
        assert isinstance(tracer.tracer, context_tracer.ContextTracer)
 def test_passing_links_in_ctor(self):
     with ContextHelper() as ctx:
         trace = tracer_module.Tracer(sampler=AlwaysOnSampler())
         parent = trace.start_span()
         wrapped_class = OpenCensusSpan(links=[
             Link(
                 headers={
                     "traceparent":
                     "00-2578531519ed94423ceae67588eff2c9-231ebdc614cb9ddd-01"
                 })
         ])
         assert len(wrapped_class.span_instance.links) == 1
         link = wrapped_class.span_instance.links[0]
         assert link.trace_id == "2578531519ed94423ceae67588eff2c9"
         assert link.span_id == "231ebdc614cb9ddd"
    def setUp(self):
        self.exporter = CapturingExporter()
        self.tracer = tracer_module.Tracer(
            sampler=AlwaysOnSampler(),
            exporter=self.exporter,
            propagator=GoogleCloudFormatPropagator()
        )

        config_integration.trace_integrations(['redis'], tracer=self.tracer)

        self.client = redis.StrictRedis()

        # Stash away the original methods for
        # after-test restoration.
        self._execute_command = redis.StrictRedis.execute_command
        self._pipeline = redis.StrictRedis.pipeline
Exemple #25
0
 def test_span(self):
     exporter = MockExporter()
     with ContextHelper() as ctx:
         tracer = tracer_module.Tracer(sampler=AlwaysOnSampler(), exporter=exporter)
         assert OpenCensusSpan.get_current_tracer() is tracer
         wrapped_class = OpenCensusSpan()
         assert tracer.current_span() == wrapped_class.span_instance
         child = wrapped_class.span()
         assert tracer.current_span() == child.span_instance
         assert child.span_instance.name == "span"
         assert child.span_instance.context_tracer.trace_id == tracer.span_context.trace_id
         assert child.span_instance.parent_span is wrapped_class.span_instance
         tracer.finish()
     exporter.build_tree()
     parent = exporter.root
     assert len(parent.children) == 1
     assert parent.children[0].span_data.span_id == child.span_instance.span_id
    def test_constructor_default(self):
        from opencensus.trace import print_exporter
        from opencensus.trace.propagation \
            import trace_context_http_header_format
        from opencensus.trace.samplers import ProbabilitySampler
        from opencensus.trace.span_context import SpanContext
        from opencensus.trace.tracers import noop_tracer

        tracer = tracer_module.Tracer()

        assert isinstance(tracer.span_context, SpanContext)
        assert isinstance(tracer.sampler, ProbabilitySampler)
        assert isinstance(tracer.exporter, print_exporter.PrintExporter)
        assert isinstance(
            tracer.propagator,
            trace_context_http_header_format.TraceContextPropagator)
        assert isinstance(tracer.tracer, noop_tracer.NoopTracer)
Exemple #27
0
    def test_trace_decorator(self):
        mock_exporter = mock.MagicMock()
        tracer = tracer_module.Tracer(exporter=mock_exporter)

        return_value = "test"

        @tracer.trace_decorator()
        def test_decorator():
            return return_value

        returned = test_decorator()

        self.assertEqual(returned, return_value)
        self.assertEqual(mock_exporter.export.call_count, 1)
        exported_spandata = mock_exporter.export.call_args[0][0][0]
        self.assertIsInstance(exported_spandata, span_data.SpanData)
        self.assertEqual(exported_spandata.name, 'test_decorator')
Exemple #28
0
 def test_with_opencencus_used(self):
     with ContextHelper():
         exporter = MockExporter()
         trace = tracer_module.Tracer(sampler=AlwaysOnSampler(), exporter=exporter)
         parent = trace.start_span(name="OverAll")
         client = MockClient(policies=[])
         client.get_foo(parent_span=parent)
         client.get_foo()
         parent.finish()
         trace.finish()
         exporter.build_tree()
         parent = exporter.root
         assert len(parent.children) == 3
         assert parent.children[0].span_data.name == "MockClient.__init__"
         assert not parent.children[0].children
         assert parent.children[1].span_data.name == "MockClient.get_foo"
         assert not parent.children[1].children
Exemple #29
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
Exemple #30
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_ROUTE, 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)