Debian Codegraph @

opentracing/scope_managers/asyncio.py

raw
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 asyncio
24
25 from opentracing import Scope
26 from opentracing.scope_managers import ThreadLocalScopeManager
27 from .constants import ACTIVE_ATTR
28
29
30 class AsyncioScopeManager(ThreadLocalScopeManager):
31 """
32 :class:`~opentracing.ScopeManager` implementation for **asyncio**
33 that stores the :class:`~opentracing.Scope` in the current
34 :class:`Task` (:meth:`asyncio.current_task()`), falling back to
35 thread-local storage if none was being executed.
36
37 Automatic :class:`~opentracing.Span` propagation from
38 parent coroutines to their children is not provided, which needs to be
39 done manually:
40
41 .. code-block:: python
42
43 async def child_coroutine(span):
44 # activate the parent Span, but do not finish it upon
45 # deactivation. That will be done by the parent coroutine.
46 with tracer.scope_manager.activate(span, finish_on_close=False):
47 with tracer.start_active_span('child') as scope:
48 ...
49
50 async def parent_coroutine():
51 with tracer.start_active_span('parent') as scope:
52 ...
53 await child_coroutine(span)
54 ...
55
56 """
57
58 def activate(self, span, finish_on_close):
59 """
60 Make a :class:`~opentracing.Span` instance active.
61
62 :param span: the :class:`~opentracing.Span` that should become active.
63 :param finish_on_close: whether *span* should automatically be
64 finished when :meth:`Scope.close()` is called.
65
66 If no :class:`Task` is being executed, thread-local
67 storage will be used to store the :class:`~opentracing.Scope`.
68
69 :return: a :class:`~opentracing.Scope` instance to control the end
70 of the active period for the :class:`~opentracing.Span`.
71 It is a programming error to neglect to call :meth:`Scope.close()`
72 on the returned instance.
73 """
74
75 task = self._get_task()
76 if not task:
77 return super(AsyncioScopeManager, self).activate(span,
78 finish_on_close)
79
80 scope = _AsyncioScope(self, span, finish_on_close)
81 self._set_task_scope(scope, task)
82
83 return scope
84
85 @property
86 def active(self):
87 """
88 Return the currently active :class:`~opentracing.Scope` which
89 can be used to access the currently active
90 :attr:`Scope.span`.
91
92 :return: the :class:`~opentracing.Scope` that is active,
93 or ``None`` if not available.
94 """
95
96 task = self._get_task()
97 if not task:
98 return super(AsyncioScopeManager, self).active
99
100 return self._get_task_scope(task)
101
102 def _get_task(self):
103 try:
104 # Prevent failure when run from a thread
105 # without an event loop.
106 loop = asyncio.get_event_loop()
107 except RuntimeError:
108 return None
109 if hasattr(asyncio, 'current_task'):
110 # Python 3.7+
111 return asyncio.current_task(loop=loop)
112 else:
113 # Python 3.6 and below
114 return asyncio.Task.current_task(loop=loop)
115
116 def _set_task_scope(self, scope, task=None):
117 if task is None:
118 task = self._get_task()
119
120 setattr(task, ACTIVE_ATTR, scope)
121
122 def _get_task_scope(self, task=None):
123 if task is None:
124 task = self._get_task()
125
126 return getattr(task, ACTIVE_ATTR, None)
127
128
129 class _AsyncioScope(Scope):
130 def __init__(self, manager, span, finish_on_close):
131 super(_AsyncioScope, self).__init__(manager, span)
132 self._finish_on_close = finish_on_close
133 self._to_restore = manager.active
134
135 def close(self):
136 if self.manager.active is not self:
137 return
138
139 self.manager._set_task_scope(self._to_restore)
140
141 if self._finish_on_close:
142 self.span.finish()