Python opentracing.ext.tags.SPAN_KIND Examples

The following are 30 code examples of opentracing.ext.tags.SPAN_KIND(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module opentracing.ext.tags , or try the search function .
Example #1
Source File: test_threads.py    From opentelemetry-python with Apache License 2.0 6 votes vote down vote up
def test_two_callbacks(self):
        response_future1 = self.client.send("message1")
        response_future2 = self.client.send("message2")

        self.assertEqual("message1::response", response_future1.result(5.0))
        self.assertEqual("message2::response", response_future2.result(5.0))

        spans = self.tracer.finished_spans()
        self.assertEqual(len(spans), 2)

        for span in spans:
            self.assertEqual(
                span.attributes.get(tags.SPAN_KIND, None),
                tags.SPAN_KIND_RPC_CLIENT,
            )

        self.assertNotSameTrace(spans[0], spans[1])
        self.assertIsNone(spans[0].parent)
        self.assertIsNone(spans[1].parent) 
Example #2
Source File: test_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_start_trace(tracer):
    assert type(tracer) is Tracer
    with mock.patch.object(random.Random, 'getrandbits') as mock_random, \
            mock.patch('time.time') as mock_timestamp:
        mock_random.return_value = 12345
        mock_timestamp.return_value = 54321

        span = tracer.start_span('test')
        span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_SERVER)
        assert span, 'Span must not be nil'
        assert span.tracer == tracer, 'Tracer must be referenced from span'
        assert find_tag(span, 'span.kind') == ext_tags.SPAN_KIND_RPC_SERVER, \
            'Span must be server-side'
        assert span.trace_id == 12345, 'Must match trace_id'
        assert span.is_sampled(), 'Must be sampled'
        assert span.parent_id is None, 'Must not have parent_id (root span)'
        assert span.start_time == 54321, 'Must match timestamp'

        span.finish()
        assert span.end_time is not None, 'Must have end_time defined'
        tracer.reporter.assert_called_once()

    tracer.close() 
Example #3
Source File: test_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_tracer_tags_on_root_span(span_type, expected_tags):
    reporter = mock.MagicMock()
    sampler = ConstSampler(True)
    with mock.patch('socket.gethostname', return_value='dream-host.com'):
        tracer = Tracer(service_name='x',
                        reporter=reporter,
                        sampler=sampler,
                        tags={'global-tag': 'global-tag'})
        span = tracer.start_span(operation_name='root')
        if span_type == 'child':
            span = tracer.start_span('child', child_of=span)
        if span_type == 'rpc-server':
            span = tracer.start_span(
                'child', child_of=span.context,
                tags={ext_tags.SPAN_KIND: ext_tags.SPAN_KIND_RPC_SERVER}
            )
        for key, value in six.iteritems(expected_tags):
            found_tag = find_tag(span, key, type(value).__name__)
            if value is None:
                assert found_tag is None, 'test (%s)' % span_type
                continue

            assert found_tag == value, \
                'test (%s): expecting tag %s=%s' % (span_type, key, value) 
Example #4
Source File: test_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_child_span(tracer):
    span = tracer.start_span('test')
    child = tracer.start_span('child', references=child_of(span.context))
    child.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_CLIENT)
    child.set_tag('bender', 'is great')
    child.log_event('kiss-my-shiny-metal-...')
    child.finish()
    span.finish()
    tracer.reporter.report_span.assert_called_once()
    assert len(span.logs) == 0, 'Parent span is Local, must not have events'
    assert len(child.logs) == 1, 'Child must have one events'

    tracer.sampler = ConstSampler(False)
    span = tracer.start_span('test')
    child = tracer.start_span('child', references=child_of(span.context))
    child.set_tag('bender', 'is great')
    child.log_event('kiss-my-shiny-metal-...')
    child.finish()
    span.finish()
    assert len(child.logs) == 0, 'Must have no events, not sampled'
    assert len(child.tags) == 0, 'Must have no attributes, not sampled'
    tracer.close() 
