| 1 |
# Copyright (c) The OpenTracing Authors. |
| 2 |
# |
| 3 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 |
# of this software and associated documentation files (the "Software"), to deal |
| 5 |
# in the Software without restriction, including without limitation the rights |
| 6 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 |
# copies of the Software, and to permit persons to whom the Software is |
| 8 |
# furnished to do so, subject to the following conditions: |
| 9 |
# |
| 10 |
# The above copyright notice and this permission notice shall be included in |
| 11 |
# all copies or substantial portions of the Software. |
| 12 |
# |
| 13 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 |
# THE SOFTWARE. |
| 20 |
|
| 21 |
from __future__ import absolute_import |
| 22 |
|
| 23 |
import threading |
| 24 |
import tornado.stack_context |
| 25 |
|
| 26 |
from opentracing import Scope |
| 27 |
from opentracing.scope_managers import ThreadLocalScopeManager |
| 28 |
|
| 29 |
|
| 30 |
# Implementation based on |
| 31 |
# github.com/uber-common/opentracing-python-instrumentation/ |
| 32 |
|
| 33 |
class TornadoScopeManager(ThreadLocalScopeManager): |
| 34 |
""" |
| 35 |
:class:`~opentracing.ScopeManager` implementation for **Tornado** |
| 36 |
that stores the :class:`~opentracing.Scope` using a custom |
| 37 |
:class:`StackContext`, falling back to thread-local storage if |
| 38 |
none was found. |
| 39 |
|
| 40 |
Using it under :func:`tracer_stack_context()` will |
| 41 |
also automatically propagate the active :class:`~opentracing.Span` |
| 42 |
from parent coroutines to their children: |
| 43 |
|
| 44 |
.. code-block:: python |
| 45 |
|
| 46 |
@tornado.gen.coroutine |
| 47 |
def child_coroutine(): |
| 48 |
# No need to pass 'parent' and activate it here, |
| 49 |
# as it is automatically propagated. |
| 50 |
with tracer.start_active_span('child') as scope: |
| 51 |
... |
| 52 |
|
| 53 |
@tornado.gen.coroutine |
| 54 |
def parent_coroutine(): |
| 55 |
with tracer.start_active_span('parent') as scope: |
| 56 |
... |
| 57 |
yield child_coroutine() |
| 58 |
... |
| 59 |
|
| 60 |
with tracer_stack_context(): |
| 61 |
loop.add_callback(parent_coroutine) |
| 62 |
|
| 63 |
|
| 64 |
.. note:: |
| 65 |
The current version does not support :class:`~opentracing.Span` |
| 66 |
activation in children coroutines when the parent yields over |
| 67 |
**multiple** of them, as the context is effectively shared by all, |
| 68 |
and the active :class:`~opentracing.Span` state is messed up: |
| 69 |
|
| 70 |
.. code-block:: python |
| 71 |
|
| 72 |
@tornado.gen.coroutine |
| 73 |
def coroutine(input): |
| 74 |
# No span should be activated here. |
| 75 |
# The parent Span will remain active, though. |
| 76 |
with tracer.start_span('child', child_of=tracer.active_span): |
| 77 |
... |
| 78 |
|
| 79 |
@tornado.gen.coroutine |
| 80 |
def handle_request_wrapper(): |
| 81 |
res1 = coroutine('A') |
| 82 |
res2 = coroutine('B') |
| 83 |
|
| 84 |
yield [res1, res2] |
| 85 |
""" |
| 86 |
|
| 87 |
def activate(self, span, finish_on_close): |
| 88 |
""" |
| 89 |
Make a :class:`~opentracing.Span` instance active. |
| 90 |
|
| 91 |
:param span: the :class:`~opentracing.Span` that should become active. |
| 92 |
:param finish_on_close: whether *span* should automatically be |
| 93 |
finished when :meth:`Scope.close()` is called. |
| 94 |
|
| 95 |
If no :func:`tracer_stack_context()` is detected, thread-local |
| 96 |
storage will be used to store the :class:`~opentracing.Scope`. |
| 97 |
Observe that in this case the active :class:`~opentracing.Span` |
| 98 |
will not be automatically propagated to the child corotuines. |
| 99 |
|
| 100 |
:return: a :class:`~opentracing.Scope` instance to control the end |
| 101 |
of the active period for the :class:`~opentracing.Span`. |
| 102 |
It is a programming error to neglect to call :meth:`Scope.close()` |
| 103 |
on the returned instance. |
| 104 |
""" |
| 105 |
|
| 106 |
context = self._get_context() |
| 107 |
if context is None: |
| 108 |
return super(TornadoScopeManager, self).activate(span, |
| 109 |
finish_on_close) |
| 110 |
|
| 111 |
scope = _TornadoScope(self, span, finish_on_close) |
| 112 |
context.active = scope |
| 113 |
|
| 114 |
return scope |
| 115 |
|
| 116 |
@property |
| 117 |
def active(self): |
| 118 |
""" |
| 119 |
Return the currently active :class:`~opentracing.Scope` which |
| 120 |
can be used to access the currently active |
| 121 |
:attr:`Scope.span`. |
| 122 |
|
| 123 |
:return: the :class:`~opentracing.Scope` that is active, |
| 124 |
or ``None`` if not available. |
| 125 |
""" |
| 126 |
|
| 127 |
context = self._get_context() |
| 128 |
if not context: |
| 129 |
return super(TornadoScopeManager, self).active |
| 130 |
|
| 131 |
return context.active |
| 132 |
|
| 133 |
def _get_context(self): |
| 134 |
return _TracerRequestContextManager.current_context() |
| 135 |
|
| 136 |
|
| 137 |
class _TornadoScope(Scope): |
| 138 |
def __init__(self, manager, span, finish_on_close): |
| 139 |
super(_TornadoScope, self).__init__(manager, span) |
| 140 |
self._finish_on_close = finish_on_close |
| 141 |
self._to_restore = manager.active |
| 142 |
|
| 143 |
def close(self): |
| 144 |
context = self.manager._get_context() |
| 145 |
if context is None or context.active is not self: |
| 146 |
return |
| 147 |
|
| 148 |
context.active = self._to_restore |
| 149 |
|
| 150 |
if self._finish_on_close: |
| 151 |
self.span.finish() |
| 152 |
|
| 153 |
|
| 154 |
class ThreadSafeStackContext(tornado.stack_context.StackContext): |
| 155 |
""" |
| 156 |
Thread safe version of Tornado's StackContext (up to 4.3) |
| 157 |
Copy of implementation by caspersj@, until tornado-extras is open-sourced. |
| 158 |
Tornado's StackContext works as follows: |
| 159 |
- When entering a context, create an instance of StackContext and |
| 160 |
add add this instance to the current "context stack" |
| 161 |
- If execution transfers to another thread (using the wraps helper |
| 162 |
method), copy the current "context stack" and apply that in the new |
| 163 |
thread when execution starts |
| 164 |
- A context stack can be entered/exited by traversing the stack and |
| 165 |
calling enter/exit on all elements. This is how the `wraps` helper |
| 166 |
method enters/exits in new threads. |
| 167 |
- StackContext has an internal pointer to a context factory (i.e. |
| 168 |
RequestContext), and an internal stack of applied contexts (instances |
| 169 |
of RequestContext) for each instance of StackContext. RequestContext |
| 170 |
instances are entered/exited from the stack as the StackContext |
| 171 |
is entered/exited |
| 172 |
- However, the enter/exit logic and maintenance of this stack of |
| 173 |
RequestContext instances is not thread safe. |
| 174 |
``` |
| 175 |
def __init__(self, context_factory): |
| 176 |
self.context_factory = context_factory |
| 177 |
self.contexts = [] |
| 178 |
self.active = True |
| 179 |
def enter(self): |
| 180 |
context = self.context_factory() |
| 181 |
self.contexts.append(context) |
| 182 |
context.__enter__() |
| 183 |
def exit(self, type, value, traceback): |
| 184 |
context = self.contexts.pop() |
| 185 |
context.__exit__(type, value, traceback) |
| 186 |
``` |
| 187 |
Unexpected semantics of Tornado's default StackContext implementation: |
| 188 |
- There exist a race on `self.contexts`, where thread A enters a |
| 189 |
context, thread B enters a context, and thread A exits its context. |
| 190 |
In this case, the exit by thread A pops the instance created by |
| 191 |
thread B and calls exit on this instance. |
| 192 |
- There exists a race between `enter` and `exit` where thread A |
| 193 |
executes the two first statements of enter (create instance and |
| 194 |
add to contexts) and thread B executes exit, calling exit on an |
| 195 |
instance that has been initialized but not yet exited (and |
| 196 |
subsequently this instance will then be entered). |
| 197 |
The ThreadSafeStackContext changes the internal contexts stack to be |
| 198 |
thread local, fixing both of the above issues. |
| 199 |
""" |
| 200 |
|
| 201 |
def __init__(self, *args, **kwargs): |
| 202 |
class LocalContexts(threading.local): |
| 203 |
def __init__(self): |
| 204 |
super(LocalContexts, self).__init__() |
| 205 |
self._contexts = [] |
| 206 |
|
| 207 |
def append(self, item): |
| 208 |
self._contexts.append(item) |
| 209 |
|
| 210 |
def pop(self): |
| 211 |
return self._contexts.pop() |
| 212 |
|
| 213 |
super(ThreadSafeStackContext, self).__init__(*args, **kwargs) |
| 214 |
|
| 215 |
if hasattr(self, 'contexts'): |
| 216 |
# only patch if context exists |
| 217 |
self.contexts = LocalContexts() |
| 218 |
|
| 219 |
|
| 220 |
class _TracerRequestContext(object): |
| 221 |
__slots__ = ('active', ) |
| 222 |
|
| 223 |
def __init__(self, active=None): |
| 224 |
self.active = active |
| 225 |
|
| 226 |
|
| 227 |
class _TracerRequestContextManager(object): |
| 228 |
_state = threading.local() |
| 229 |
_state.context = None |
| 230 |
|
| 231 |
@classmethod |
| 232 |
def current_context(cls): |
| 233 |
return getattr(cls._state, 'context', None) |
| 234 |
|
| 235 |
def __init__(self, context): |
| 236 |
self._context = context |
| 237 |
|
| 238 |
def __enter__(self): |
| 239 |
self._prev_context = self.__class__.current_context() |
| 240 |
self.__class__._state.context = self._context |
| 241 |
return self._context |
| 242 |
|
| 243 |
def __exit__(self, *_): |
| 244 |
self.__class__._state.context = self._prev_context |
| 245 |
self._prev_context = None |
| 246 |
return False |
| 247 |
|
| 248 |
|
| 249 |
def tracer_stack_context(): |
| 250 |
""" |
| 251 |
Create a custom Tornado's :class:`StackContext` that allows |
| 252 |
:class:`TornadoScopeManager` to store the active |
| 253 |
:class:`~opentracing.Span` in the thread-local request context. |
| 254 |
|
| 255 |
Suppose you have a method ``handle_request(request)`` in the |
| 256 |
http server. Instead of calling it directly, use a wrapper: |
| 257 |
|
| 258 |
.. code-block:: python |
| 259 |
|
| 260 |
from opentracing.scope_managers.tornado import tracer_stack_context |
| 261 |
|
| 262 |
@tornado.gen.coroutine |
| 263 |
def handle_request_wrapper(request, actual_handler, *args, **kwargs) |
| 264 |
|
| 265 |
request_wrapper = TornadoRequestWrapper(request=request) |
| 266 |
span = http_server.before_request(request=request_wrapper) |
| 267 |
|
| 268 |
with tracer_stack_context(): |
| 269 |
with tracer.scope_manager.activate(span, True): |
| 270 |
return actual_handler(*args, **kwargs) |
| 271 |
|
| 272 |
:return: |
| 273 |
Return a custom :class:`StackContext` that allows |
| 274 |
:class:`TornadoScopeManager` to activate and propagate |
| 275 |
:class:`~opentracing.Span` instances. |
| 276 |
""" |
| 277 |
context = _TracerRequestContext() |
| 278 |
return ThreadSafeStackContext( |
| 279 |
lambda: _TracerRequestContextManager(context) |
| 280 |
) |