Skip to content

Commit 7f11feb

Browse files
authored
Context copy improvements (#2585)
* Context copy improvements Each span needs its own context copy as the `span.context` property returns the trace context specialized with the span's id. The lock is removed from `context._with_span` as the copied references are not volatile. * Handle possibly none context The span._context can possibly be None but only when not using the main tracer APIs. Add a safeguard in case the main APIs are not used. * Don't set none attributes on initialize This prevents needless lock acquisition when initializing context objects.
1 parent 8969b51 commit 7f11feb

File tree

2 files changed

+12
-14
lines changed

2 files changed

+12
-14
lines changed

ddtrace/context.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,10 @@ class Context(object):
3535
_metrics = attr.ib(factory=dict) # type: _MetricDictType
3636

3737
def __attrs_post_init__(self):
38-
self.dd_origin = self._dd_origin
39-
self.sampling_priority = self._sampling_priority
38+
if self._dd_origin is not None:
39+
self.dd_origin = self._dd_origin
40+
if self._sampling_priority is not None:
41+
self.sampling_priority = self._sampling_priority
4042
del self._dd_origin
4143
del self._sampling_priority
4244

@@ -52,12 +54,11 @@ def __eq__(self, other):
5254
def _with_span(self, span):
5355
# type: (Span) -> Context
5456
"""Return a shallow copy of the context with the given span."""
55-
with self._lock:
56-
ctx = self.__class__(trace_id=span.trace_id, span_id=span.span_id)
57-
ctx._lock = self._lock
58-
ctx._meta = self._meta
59-
ctx._metrics = self._metrics
60-
return ctx
57+
ctx = self.__class__(trace_id=span.trace_id, span_id=span.span_id)
58+
ctx._lock = self._lock
59+
ctx._meta = self._meta
60+
ctx._metrics = self._metrics
61+
return ctx
6162

6263
def _update_tags(self, span):
6364
# type: (Span) -> None

ddtrace/span.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def __init__(
146146
# sampling
147147
self.sampled = True # type: bool
148148

149-
self._context = context # type: Optional[Context]
149+
self._context = context._with_span(self) if context else None # type: Optional[Context]
150150
self._parent = None # type: Optional[Span]
151151
self._ignored_exceptions = None # type: Optional[List[Exception]]
152152
self._local_root = None # type: Optional[Span]
@@ -504,11 +504,8 @@ def context(self):
504504
# type: () -> Context
505505
"""Return the trace context for this span."""
506506
if self._context is None:
507-
ctx = Context(trace_id=self.trace_id, span_id=self.span_id)
508-
self._context = ctx
509-
else:
510-
ctx = self._context._with_span(self)
511-
return ctx
507+
self._context = Context(trace_id=self.trace_id, span_id=self.span_id)
508+
return self._context
512509

513510
def __enter__(self):
514511
return self

0 commit comments

Comments
 (0)