Example #5
Source File: tracing.py    From tchannel-python with MIT License 6 votes vote down vote up
def start_basic_span(self, request):
        """
        Start tracing span from the protocol's `tracing` fields.
        This will only work if the `tracer` supports Zipkin-style span context.

        :param request: inbound request
        :type request: tchannel.tornado.request.Request
        """
        # noinspection PyBroadException
        try:
            # Currently Java does not populate Tracing field, so do not
            # mistaken it for a real trace ID.
            if request.tracing.trace_id:
                context = self.tracer.extract(
                    format=ZIPKIN_SPAN_FORMAT,
                    carrier=request.tracing)
                self.span = self.tracer.start_span(
                    operation_name=request.endpoint,
                    child_of=context,
                    tags={tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER},
                )
        except opentracing.UnsupportedFormatException:
            pass  # tracer might not support Zipkin format
        except:
            log.exception('Cannot extract tracing span from Trace field') 
Example #6
Source File: test_threads.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_two_callbacks(self):
        response_future1 = self.client.send('message1')
        response_future2 = self.client.send('message2')

        self.assertEquals('message1::response', response_future1.result(5.0))
        self.assertEquals('message2::response', response_future2.result(5.0))

        spans = self.tracer.finished_spans()
        self.assertEquals(len(spans), 2)

        for span in spans:
            self.assertEquals(span.tags.get(tags.SPAN_KIND, None),
                              tags.SPAN_KIND_RPC_CLIENT)

        self.assertNotSameTrace(spans[0], spans[1])
        self.assertIsNone(spans[0].parent_id)
        self.assertIsNone(spans[1].parent_id) 
Example #7
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_two_callbacks(self):
        res_future1 = self.loop.create_task(self.client.send('message1'))
        res_future2 = self.loop.create_task(self.client.send('message2'))

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.run_forever()

        self.assertEqual('message1::response', res_future1.result())
        self.assertEqual('message2::response', res_future2.result())

        spans = self.tracer.finished_spans()
        self.assertEqual(len(spans), 2)

        for span in spans:
            self.assertEqual(span.tags.get(tags.SPAN_KIND, None),
                             tags.SPAN_KIND_RPC_CLIENT)

        self.assertNotSameTrace(spans[0], spans[1])
        self.assertIsNone(spans[0].parent_id)
        self.assertIsNone(spans[1].parent_id) 
Example #8
Source File: test_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_start_child(tracer, mode):
    root = tracer.start_span('test')
    if mode == 'arg':
        span = tracer.start_span('test', child_of=root.context)
    elif mode == 'ref':
        span = tracer.start_span('test', references=child_of(root.context))
    else:
        raise ValueError('bad mode')
    span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_SERVER)
    assert span.is_sampled(), 'Must be sampled'
    assert span.trace_id == root.trace_id, 'Must have the same trace id'
    assert span.parent_id == root.span_id, 'Must inherit parent id'
    span.finish()
    assert span.end_time is not None, 'Must have end_time set'
    tracer.reporter.assert_called_once()
    tracer.close() 
Example #9
Source File: test_tornado.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_two_callbacks(self):
        res_future1 = self.client.send('message1')
        res_future2 = self.client.send('message2')

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.start()

        self.assertEquals('message1::response', res_future1.result())
        self.assertEquals('message2::response', res_future2.result())

        spans = self.tracer.finished_spans()
        self.assertEquals(len(spans), 2)

        for span in spans:
            self.assertEquals(span.tags.get(tags.SPAN_KIND, None),
                              tags.SPAN_KIND_RPC_CLIENT)

        self.assertNotSameTrace(spans[0], spans[1])
        self.assertIsNone(spans[0].parent_id)
        self.assertIsNone(spans[1].parent_id) 
