Debian Codegraph @

opentracing/tracer.py

raw
1 # Copyright The OpenTracing Authors
2 # Copyright Uber Technologies, Inc
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 from __future__ import absolute_import
17 from collections import namedtuple
18 from .span import Span
19 from .span import SpanContext
20 from .scope import Scope
21 from .scope_manager import ScopeManager
22 from .propagation import Format, UnsupportedFormatException
23
24
25 class Tracer(object):
26 """Tracer is the entry point API between instrumentation code and the
27 tracing implementation.
28
29 This implementation both defines the public Tracer API, and provides
30 a default no-op behavior.
31 """
32
33 _supported_formats = [Format.TEXT_MAP, Format.BINARY, Format.HTTP_HEADERS]
34
35 def __init__(self, scope_manager=None):
36 self._scope_manager = ScopeManager() if scope_manager is None \
37 else scope_manager
38 self._noop_span_context = SpanContext()
39 self._noop_span = Span(tracer=self, context=self._noop_span_context)
40 self._noop_scope = Scope(self._scope_manager, self._noop_span)
41
42 @property
43 def scope_manager(self):
44 """Provides access to the current :class:`~opentracing.ScopeManager`.
45
46 :rtype: :class:`~opentracing.ScopeManager`
47 """
48 return self._scope_manager
49
50 @property
51 def active_span(self):
52 """Provides access to the the active :class:`Span`. This is a shorthand for
53 :attr:`Tracer.scope_manager.active.span`, and ``None`` will be
54 returned if :attr:`Scope.span` is ``None``.
55
56 :rtype: :class:`~opentracing.Span`
57 :return: the active :class:`Span`.
58 """
59 scope = self._scope_manager.active
60 return None if scope is None else scope.span
61
62 def start_active_span(self,
63 operation_name,
64 child_of=None,
65 references=None,
66 tags=None,
67 start_time=None,
68 ignore_active_span=False,
69 finish_on_close=True):
70 """Returns a newly started and activated :class:`Scope`.
71
72 The returned :class:`Scope` supports with-statement contexts. For
73 example::
74
75 with tracer.start_active_span('...') as scope:
76 scope.span.set_tag('http.method', 'GET')
77 do_some_work()
78 # Span.finish() is called as part of scope deactivation through
79 # the with statement.
80
81 It's also possible to not finish the :class:`Span` when the
82 :class:`Scope` context expires::
83
84 with tracer.start_active_span('...',
85 finish_on_close=False) as scope:
86 scope.span.set_tag('http.method', 'GET')
87 do_some_work()
88 # Span.finish() is not called as part of Scope deactivation as
89 # `finish_on_close` is `False`.
90
91 :param operation_name: name of the operation represented by the new
92 :class:`Span` from the perspective of the current service.
93 :type operation_name: str
94
95 :param child_of: (optional) a :class:`Span` or :class:`SpanContext`
96 instance representing the parent in a REFERENCE_CHILD_OF reference.
97 If specified, the `references` parameter must be omitted.
98 :type child_of: Span or SpanContext
99
100 :param references: (optional) references that identify one or more
101 parent :class:`SpanContext`\\ s. (See the Reference documentation
102 for detail).
103 :type references: :obj:`list` of :class:`Reference`
104
105 :param tags: an optional dictionary of :class:`Span` tags. The caller
106 gives up ownership of that dictionary, because the :class:`Tracer`
107 may use it as-is to avoid extra data copying.
108 :type tags: dict
109
110 :param start_time: an explicit :class:`Span` start time as a unix
111 timestamp per :meth:`time.time()`.
112 :type start_time: float
113
114 :param ignore_active_span: (optional) an explicit flag that ignores
115 the current active :class:`Scope` and creates a root :class:`Span`.
116 :type ignore_active_span: bool
117
118 :param finish_on_close: whether :class:`Span` should automatically be
119 finished when :meth:`Scope.close()` is called.
120 :type finish_on_close: bool
121
122 :rtype: Scope
123 :return: a :class:`Scope`, already registered via the
124 :class:`ScopeManager`.
125 """
126 return self._noop_scope
127
128 def start_span(self,
129 operation_name=None,
130 child_of=None,
131 references=None,
132 tags=None,
133 start_time=None,
134 ignore_active_span=False):
135 """Starts and returns a new :class:`Span` representing a unit of work.
136
137
138 Starting a root :class:`Span` (a :class:`Span` with no causal
139 references)::
140
141 tracer.start_span('...')
142
143
144 Starting a child :class:`Span` (see also :meth:`start_child_span()`)::
145
146 tracer.start_span(
147 '...',
148 child_of=parent_span)
149
150
151 Starting a child :class:`Span` in a more verbose way::
152
153 tracer.start_span(
154 '...',
155 references=[opentracing.child_of(parent_span)])
156
157
158 :param operation_name: name of the operation represented by the new
159 :class:`Span` from the perspective of the current service.
160 :type operation_name: str
161
162 :param child_of: (optional) a :class:`Span` or :class:`SpanContext`
163 representing the parent in a REFERENCE_CHILD_OF reference. If
164 specified, the `references` parameter must be omitted.
165 :type child_of: Span or SpanContext
166
167 :param references: (optional) references that identify one or more
168 parent :class:`SpanContext`\\ s. (See the Reference documentation
169 for detail).
170 :type references: :obj:`list` of :class:`Reference`
171
172 :param tags: an optional dictionary of :class:`Span` tags. The caller
173 gives up ownership of that dictionary, because the :class:`Tracer`
174 may use it as-is to avoid extra data copying.
175 :type tags: dict
176
177 :param start_time: an explicit Span start time as a unix timestamp per
178 :meth:`time.time()`
179 :type start_time: float
180
181 :param ignore_active_span: an explicit flag that ignores the current
182 active :class:`Scope` and creates a root :class:`Span`.
183 :type ignore_active_span: bool
184
185 :rtype: Span
186 :return: an already-started :class:`Span` instance.
187 """
188 return self._noop_span
189
190 def inject(self, span_context, format, carrier):
191 """Injects `span_context` into `carrier`.
192
193 The type of `carrier` is determined by `format`. See the
194 :class:`Format` class/namespace for the built-in OpenTracing formats.
195
196 Implementations *must* raise :exc:`UnsupportedFormatException` if
197 `format` is unknown or disallowed.
198
199 :param span_context: the :class:`SpanContext` instance to inject
200 :type span_context: SpanContext
201
202 :param format: a python object instance that represents a given
203 carrier format. `format` may be of any type, and `format` equality
204 is defined by python ``==`` equality.
205 :type format: Format
206 :param carrier: the format-specific carrier object to inject into
207 """
208 if format in Tracer._supported_formats:
209 return
210 raise UnsupportedFormatException(format)
211
212 def extract(self, format, carrier):
213 """Returns a :class:`SpanContext` instance extracted from a `carrier` of the
214 given `format`, or ``None`` if no such :class:`SpanContext` could be
215 found.
216
217 The type of `carrier` is determined by `format`. See the
218 :class:`Format` class/namespace for the built-in OpenTracing formats.
219
220 Implementations *must* raise :exc:`UnsupportedFormatException` if
221 `format` is unknown or disallowed.
222
223 Implementations may raise :exc:`InvalidCarrierException`,
224 :exc:`SpanContextCorruptedException`, or implementation-specific errors
225 if there are problems with `carrier`.
226
227
228 :param format: a python object instance that represents a given
229 carrier format. `format` may be of any type, and `format` equality
230 is defined by python ``==`` equality.
231
232 :param carrier: the format-specific carrier object to extract from
233
234 :rtype: SpanContext
235 :return: a :class:`SpanContext` extracted from `carrier` or ``None`` if
236 no such :class:`SpanContext` could be found.
237 """
238 if format in Tracer._supported_formats:
239 return self._noop_span_context
240 raise UnsupportedFormatException(format)
241
242
243 class ReferenceType(object):
244 """A namespace for OpenTracing reference types.
245
246 See http://opentracing.io/spec for more detail about references,
247 reference types, and CHILD_OF and FOLLOWS_FROM in particular.
248 """
249 CHILD_OF = 'child_of'
250 FOLLOWS_FROM = 'follows_from'
251
252
253 # We use namedtuple since references are meant to be immutable.
254 # We subclass it to expose a standard docstring.
255 class Reference(namedtuple('Reference', ['type', 'referenced_context'])):
256 """A Reference pairs a reference type with a referenced :class:`SpanContext`.
257
258 References are used by :meth:`Tracer.start_span()` to describe the
259 relationships between :class:`Span`\\ s.
260
261 :class:`Tracer` implementations must ignore references where
262 referenced_context is ``None``. This behavior allows for simpler code when
263 an inbound RPC request contains no tracing information and as a result
264 :meth:`Tracer.extract()` returns ``None``::
265
266 parent_ref = tracer.extract(opentracing.HTTP_HEADERS, request.headers)
267 span = tracer.start_span(
268 'operation', references=child_of(parent_ref)
269 )
270
271 See :meth:`child_of` and :meth:`follows_from` helpers for creating these
272 references.
273 """
274 pass
275
276
277 def child_of(referenced_context=None):
278 """child_of is a helper that creates CHILD_OF References.
279
280 :param referenced_context: the (causal parent) :class:`SpanContext` to
281 reference. If ``None`` is passed, this reference must be ignored by
282 the :class:`Tracer`.
283 :type referenced_context: SpanContext
284
285 :rtype: Reference
286 :return: A reference suitable for ``Tracer.start_span(...,
287 references=...)``
288 """
289 return Reference(
290 type=ReferenceType.CHILD_OF,
291 referenced_context=referenced_context)
292
293
294 def follows_from(referenced_context=None):
295 """follows_from is a helper that creates FOLLOWS_FROM References.
296
297 :param referenced_context: the (causal parent) :class:`SpanContext` to
298 reference. If ``None`` is passed, this reference must be ignored by the
299 :class:`Tracer`.
300 :type referenced_context: SpanContext
301
302 :rtype: Reference
303 :return: A Reference suitable for ``Tracer.start_span(...,
304 references=...)``
305 """
306 return Reference(
307 type=ReferenceType.FOLLOWS_FROM,
308 referenced_context=referenced_context)
309
310
311 def start_child_span(parent_span, operation_name, tags=None, start_time=None):
312 """A shorthand method that starts a `child_of` :class:`Span` for a given
313 parent :class:`Span`.
314
315 Equivalent to calling::
316
317 parent_span.tracer().start_span(
318 operation_name,
319 references=opentracing.child_of(parent_span.context),
320 tags=tags,
321 start_time=start_time)
322
323 :param parent_span: the :class:`Span` which will act as the parent in the
324 returned :class:`Span`\\ s child_of reference.
325 :type parent_span: Span
326
327 :param operation_name: the operation name for the child :class:`Span`
328 instance
329 :type operation_name: str
330
331 :param tags: optional dict of :class:`Span` tags. The caller gives up
332 ownership of that dict, because the :class:`Tracer` may use it as-is to
333 avoid extra data copying.
334 :type tags: dict
335
336 :param start_time: an explicit :class:`Span` start time as a unix timestamp
337 per :meth:`time.time()`.
338 :type start_time: float
339
340 :rtype: Span
341 :return: an already-started :class:`Span` instance.
342 """
343 return parent_span.tracer.start_span(
344 operation_name=operation_name,
345 child_of=parent_span,
346 tags=tags,
347 start_time=start_time
348 )