# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
#     """
#     Access current request context and extract current Span from it.
#     :return:
#         Return current span associated with the current request context.
#         If no request context is present in thread local, or the context
#         has no span, return None.
#     """
#     # Check against the old, ScopeManager-less implementation,
#     # for backwards compatibility.
#     context = RequestContextManager.current_context()
#     if context is not None:
#         return context.span
# 
#     active = opentracing.tracer.scope_manager.active
#     return active.span if active else None
# 
# def span_in_context(span):
#     """
#     Create a context manager that stores the given span in the thread-local
#     request context. This function should only be used in single-threaded
#     applications like Flask / uWSGI.
# 
#     ## Usage example in WSGI middleware:
# 
#     .. code-block:: python
#         from opentracing_instrumentation.http_server import WSGIRequestWrapper
#         from opentracing_instrumentation.http_server import before_request
#         from opentracing_instrumentation import request_context
# 
#         def create_wsgi_tracing_middleware(other_wsgi):
# 
#             def wsgi_tracing_middleware(environ, start_response):
#                 request = WSGIRequestWrapper.from_wsgi_environ(environ)
#                 span = before_request(request=request, tracer=tracer)
# 
#                 # Wrapper around the real start_response object to log
#                 # additional information to opentracing Span
#                 def start_response_wrapper(status, response_headers,
#                                            exc_info=None):
#                     if exc_info is not None:
#                         span.log(event='exception', payload=exc_info)
#                     span.finish()
# 
#                     return start_response(status, response_headers)
# 
#                 with request_context.span_in_context(span):
#                     return other_wsgi(environ, start_response_wrapper)
# 
#             return wsgi_tracing_middleware
# 
#     :param span: OpenTracing Span
#     :return:
#         Return context manager that wraps the request context.
#     """
# 
#     # Return a no-op Scope if None was specified.
#     if span is None:
#         return opentracing.Scope(None, None)
# 
#     return opentracing.tracer.scope_manager.activate(span, False)
# 
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
# 
#     def __init__(self):
#         self.patches_installed = False
# 
#     @property
#     def applicable(self):
#         raise NotImplementedError
# 
#     def install_patches(self):
#         if self.patches_installed:
#             return
# 
#         if self.applicable:
#             self._install_patches()
#         self.patches_installed = True
# 
#     def reset_patches(self):
#         if self.applicable:
#             self._reset_patches()
#         self.patches_installed = False
# 
#     def _install_patches(self):
#         raise NotImplementedError
# 
#     def _reset_patches(self):
#         raise NotImplementedError
# 
#     @classmethod
#     def configure_hook_module(cls, context):
#         def set_patcher(custom_patcher):
#             context['patcher'] = custom_patcher
# 
#         def install_patches():
#             context['patcher'].install_patches()
# 
#         def reset_patches():
#             context['patcher'].reset_patches()
# 
#         context['patcher'] = cls()
#         context['set_patcher'] = set_patcher
#         context['install_patches'] = install_patches
#         context['reset_patches'] = reset_patches


import opentracing
from opentracing.ext import tags
from ..request_context import get_current_span, span_in_context
from ._patcher import Patcher
    from celery.app.task import Task
    from celery.signals import (
        before_task_publish, task_prerun, task_success, task_failure
    )
                              carrier=span_context)


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)


# Path: opentracing_instrumentation/request_context.py
# def get_current_span():
#     """
#     Access current request context and extract current Span from it.
#     :return:
#         Return current span associated with the current request context.
#         If no request context is present in thread local, or the context
#         has no span, return None.
#     """
#     # Check against the old, ScopeManager-less implementation,
#     # for backwards compatibility.
#     context = RequestContextManager.current_context()
#     if context is not None:
#         return context.span
# 
#     active = opentracing.tracer.scope_manager.active
#     return active.span if active else None
# 
# def span_in_context(span):
#     """
#     Create a context manager that stores the given span in the thread-local
#     request context. This function should only be used in single-threaded
#     applications like Flask / uWSGI.
# 
#     ## Usage example in WSGI middleware:
# 
#     .. code-block:: python
#         from opentracing_instrumentation.http_server import WSGIRequestWrapper
#         from opentracing_instrumentation.http_server import before_request
#         from opentracing_instrumentation import request_context
# 
#         def create_wsgi_tracing_middleware(other_wsgi):
# 
#             def wsgi_tracing_middleware(environ, start_response):
#                 request = WSGIRequestWrapper.from_wsgi_environ(environ)
#                 span = before_request(request=request, tracer=tracer)
# 
#                 # Wrapper around the real start_response object to log
#                 # additional information to opentracing Span
#                 def start_response_wrapper(status, response_headers,
#                                            exc_info=None):
#                     if exc_info is not None:
#                         span.log(event='exception', payload=exc_info)
#                     span.finish()
# 
#                     return start_response(status, response_headers)
# 
#                 with request_context.span_in_context(span):
#                     return other_wsgi(environ, start_response_wrapper)
# 
#             return wsgi_tracing_middleware
# 
#     :param span: OpenTracing Span
#     :return:
#         Return context manager that wraps the request context.
#     """
# 
#     # Return a no-op Scope if None was specified.
#     if span is None:
#         return opentracing.Scope(None, None)
# 
#     return opentracing.tracer.scope_manager.activate(span, False)
# 
# Path: opentracing_instrumentation/client_hooks/_patcher.py
# class Patcher(object):
# 
#     def __init__(self):
#         self.patches_installed = False
# 
#     @property
#     def applicable(self):
#         raise NotImplementedError
# 
#     def install_patches(self):
#         if self.patches_installed:
#             return
# 
#         if self.applicable:
#             self._install_patches()
#         self.patches_installed = True
# 
#     def reset_patches(self):
#         if self.applicable:
#             self._reset_patches()
#         self.patches_installed = False
# 
#     def _install_patches(self):
#         raise NotImplementedError
# 
#     def _reset_patches(self):
#         raise NotImplementedError
# 
#     @classmethod
#     def configure_hook_module(cls, context):
#         def set_patcher(custom_patcher):
#             context['patcher'] = custom_patcher
# 
#         def install_patches():
#             context['patcher'].install_patches()
# 
#         def reset_patches():
#             context['patcher'].reset_patches()
# 
#         context['patcher'] = cls()
#         context['set_patcher'] = set_patcher
#         context['install_patches'] = install_patches
#         context['reset_patches'] = reset_patches


# Path: opentracing_instrumentation/client_hooks/celery.py
import opentracing
from opentracing.ext import tags
from ..request_context import get_current_span, span_in_context
from ._patcher import Patcher
    from celery.app.task import Task
    from celery.signals import (
        before_task_publish, task_prerun, task_success, task_failure
    )

                              carrier=span_context)


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)