Python opentracing.ext.tags.SPAN_KIND_RPC_SERVER Examples

The following are 30 code examples of opentracing.ext.tags.SPAN_KIND_RPC_SERVER(). 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_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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: tracing.py    From python-flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _before_request_fn(self, attributes):
        request = stack.top.request
        operation_name = request.endpoint
        headers = {}
        for k, v in request.headers:
            headers[k.lower()] = v

        try:
            span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS,
                                           headers)
            scope = self.tracer.start_active_span(operation_name,
                                                  child_of=span_ctx)
        except (opentracing.InvalidCarrierException,
                opentracing.SpanContextCorruptedException):
            scope = self.tracer.start_active_span(operation_name)

        self._current_scopes[request] = scope

        span = scope.span
        span.set_tag(tags.COMPONENT, 'Flask')
        span.set_tag(tags.HTTP_METHOD, request.method)
        span.set_tag(tags.HTTP_URL, request.base_url)
        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)

        for attr in attributes:
            if hasattr(request, attr):
                payload = getattr(request, attr)
                if payload not in ('', b''):  # python3
                    span.set_tag(attr, str(payload))

        self._call_start_span_cb(span, request) 
Example #11
Source File: test_asyncio.py    From opentracing-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 #12
Source File: test_tracer.py    From jaeger-client-python with Apache License 2.0 5 votes vote down vote up
def test_one_span_per_rpc(tracer, one_span_per_rpc):
    tracer.one_span_per_rpc = one_span_per_rpc
    span = tracer.start_span('client')
    span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_CLIENT)
    child = tracer.start_span(
        'server',
        references=child_of(span.context),
        tags={ext_tags.SPAN_KIND: ext_tags.SPAN_KIND_RPC_SERVER},
    )
    assert span.trace_id == child.trace_id, 'Must have the same trace ids'
    if one_span_per_rpc:
        assert span.span_id == child.span_id, 'Must have the same span ids'
    else:
        assert span.span_id != child.span_id, 'Must have different span ids' 
Example #13
Source File: test_tornado.py    From opentracing-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 #14
Source File: test_contextvars.py    From opentracing-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 #15
Source File: span.py    From jaeger-client-python with Apache License 2.0 5 votes vote down vote up
def is_rpc(self):
        for tag in self.tags:
            if tag.key == ext_tags.SPAN_KIND:
                return tag.vStr == ext_tags.SPAN_KIND_RPC_CLIENT or \
                    tag.vStr == ext_tags.SPAN_KIND_RPC_SERVER
        return False 
Example #16
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 #17
Source File: test_celery.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def _test_with_regular_client(celery, tracer, task_error):
    before_task_publish.disconnect(celery_hooks.before_task_publish_handler)
    try:
        result = _test_foo_task(celery, task_error)

        spans = tracer.recorder.get_spans()
        assert len(spans) == 1

        span = spans[0]
        assert span.parent_id is None
        assert_span(span, result, 'run', tags.SPAN_KIND_RPC_SERVER)
    finally:
        before_task_publish.connect(celery_hooks.before_task_publish_handler) 
Example #18
Source File: test_celery.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def _test_with_instrumented_client(celery, tracer, task_error):
    result = _test_foo_task(celery, task_error)

    span_server, span_client = tracer.recorder.get_spans()
    assert span_client.parent_id is None
    assert span_client.context.trace_id == span_server.context.trace_id
    assert span_client.context.span_id == span_server.parent_id

    assert_span(span_client, result, 'apply_async', tags.SPAN_KIND_RPC_CLIENT)
    assert_span(span_server, result, 'run', tags.SPAN_KIND_RPC_SERVER) 
Example #19
Source File: celery.py    From opentracing-python-instrumentation with MIT License 5 votes vote down vote up
def task_prerun_handler(task, task_id, **kwargs):
    request = task.request

    operation_name = 'Celery:run:{}'.format(task.name)
    child_of = None
    if request.delivery_info.get('is_eager'):
        child_of = get_current_span()
    else:
        if getattr(request, 'headers', None) is not None:
            # Celery 3.x
            parent_span_context = request.headers.get('parent_span_context')
        else:
            # Celery 4.x
            parent_span_context = getattr(request, 'parent_span_context', None)

        if parent_span_context:
            child_of = opentracing.tracer.extract(
                opentracing.Format.TEXT_MAP, parent_span_context
            )

    task.request.span = span = opentracing.tracer.start_span(
        operation_name=operation_name,
        child_of=child_of,
    )
    set_common_tags(span, task, tags.SPAN_KIND_RPC_SERVER)
    span.set_tag('celery.task_id', task_id)

    request.tracing_context = span_in_context(span)
    request.tracing_context.__enter__() 
Example #20
Source File: test_threads.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        client.send()

        await_until(lambda: len(self.tracer.finished_spans()) >= 2)

        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 #21
Source File: test_threads.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 #22
Source File: test_threads.py    From opentracing-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 #23
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 #24
Source File: test_threads.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        client.send()

        await_until(lambda: len(self.tracer.finished_spans()) >= 2)

        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 #25
