Exemple #1
1
def test_db_span():
    tracer = opentracing.tracer
    span = tracer.start_span(operation_name='parent')
    with span_in_context(span=span):
        with db_span(_COMMIT, 'MySQLdb') as child_span:
            assert span is child_span
        with db_span('select * from X', 'MySQLdb') as child_span:
            assert span is child_span
Exemple #2
0
 def yeet_generator(self):
     with tracer.start_span("yeet_gen_1", child_of=get_current_span()) as span:
         with span_in_context(span):
             y = [pyfiglet.figlet_format("Yeet!!") for _ in range(1000)]
             x = self.yeet_gen_2()
             x.append(y)
             return y
Exemple #3
0
def test_func_span():
    tracer = opentracing.tracer
    span = tracer.start_span(operation_name='parent')
    with span_in_context(span=span):
        with func_span('test') as child_span:
            assert span is child_span
        with func_span('test', tags={'x': 'y'}) as child_span:
            assert span is child_span
Exemple #4
0
    def decorator(*args, **kwargs):
        parent_span = get_current_span()
        if parent_span is None and require_active_trace:
            return func(*args, **kwargs)

        span = utils.start_child_span(
            operation_name=operation_name, parent=parent_span)
        if callable(on_start):
            on_start(span, *args, **kwargs)

        with span, span_in_context(span):
            try:
                return func(*args, **kwargs)
            except Exception as error:
                span.set_tag(tags.ERROR, True)
                span.log_kv({
                    'event': tags.ERROR,
                    'error.object': error,
                })
                raise
Exemple #5
0
    def decorator(*args, **kwargs):
        parent_span = get_current_span()
        if parent_span is None and require_active_trace:
            return func(*args, **kwargs)

        span = utils.start_child_span(operation_name=operation_name,
                                      parent=parent_span)
        if callable(on_start):
            on_start(span, *args, **kwargs)

        with span, span_in_context(span):
            try:
                return func(*args, **kwargs)
            except Exception as error:
                span.set_tag(tags.ERROR, True)
                span.log_kv({
                    'event': tags.ERROR,
                    'error.object': error,
                })
                raise
Exemple #6
0
def func_span(func, tags=None, require_active_trace=True):
    """
    Creates a new local span for execution of the given `func`.
    The returned span is best used as a context manager, e.g.

    .. code-block:: python

        with func_span('my_function'):
            return my_function(...)

    At this time the func should be a string name. In the future this code
    can be enhanced to accept a real function and derive its qualified name.

    :param func: name of the function or method
    :param tags: optional tags to add to the child span
    :param require_active_trace: controls what to do when there is no active
        trace. If require_active_trace=True, then no span is created.
        If require_active_trace=False, a new trace is started.
    :return: new child span, or a dummy context manager if there is no
        active/current parent span
    """
    current_span = get_current_span()

    if current_span is None and require_active_trace:

        @contextlib.contextmanager
        def empty_ctx_mgr():
            yield None

        return empty_ctx_mgr()

    # TODO convert func to a proper name: module:class.func
    operation_name = str(func)
    span = utils.start_child_span(operation_name=operation_name,
                                  parent=current_span,
                                  tags=tags)
    with span_in_context(span):
        return span
Exemple #7
0
    def span_in_context(self, span):
        """
        Store the `span` in the request context and return a `StackContext`.

        This method is meant to be used as a context manager:

        .. code-block:: python

            with tchannel.context_provider.span_in_context(span):
                f = handler_fn()
            res = yield f

        Note: StackContext does not allow yield when used a context manager.
        Instead, save the future and yield it outside of `with:` statement.

        :param span: an OpenTracing Span
        :return: ``StackContext``-based context manager
        """
        if isinstance(opentracing.tracer.scope_manager,
                      opentracing_instrumentation.request_context.TornadoScopeManager):  # noqa
            return opentracing_instrumentation.span_in_stack_context(span)

        return opentracing_instrumentation.span_in_context(span)
Exemple #8
0
        def tracing_wrapper(*args, **kwargs):
            op_name = func.__name__ if span_name is None else span_name
            args_dict = dict(zip(func.__code__.co_varnames, args))
            args_dict.update(kwargs)
            parent = args_dict.get(parent_span_arg, None)
            try:
                parent = deserialize_span_context(parent)

            except:
                pass
            if parent is None:
                parent = get_current_span()
            with opentracing.tracer.start_span(op_name,
                                               child_of=parent) as span:
                #add tags
                try:
                    for arg in args_as_tags:
                        span.set_tag(arg, args_dict.get(arg, None))
                except TypeError:
                    pass
                with span_in_context(span):
                    value = func(*args, **kwargs)
            return value
Exemple #9
0
    def wsgi_tracing_middleware(environ, start_response):
        if environ['PATH_INFO'] == '/metrics':
            return prometheus_app(environ, start_response)

        # TODO find out if the route can be retrieved from somewhere
        request = WSGIRequestWrapper.from_wsgi_environ(environ)
        span = before_request(request=request, tracer=tracer)
        nm = '%s %s %s' % (environ['wsgi.url_scheme'].upper(),
                           request.operation.upper(), environ['PATH_INFO'])
        nm = _NORM_RE.sub('-', nm)
        span.set_operation_name(nm)

        # Wrapper around the real start_response object to log
        # additional information to opentracing Span
        def start_response_wrapper(status, response_headers, exc_info=None):
            span.set_tag('error', exc_info is not None)
            span.set_tag('http.status_code', status[:3])
            span.finish()

            return start_response(status, response_headers)

        with opentracing_instrumentation.span_in_context(span):
            return other_wsgi(environ, start_response_wrapper)
Exemple #10
0
def func_span(func, tags=None, require_active_trace=True):
    """
    Creates a new local span for execution of the given `func`.
    The returned span is best used as a context manager, e.g.

    .. code-block:: python

        with func_span('my_function'):
            return my_function(...)

    At this time the func should be a string name. In the future this code
    can be enhanced to accept a real function and derive its qualified name.

    :param func: name of the function or method
    :param tags: optional tags to add to the child span
    :param require_active_trace: controls what to do when there is no active
        trace. If require_active_trace=True, then no span is created.
        If require_active_trace=False, a new trace is started.
    :return: new child span, or a dummy context manager if there is no
        active/current parent span
    """
    current_span = get_current_span()

    if current_span is None and require_active_trace:
        @contextlib.contextmanager
        def empty_ctx_mgr():
            yield None

        return empty_ctx_mgr()

    # TODO convert func to a proper name: module:class.func
    operation_name = str(func)
    span = utils.start_child_span(
        operation_name=operation_name, parent=current_span, tags=tags)
    with span_in_context(span):
        return span
Exemple #11
0
 def yeet_gen_2():
     with tracer.start_span("yeet_gen_2", child_of=get_current_span()) as span:
         with span_in_context(span):
             y = pyfiglet.figlet_format("Yeet!!")
             return [y for _ in range(10000)]
Exemple #12
0
 def get(self, request, *args, **kwargs):
     with tracer.start_span(self) as span:
         with span_in_context(span):
             yeet = self.yeet_generator()
             return HttpResponse(yeet, content_type='text/plain')