Debian Codegraph @

aws_xray_sdk/core/recorder.py

raw
1 import logging
2 import time
3 import os
4 import traceback
5 import json
6
7 import wrapt
8
9 from .models.segment import Segment
10 from .models.subsegment import Subsegment
11 from .models.default_dynamic_naming import DefaultDynamicNaming
12 from .models.dummy_entities import DummySegment, DummySubsegment
13 from .emitters.udp_emitter import UDPEmitter
14 from .sampling.default_sampler import DefaultSampler
15 from .context import Context
16 from .plugins.utils import get_plugin_modules
17 from .lambda_launcher import check_in_lambda
18 from .exceptions.exceptions import SegmentNameMissingException
19 from .utils.compat import string_types
20
21 log = logging.getLogger(__name__)
22
23 TRACING_NAME_KEY = 'AWS_XRAY_TRACING_NAME'
24 DAEMON_ADDR_KEY = 'AWS_XRAY_DAEMON_ADDRESS'
25 CONTEXT_MISSING_KEY = 'AWS_XRAY_CONTEXT_MISSING'
26
27
28 class AWSXRayRecorder(object):
29 """
30 A global AWS X-Ray recorder that will begin/end segments/subsegments
31 and send them to the X-Ray daemon. This recorder is initialized during
32 loading time so you can use::
33
34 from aws_xray_sdk.core import xray_recorder
35
36 in your module to access it
37 """
38 def __init__(self):
39
40 context = check_in_lambda()
41 if context:
42 self._context = context
43 self._max_subsegments = 0
44 else:
45 self._context = Context()
46 self._max_subsegments = 30
47
48 self._emitter = UDPEmitter()
49 self._sampler = DefaultSampler()
50 self._sampling = True
51 self._max_trace_back = 10
52 self._plugins = None
53 self._service = os.getenv(TRACING_NAME_KEY)
54 self._dynamic_naming = None
55
56 def configure(self, sampling=None, plugins=None,
57 context_missing=None, sampling_rules=None,
58 daemon_address=None, service=None,
59 context=None, emitter=None,
60 dynamic_naming=None):
61 """Configure global X-Ray recorder.
62
63 Configure needs to run before patching thrid party libraries
64 to avoid creating dangling subsegment.
65
66 :param bool sampling: If sampling is enabled, every time the recorder
67 creates a segment it decides whether to send this segment to
68 the X-Ray daemon. This setting is not used if the recorder
69 is running in AWS Lambda.
70 :param sampling_rules: Pass a set of custom sampling rules.
71 Can be an absolute path of the sampling rule config json file
72 or a dictionary that defines those rules.
73 :param tuple plugins: plugins that add extra metadata to each segment.
74 Currently available plugins are EC2Plugin, ECS plugin and
75 ElasticBeanstalkPlugin.
76 :param str context_missing: recorder behavior when it tries to mutate
77 a segment or add a subsegment but there is no active segment.
78 RUNTIME_ERROR means the recorder will raise an exception.
79 LOG_ERROR means the recorder will only log the error and
80 do nothing.
81 :param str daemon_address: The X-Ray daemon address where the recorder
82 sends data to.
83 :param str service: default segment name if creating a segment without
84 providing a name.
85 :param context: You can pass your own implementation of context storage
86 for active segment/subsegment by overriding the default
87 ``Context`` class.
88 :param emitter: The emitter that sends a segment/subsegment to
89 the X-Ray daemon. You can override ``UDPEmitter`` class.
90 :param dynamic_naming: a string that defines a pattern that host names
91 should match. Alternatively you can pass a module which
92 overrides ``DefaultDynamicNaming`` module.
93
94 Environment variables AWS_XRAY_DAEMON_ADDRESS, AWS_XRAY_CONTEXT_MISSING
95 and AWS_XRAY_TRACING_NAME respectively overrides arguments
96 daemon_address, context_missing and service.
97 """
98 if sampling is not None:
99 self.sampling = sampling
100 if service:
101 self.service = os.getenv(TRACING_NAME_KEY, service)
102 if sampling_rules:
103 self._load_sampling_rules(sampling_rules)
104 if emitter:
105 self.emitter = emitter
106 if daemon_address:
107 self.emitter.set_daemon_address(os.getenv(DAEMON_ADDR_KEY, daemon_address))
108 if context:
109 self.context = context
110 if context_missing:
111 self.context.context_missing = os.getenv(CONTEXT_MISSING_KEY, context_missing)
112 if dynamic_naming:
113 self.dynamic_naming = dynamic_naming
114
115 plugin_modules = None
116 if plugins:
117 plugin_modules = get_plugin_modules(plugins)
118 for module in plugin_modules:
119 module.initialize()
120 self._plugins = plugin_modules
121
122 def begin_segment(self, name=None, traceid=None,
123 parent_id=None, sampling=None):
124 """
125 Begin a segment on the current thread and return it. The recorder
126 only keeps one segment at a time. Create the second one without
127 closing existing one will overwrite it.
128
129 :param str name: the name of the segment
130 :param str traceid: trace id of the segment
131 :param int sampling: 0 means not sampled, 1 means sampled
132 """
133 seg_name = name or self.service
134 if not seg_name:
135 raise SegmentNameMissingException("Segment name is required.")
136
137 # we respect sampling decision regardless of recorder configuration.
138 dummy = False
139 if sampling == 0:
140 dummy = True
141 elif sampling == 1:
142 dummy = False
143 elif self.sampling and not self._sampler.should_trace():
144 dummy = True
145
146 if dummy:
147 segment = DummySegment(seg_name)
148 else:
149 segment = Segment(name=seg_name, traceid=traceid,
150 parent_id=parent_id)
151 self._populate_runtime_context(segment)
152
153 self.context.put_segment(segment)
154 return segment
155
156 def end_segment(self, end_time=None):
157 """
158 End the current segment and send it to X-Ray daemon
159 if it is ready to send. Ready means segment and
160 all its subsegments are closed.
161
162 :param float end_time: segment compeletion in unix epoch in seconds.
163 """
164 self.context.end_segment(end_time)
165 if self.current_segment().ready_to_send():
166 self._send_segment()
167
168 def current_segment(self):
169 """
170 Return the currently active segment. In a multithreading environment,
171 this will make sure the segment returned is the one created by the
172 same thread.
173 """
174 entity = self.get_trace_entity()
175 if self._is_subsegment(entity):
176 return entity.parent_segment
177 else:
178 return entity
179
180 def begin_subsegment(self, name, namespace='local'):
181 """
182 Begin a new subsegment.
183 If there is open subsegment, the newly created subsegment will be the
184 child of latest opened subsegment.
185 If not, it will be the child of the current open segment.
186
187 :param str name: the name of the subsegment.
188 :param str namespace: currently can only be 'local', 'remote', 'aws'.
189 """
190 segment = self.current_segment()
191 if not segment:
192 log.warning("No segment found, cannot begin subsegment %s." % name)
193 return None
194
195 if not segment.sampled:
196 subsegment = DummySubsegment(segment, name)
197 else:
198 subsegment = Subsegment(name, namespace, segment)
199
200 self.context.put_subsegment(subsegment)
201
202 return subsegment
203
204 def current_subsegment(self):
205 """
206 Return the latest opened subsegment. In a multithreading environment,
207 this will make sure the subsegment returned is one created
208 by the same thread.
209 """
210 entity = self.get_trace_entity()
211 if self._is_subsegment(entity):
212 return entity
213 else:
214 return None
215
216 def end_subsegment(self, end_time=None):
217 """
218 End the current active subsegment. If this is the last one open
219 under its parent segment, the entire segment will be sent.
220
221 :param float end_time: subsegment compeletion in unix epoch in seconds.
222 """
223 if not self.context.end_subsegment(end_time):
224 return
225
226 # if segment is already close, we check if we can send entire segment
227 # otherwise we check if we need to stream some subsegments
228 if self.current_segment().ready_to_send():
229 self._send_segment()
230 else:
231 self.stream_subsegments()
232
233 def get_trace_entity(self):
234 """
235 A pass through method to ``context.get_trace_entity()``.
236 """
237 return self.context.get_trace_entity()
238
239 def set_trace_entity(self, trace_entity):
240 """
241 A pass through method to ``context.set_trace_entity()``.
242 """
243 self.context.set_trace_entity(trace_entity)
244
245 def clear_trace_entities(self):
246 """
247 A pass through method to ``context.clear_trace_entities()``.
248 """
249 self.context.clear_trace_entities()
250
251 def stream_subsegments(self):
252 """
253 Stream all closed subsegments to the daemon
254 and remove reference to the parent segment.
255 No-op for a not sampled segment.
256 """
257 segment = self.current_segment()
258
259 if not segment or not segment.sampled:
260 return
261
262 if segment.get_total_subsegments_size() <= self._max_subsegments:
263 return
264
265 # find all subsegments that has no open child subsegments and
266 # send them to the daemon
267 self._stream_eligible_subsegments(segment)
268
269 def _stream_eligible_subsegments(self, subsegment):
270
271 children = subsegment.subsegments
272
273 children_ready = []
274 if len(children) > 0:
275 for child in children:
276 if self._stream_eligible_subsegments(child):
277 children_ready.append(child)
278
279 if len(children_ready) == len(children) and not subsegment.in_progress:
280 return True
281
282 # stream all ready children before return False
283 for child in children_ready:
284 self._stream_subsegment(child)
285 subsegment.remove_subsegment(child)
286
287 return False
288
289 def capture(self, name=None):
290 """
291 A decorator that records enclosed function in a subsegment.
292 It only works with synchronous functions.
293
294 params str name: The name of the subsegment. If not specified
295 the function name will be used.
296 """
297 @wrapt.decorator
298 def wrapper(wrapped, instance, args, kwargs):
299 func_name = name
300 if not func_name:
301 func_name = wrapped.__name__
302
303 return self.record_subsegment(
304 wrapped, instance, args, kwargs,
305 name=func_name,
306 namespace='local',
307 meta_processor=None,
308 )
309
310 return wrapper
311
312 def record_subsegment(self, wrapped, instance, args, kwargs, name,
313 namespace, meta_processor):
314
315 subsegment = self.begin_subsegment(name, namespace)
316
317 exception = None
318 stack = None
319 return_value = None
320
321 try:
322 return_value = wrapped(*args, **kwargs)
323 return return_value
324 except Exception as e:
325 exception = e
326 stack = traceback.extract_stack(limit=self._max_trace_back)
327 raise
328 finally:
329 end_time = time.time()
330 if callable(meta_processor):
331 meta_processor(
332 wrapped=wrapped,
333 instance=instance,
334 args=args,
335 kwargs=kwargs,
336 return_value=return_value,
337 exception=exception,
338 subsegment=subsegment,
339 stack=stack,
340 )
341 elif exception:
342 if subsegment:
343 subsegment.add_exception(exception, stack)
344
345 self.end_subsegment(end_time)
346
347 def _populate_runtime_context(self, segment):
348 if not self._plugins:
349 return
350
351 aws_meta = {}
352 for plugin in self._plugins:
353 if plugin.runtime_context:
354 aws_meta[plugin.SERVICE_NAME] = plugin.runtime_context
355 setattr(segment, 'origin', plugin.ORIGIN)
356 segment.set_aws(aws_meta)
357
358 def _send_segment(self):
359 """
360 Send the current segment to X-Ray daemon if it is present and
361 sampled, then clean up context storage.
362 The emitter will handle failures.
363 """
364 segment = self.current_segment()
365
366 if not segment:
367 return
368
369 if segment.sampled:
370 self.emitter.send_entity(segment)
371 self.clear_trace_entities()
372
373 def _stream_subsegment(self, subsegment):
374
375 log.debug("streaming subsegments...")
376 self.emitter.send_entity(subsegment)
377
378 def _load_sampling_rules(self, sampling_rules):
379
380 if not sampling_rules:
381 return
382
383 if isinstance(sampling_rules, dict):
384 self.sampler = DefaultSampler(sampling_rules)
385 else:
386 with open(sampling_rules) as f:
387 self.sampler = DefaultSampler(json.load(f))
388
389 def _is_subsegment(self, entity):
390
391 return (hasattr(entity, 'type') and entity.type == 'subsegment')
392
393 @property
394 def sampling(self):
395 return self._sampling
396
397 @sampling.setter
398 def sampling(self, value):
399 self._sampling = value
400
401 @property
402 def sampler(self):
403 return self._sampler
404
405 @sampler.setter
406 def sampler(self, value):
407 self._sampler = value
408
409 @property
410 def service(self):
411 return self._service
412
413 @service.setter
414 def service(self, value):
415 self._service = value
416
417 @property
418 def dynamic_naming(self):
419 return self._dynamic_naming
420
421 @dynamic_naming.setter
422 def dynamic_naming(self, value):
423 if isinstance(value, string_types):
424 self._dynamic_naming = DefaultDynamicNaming(value, self.service)
425 else:
426 self._dynamic_naming = value
427
428 @property
429 def context(self):
430 return self._context
431
432 @context.setter
433 def context(self, cxt):
434 self._context = cxt
435
436 @property
437 def emitter(self):
438 return self._emitter
439
440 @emitter.setter
441 def emitter(self, value):
442 self._emitter = value