Example #10
Source File: test_span.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_is_rpc():
    mock_tracer = mock.MagicMock()
    mock_tracer.max_tag_value_length = 100
    ctx = SpanContext(trace_id=1, span_id=2, parent_id=None, flags=1)

    span = Span(context=ctx, operation_name='x', tracer=mock_tracer)
    assert span.is_rpc() is False
    assert span.is_rpc_client() is False

    span = Span(context=ctx, operation_name='x', tracer=mock_tracer)
    span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_SERVER)
    assert span.is_rpc() is True
    assert span.is_rpc_client() is False

    span = Span(context=ctx, operation_name='x', tracer=mock_tracer)
    span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_CLIENT)
    assert span.is_rpc() is True
    assert span.is_rpc_client() is True 
Example #11
Source File: test_asyncio.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        self.loop.create_task(self.server.run())
        self.loop.create_task(client.send())

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.run_forever()

        spans = self.tracer.finished_spans()
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_SERVER))
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_CLIENT)) 
Example #12
Source File: test_contextvars.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        self.loop.create_task(self.server.run())
        self.loop.create_task(client.send())

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.run_forever()

        spans = self.tracer.finished_spans()
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_SERVER))
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_CLIENT)) 
Example #13
Source File: boto3.py    From opentracing-python-instrumentation with MIT License 6 votes vote down vote up
def perform_call(self, original_func, kind, service_name, operation_name,
                     *args, **kwargs):
        span = utils.start_child_span(
            operation_name='boto3:{}:{}:{}'.format(
                kind, service_name, operation_name
            ),
            parent=get_current_span()
        )

        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
        span.set_tag(tags.COMPONENT, 'boto3')
        span.set_tag('boto3.service_name', service_name)

        with span, span_in_stack_context(span):
            try:
                response = original_func(*args, **kwargs)
            except ClientError as error:
                self.set_request_id_tag(span, error.response)
                raise
            else:
                if isinstance(response, dict):
                    self.set_request_id_tag(span, response)

        return response 
Example #14
Source File: test_asyncio.py    From opentelemetry-python with Apache License 2.0 6 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        self.loop.create_task(self.server.run())
        self.loop.create_task(client.send())

        stop_loop_when(
            self.loop,
            lambda: len(self.tracer.finished_spans()) >= 2,
            timeout=5.0,
        )
        self.loop.run_forever()

        spans = self.tracer.finished_spans()
        self.assertIsNotNone(
            get_one_by_tag(spans, tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)
        )
        self.assertIsNotNone(
            get_one_by_tag(spans, tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
        ) 
Example #15
Source File: pep0249.py    From python-sensor with MIT License 6 votes vote down vote up
def _collect_kvs(self, span, sql):
        try:
            span.set_tag(ext.SPAN_KIND, 'exit')

            if 'db' in self._connect_params[1]:
                span.set_tag(ext.DATABASE_INSTANCE, self._connect_params[1]['db'])
            elif 'database' in self._connect_params[1]:
                span.set_tag(ext.DATABASE_INSTANCE, self._connect_params[1]['database'])

            span.set_tag(ext.DATABASE_STATEMENT, sql_sanitizer(sql))
            span.set_tag(ext.DATABASE_USER, self._connect_params[1]['user'])
            span.set_tag('host', self._connect_params[1]['host'])
            span.set_tag('port', self._connect_params[1]['port'])
        except Exception as e:
            logger.debug(e)
        finally:
            return span 
Example #16
Source File: app_django.py    From python-sensor with MIT License 6 votes vote down vote up
def complex(request):
    with opentracing.tracer.start_active_span('asteroid') as pscope:
        pscope.span.set_tag(ext.COMPONENT, "Python simple example app")
        pscope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
        pscope.span.set_tag(ext.PEER_HOSTNAME, "localhost")
        pscope.span.set_tag(ext.HTTP_URL, "/python/simple/one")
        pscope.span.set_tag(ext.HTTP_METHOD, "GET")
        pscope.span.set_tag(ext.HTTP_STATUS_CODE, 200)
        pscope.span.log_kv({"foo": "bar"})
        time.sleep(.2)

        with opentracing.tracer.start_active_span('spacedust', child_of=pscope.span) as cscope:
            cscope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_CLIENT)
            cscope.span.set_tag(ext.PEER_HOSTNAME, "localhost")
            cscope.span.set_tag(ext.HTTP_URL, "/python/simple/two")
            cscope.span.set_tag(ext.HTTP_METHOD, "POST")
            cscope.span.set_tag(ext.HTTP_STATUS_CODE, 204)
            cscope.span.set_baggage_item("someBaggage", "someValue")
            time.sleep(.1)

    return HttpResponse('Stan wuz here!') 
