Debian Codegraph @

opentracing/span.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 . import logs
18
19 from opentracing.ext import tags
20
21
22 class SpanContext(object):
23 """SpanContext represents :class:`Span` state that must propagate to
24 descendant :class:`Span`\\ s and across process boundaries.
25
26 SpanContext is logically divided into two pieces: the user-level "Baggage"
27 (see :meth:`Span.set_baggage_item` and :meth:`Span.get_baggage_item`) that
28 propagates across :class:`Span` boundaries and any
29 tracer-implementation-specific fields that are needed to identify or
30 otherwise contextualize the associated :class:`Span` (e.g., a ``(trace_id,
31 span_id, sampled)`` tuple).
32 """
33
34 EMPTY_BAGGAGE = {} # TODO would be nice to make this immutable
35
36 @property
37 def baggage(self):
38 """
39 Return baggage associated with this :class:`SpanContext`.
40 If no baggage has been added to the :class:`Span`, returns an empty
41 dict.
42
43 The caller must not modify the returned dictionary.
44
45 See also: :meth:`Span.set_baggage_item()` /
46 :meth:`Span.get_baggage_item()`
47
48 :rtype: dict
49 :return: baggage associated with this :class:`SpanContext` or ``{}``.
50 """
51 return SpanContext.EMPTY_BAGGAGE
52
53
54 class Span(object):
55 """
56 Span represents a unit of work executed on behalf of a trace. Examples of
57 spans include a remote procedure call, or a in-process method call to a
58 sub-component. Every span in a trace may have zero or more causal parents,
59 and these relationships transitively form a DAG. It is common for spans to
60 have at most one parent, and thus most traces are merely tree structures.
61
62 Span implements a context manager API that allows the following usage::
63
64 with tracer.start_span(operation_name='go_fishing') as span:
65 call_some_service()
66
67 In the context manager syntax it's not necessary to call
68 :meth:`Span.finish()`
69 """
70
71 def __init__(self, tracer, context):
72 self._tracer = tracer
73 self._context = context
74
75 @property
76 def context(self):
77 """Provides access to the :class:`SpanContext` associated with this
78 :class:`Span`.
79
80 The :class:`SpanContext` contains state that propagates from
81 :class:`Span` to :class:`Span` in a larger trace.
82
83 :rtype: SpanContext
84 :return: the :class:`SpanContext` associated with this :class:`Span`.
85 """
86 return self._context
87
88 @property
89 def tracer(self):
90 """Provides access to the :class:`Tracer` that created this
91 :class:`Span`.
92
93 :rtype: Tracer
94 :return: the :class:`Tracer` that created this :class:`Span`.
95 """
96 return self._tracer
97
98 def set_operation_name(self, operation_name):
99 """Changes the operation name.
100
101 :param operation_name: the new operation name
102 :type operation_name: str
103
104 :rtype: Span
105 :return: the :class:`Span` itself, for call chaining.
106 """
107 return self
108
109 def finish(self, finish_time=None):
110 """Indicates that the work represented by this :class:`Span` has completed or
111 terminated.
112
113 With the exception of the :attr:`Span.context` property, the semantics
114 of all other :class:`Span` methods are undefined after
115 :meth:`Span.finish()` has been invoked.
116
117 :param finish_time: an explicit :class:`Span` finish timestamp as a
118 unix timestamp per :meth:`time.time()`
119 :type finish_time: float
120 """
121 pass
122
123 def set_tag(self, key, value):
124 """Attaches a key/value pair to the :class:`Span`.
125
126 The value must be a string, a bool, or a numeric type.
127
128 If the user calls set_tag multiple times for the same key,
129 the behavior of the :class:`Tracer` is undefined, i.e. it is
130 implementation specific whether the :class:`Tracer` will retain the
131 first value, or the last value, or pick one randomly, or even keep all
132 of them.
133
134 :param key: key or name of the tag. Must be a string.
135 :type key: str
136
137 :param value: value of the tag.
138 :type value: string or bool or int or float
139
140 :rtype: Span
141 :return: the :class:`Span` itself, for call chaining.
142 """
143 return self
144
145 def log_kv(self, key_values, timestamp=None):
146 """Adds a log record to the :class:`Span`.
147
148 For example::
149
150 span.log_kv({
151 "event": "time to first byte",
152 "packet.size": packet.size()})
153
154 span.log_kv({"event": "two minutes ago"}, time.time() - 120)
155
156 :param key_values: A dict of string keys and values of any type
157 :type key_values: dict
158
159 :param timestamp: A unix timestamp per :meth:`time.time()`; current
160 time if ``None``
161 :type timestamp: float
162
163 :rtype: Span
164 :return: the :class:`Span` itself, for call chaining.
165 """
166 return self
167
168 def set_baggage_item(self, key, value):
169 """Stores a Baggage item in the :class:`Span` as a key/value pair.
170
171 Enables powerful distributed context propagation functionality where
172 arbitrary application data can be carried along the full path of
173 request execution throughout the system.
174
175 Note 1: Baggage is only propagated to the future (recursive) children
176 of this :class:`Span`.
177
178 Note 2: Baggage is sent in-band with every subsequent local and remote
179 calls, so this feature must be used with care.
180
181 :param key: Baggage item key
182 :type key: str
183
184 :param value: Baggage item value
185 :type value: str
186
187 :rtype: Span
188 :return: itself, for chaining the calls.
189 """
190 return self
191
192 def get_baggage_item(self, key):
193 """Retrieves value of the baggage item with the given key.
194
195 :param key: key of the baggage item
196 :type key: str
197
198 :rtype: str
199 :return: value of the baggage item with given key, or ``None``.
200 """
201 return None
202
203 def __enter__(self):
204 """Invoked when :class:`Span` is used as a context manager.
205
206 :rtype: Span
207 :return: the :class:`Span` itself
208 """
209 return self
210
211 def __exit__(self, exc_type, exc_val, exc_tb):
212 """Ends context manager and calls finish() on the :class:`Span`.
213
214 If exception has occurred during execution, it is automatically logged
215 and added as a tag. :attr:`~operation.ext.tags.ERROR` will also be set
216 to `True`.
217 """
218 Span._on_error(self, exc_type, exc_val, exc_tb)
219 self.finish()
220
221 @staticmethod
222 def _on_error(span, exc_type, exc_val, exc_tb):
223 if not span or not exc_val:
224 return
225
226 span.set_tag(tags.ERROR, True)
227 span.log_kv({
228 logs.EVENT: tags.ERROR,
229 logs.MESSAGE: str(exc_val),
230 logs.ERROR_OBJECT: exc_val,
231 logs.ERROR_KIND: exc_type,
232 logs.STACK: exc_tb,
233 })
234
235 def log_event(self, event, payload=None):
236 """DEPRECATED"""
237 if payload is None:
238 return self.log_kv({logs.EVENT: event})
239 else:
240 return self.log_kv({logs.EVENT: event, 'payload': payload})
241
242 def log(self, **kwargs):
243 """DEPRECATED"""
244 key_values = {}
245 if logs.EVENT in kwargs:
246 key_values[logs.EVENT] = kwargs[logs.EVENT]
247 if 'payload' in kwargs:
248 key_values['payload'] = kwargs['payload']
249 timestamp = None
250 if 'timestamp' in kwargs:
251 timestamp = kwargs['timestamp']
252 return self.log_kv(key_values, timestamp)