Source File: test_gevent.py    From opentracing-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 #26
Source File: trace_context_test_service.py    From lightstep-tracer-python with MIT License 5 votes vote down vote up
def hello():

    span_ctx = tracer.extract(Format.HTTP_HEADERS, request.headers)
    span_tags = {tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER}

    for action in request.json:
        with (
            tracer.start_active_span(
                'format', child_of=span_ctx, tags=span_tags
            )
        ) as scope:
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json; charset=utf-8",
            }

            tracer.inject(scope.span.context, Format.HTTP_HEADERS, headers)

            hello_to = request.args.get('helloTo')

            post(
                url=action["url"],
                data=dumps(action["arguments"]),
                headers=headers,
                timeout=5.0,
            )

    return 'Hello, {}!'.format(hello_to) 
Example #27
Source File: test_flask_tracing.py    From python-flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_span_tags(self):
        test_app.get('/another_test_simple')

        spans = tracing._tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags == {
            tags.COMPONENT: 'Flask',
            tags.HTTP_METHOD: 'GET',
            tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
            tags.HTTP_URL: 'http://localhost/another_test_simple',
            'is_xhr': 'False',
        } 
Example #28
Source File: test_gevent.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test(self):
        client = Client(self.tracer, self.queue)
        gevent.spawn(self.server.run)
        gevent.spawn(client.send)

        gevent.wait(timeout=5.0)

        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 #29
Source File: http_server.py    From opentracing-python-instrumentation with MIT License 4 votes vote down vote up
def before_request(request, tracer=None):
    """
    Attempts to extract a tracing span from incoming request.
    If no tracing context is passed in the headers, or the data
    cannot be parsed, a new root span is started.

    :param request: HTTP request with `.headers` property exposed
        that satisfies a regular dictionary interface
    :param tracer: optional tracer instance to use. If not specified
        the global opentracing.tracer will be used.
    :return: returns a new, already started span.
    """
    if tracer is None:
        tracer = opentracing.tracer

    # we need to prepare tags upfront, mainly because RPC_SERVER tag must be
    # set when starting the span, to support Zipkin's one-span-per-RPC model
    tags_dict = {
        tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
        tags.HTTP_URL: request.full_url,
        tags.HTTP_METHOD: request.method,
    }

    remote_ip = request.remote_ip
    if remote_ip:
        tags_dict[tags.PEER_HOST_IPV4] = remote_ip

    caller_name = request.caller_name
    if caller_name:
        tags_dict[tags.PEER_SERVICE] = caller_name

    remote_port = request.remote_port
    if remote_port:
        tags_dict[tags.PEER_PORT] = remote_port

    operation = request.operation
    try:
        carrier = {}
        for key, value in six.iteritems(request.headers):
            carrier[key] = value
        parent_ctx = tracer.extract(
            format=Format.HTTP_HEADERS, carrier=carrier
        )
    except Exception as e:
        logging.exception('trace extract failed: %s' % e)
        parent_ctx = None

    span = tracer.start_span(
        operation_name=operation,
        child_of=parent_ctx,
        tags=tags_dict)

    return span 
Example #30
Source File: tweens.py    From python-sensor with MIT License 4 votes vote down vote up
def __call__(self, request):
        ctx = tracer.extract(ot.Format.HTTP_HEADERS, request.headers)        
        scope = tracer.start_active_span('http', child_of=ctx)

        scope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
        scope.span.set_tag("http.host", request.host)
        scope.span.set_tag(ext.HTTP_METHOD, request.method)
        scope.span.set_tag(ext.HTTP_URL, request.path)

        if request.matched_route is not None:
            scope.span.set_tag("http.path_tpl", request.matched_route.pattern)

        if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
            for custom_header in agent.extra_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                h = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if h in request.headers:
                    scope.span.set_tag("http.%s" % custom_header, request.headers[h])

        if len(request.query_string):
            scrubbed_params = strip_secrets(request.query_string, agent.secrets_matcher, agent.secrets_list)
            scope.span.set_tag("http.params", scrubbed_params)

        response = None
        try:
            response = self.handler(request)
            
            tracer.inject(scope.span.context, ot.Format.HTTP_HEADERS, response.headers)
            response.headers['Server-Timing'] = "intid;desc=%s" % scope.span.context.trace_id
        except HTTPException as e:
            response = e
            raise
        except BaseException as e:
            scope.span.set_tag("http.status", 500)

            # we need to explicitly populate the `message` tag with an error here
            # so that it's picked up from an SDK span
            scope.span.set_tag("message", str(e))            
            scope.span.log_exception(e)
            
            logger.debug("Pyramid Instana tween", exc_info=True)
        finally:
            if response:
                scope.span.set_tag("http.status", response.status_int)
                
                if 500 <= response.status_int <= 511:
                    if response.exception is not None:
                        message = str(response.exception)
                        scope.span.log_exception(response.exception)
                    else:
                        message = response.status
                        
                    scope.span.set_tag("message", message)
                    scope.span.assure_errored()

            scope.close()

        return response