Example #17
Source File: _server.py    From python-grpc with Apache License 2.0 6 votes vote down vote up
def _start_span(self, servicer_context, method):
        span_context = None
        error = None
        metadata = servicer_context.invocation_metadata()
        try:
            if metadata:
                span_context = self._tracer.extract(
                    opentracing.Format.HTTP_HEADERS, dict(metadata))
        except (opentracing.UnsupportedFormatException,
                opentracing.InvalidCarrierException,
                opentracing.SpanContextCorruptedException) as e:
            logging.exception('tracer.extract() failed')
            error = e
        tags = {
            ot_tags.COMPONENT: 'grpc',
            ot_tags.SPAN_KIND: ot_tags.SPAN_KIND_RPC_SERVER
        }
        _add_peer_tags(servicer_context.peer(), tags)
        span = self._tracer.start_span(
            operation_name=method, child_of=span_context, tags=tags)
        if error is not None:
            span.log_kv({'event': 'error', 'error.object': error})
        return span 
Example #18
Source File: test_tornado.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        with tracer_stack_context():
            self.loop.add_callback(self.server.run)
            self.loop.add_callback(client.send)

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.start()

        spans = self.tracer.finished_spans()
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_SERVER))
        self.assertIsNotNone(get_one_by_tag(spans,
                                            tags.SPAN_KIND,
                                            tags.SPAN_KIND_RPC_CLIENT)) 
Example #19
Source File: test_asyncio.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_two_callbacks(self):
        res_future1 = self.loop.create_task(self.client.send('message1'))
        res_future2 = self.loop.create_task(self.client.send('message2'))

        stop_loop_when(self.loop,
                       lambda: len(self.tracer.finished_spans()) >= 2)
        self.loop.run_forever()

        self.assertEquals('message1::response', res_future1.result())
        self.assertEquals('message2::response', res_future2.result())

        spans = self.tracer.finished_spans()
        self.assertEquals(len(spans), 2)

        for span in spans:
            self.assertEquals(span.tags.get(tags.SPAN_KIND, None),
                              tags.SPAN_KIND_RPC_CLIENT)

        self.assertNotSameTrace(spans[0], spans[1])
        self.assertIsNone(spans[0].parent_id)
        self.assertIsNone(spans[1].parent_id) 
Example #20
Source File: request_handler.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def before_request(self, request, request_context):
        logger.info("Before request %s", request)

        # If we should ignore the active Span, use any passed SpanContext
        # as the parent. Else, use the active one.
        if self.ignore_active_span:
            span = self.tracer.start_span(
                "send", child_of=self.context, ignore_active_span=True
            )
        else:
            span = self.tracer.start_span("send")

        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)

        request_context["span"] = span 
Example #21
Source File: app.py    From microservices-in-action with MIT License 5 votes vote down vote up
def get_user_settings(uuid):
    logger.info("getting user settings", extra={"uuid": uuid})
    settings_url = urljoin("http://settings:5000/settings/", "{}".format(uuid))

    span = get_current_span()
    span.set_tag(tags.HTTP_METHOD, 'GET')
    span.set_tag(tags.HTTP_URL, settings_url)
    span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
    span.set_tag('uuid', uuid)
    headers = {}
    tracer.inject(span, Format.HTTP_HEADERS, headers)

    r = requests.get(settings_url, headers=headers)
    return r.json() 
Example #22
Source File: test_sqlalchemy.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def assert_span(span, operation):
    assert span.operation_name == 'SQL ' + operation
    assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
    assert span.tags.get(tags.DATABASE_TYPE) == 'sqlite'
    assert span.tags.get(tags.DATABASE_INSTANCE) == 'sqlite://'
    assert span.tags.get(tags.COMPONENT) == 'sqlalchemy' 
Example #23
Source File: app.py    From microservices-in-action with MIT License 5 votes vote down vote up
def settings(uuid):
    logger.info("fetching user settings", extra={"uuid": uuid})
    span_ctx = tracer.extract(Format.HTTP_HEADERS, request.headers)
    span_tags = {tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER, 'uuid': uuid}

    with tracer.start_span('settings', child_of=span_ctx, tags=span_tags):
        time.sleep(randint(0, 2))
        return jsonify({'settings': {'name': 'demo user', 'uuid': uuid}}) 
Example #24
Source File: test_middleware.py    From python-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify_traced_tags(self):
        client = Client()
        client.get('/traced/')

        spans = settings.OPENTRACING_TRACING._tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags.get(tags.COMPONENT, None) == 'django'
        assert spans[0].tags.get(tags.HTTP_METHOD, None) == 'GET'
        assert spans[0].tags.get(tags.HTTP_STATUS_CODE, None) == 200
        assert spans[0].tags.get(tags.SPAN_KIND, None) == tags.SPAN_KIND_RPC_SERVER 
Example #25
Source File: test_asyncio.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def send(self):
        with self.tracer.start_active_span("send") as scope:
            scope.span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)

            message = {}
            self.tracer.inject(
                scope.span.context, opentracing.Format.TEXT_MAP, message
            )
            await self.queue.put(message)

        logger.info("Sent message from client") 
Example #26
Source File: test_asyncio.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def process(self, message):
        logger.info("Processing message in server")

        ctx = self.tracer.extract(opentracing.Format.TEXT_MAP, message)
        with self.tracer.start_active_span("receive", child_of=ctx) as scope:
            scope.span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER) 
Example #27
Source File: test_threads.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def test_main(self):
        client = Client(self.tracer)
        res = client.send_sync("message")
        self.assertEqual(res, "message::response")

        spans = self.tracer.finished_spans()
        self.assertEqual(len(spans), 1)

        span = get_one_by_tag(spans, tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
        self.assertIsNotNone(span) 
Example #28
Source File: test_asyncio.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def test_main(self):
        client = Client(self.tracer, self.loop)
        res = client.send_sync("message")
        self.assertEqual(res, "message::response")

        spans = self.tracer.finished_spans()
        self.assertEqual(len(spans), 1)

        span = get_one_by_tag(spans, tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
        self.assertIsNotNone(span) 
Example #29
Source File: tracing.py    From tchannel-python with MIT License 5 votes vote down vote up
def start_span(self, service, endpoint, headers=None,
                   hostport=None, encoding=None):
        parent_span = self.channel.context_provider.get_current_span()
        parent_ctx = parent_span.context if parent_span else None
        span = self.channel.tracer.start_span(
            operation_name=endpoint,
            child_of=parent_ctx
        )
        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
        span.set_tag(tags.PEER_SERVICE, service)
        set_peer_host_port(span, hostport)
        if encoding:
            span.set_tag('as', encoding)

        if headers is None:
            headers = {}
        if isinstance(headers, dict):
            # noinspection PyBroadException
            try:
                tracing_headers = {}
                self.channel.tracer.inject(
                    span.context, opentracing.Format.TEXT_MAP, tracing_headers)
                for k, v in six.iteritems(tracing_headers):
                    headers[TRACING_KEY_PREFIX + k] = v
            except:
                log.exception('Failed to inject tracing span into headers')

        return span, headers 
Example #30
Source File: celery.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def set_common_tags(span, task, span_kind):
    span.set_tag(tags.SPAN_KIND, span_kind)
    span.set_tag(tags.COMPONENT, 'Celery')
    span.set_tag('celery.task_name', task.name)