Skip to content

Commit db47635

Browse files
authored
Merge pull request #374 from DataDog/benjamin/propagate-no-priority
Make HTTPPropagator safe
2 parents 8142e3f + ba95870 commit db47635

File tree

1 file changed

+34
-12
lines changed

1 file changed

+34
-12
lines changed

ddtrace/propagation/http.py

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
import logging
2+
13
from ..context import Context
24

5+
log = logging.getLogger(__name__)
6+
37
# HTTP headers one should set for distributed tracing.
48
# These are cross-language (eg: Python, Go and other implementations should honor these)
59
HTTP_HEADER_TRACE_ID = 'x-datadog-trace-id'
@@ -30,7 +34,10 @@ def parent_call():
3034
"""
3135
headers[HTTP_HEADER_TRACE_ID] = str(span_context.trace_id)
3236
headers[HTTP_HEADER_PARENT_ID] = str(span_context.span_id)
33-
headers[HTTP_HEADER_SAMPLING_PRIORITY] = str(span_context.sampling_priority)
37+
sampling_priority = span_context.sampling_priority
38+
# Propagate priority only if defined
39+
if sampling_priority is not None:
40+
headers[HTTP_HEADER_SAMPLING_PRIORITY] = str(span_context.sampling_priority)
3441

3542
def extract(self, headers):
3643
"""Extract a Context from HTTP headers into a new Context.
@@ -52,14 +59,29 @@ def my_controller(url, headers):
5259
if not headers:
5360
return Context()
5461

55-
trace_id = int(headers.get(HTTP_HEADER_TRACE_ID, 0))
56-
parent_span_id = int(headers.get(HTTP_HEADER_PARENT_ID, 0))
57-
sampling_priority = headers.get(HTTP_HEADER_SAMPLING_PRIORITY)
58-
if sampling_priority is not None:
59-
sampling_priority = int(sampling_priority)
60-
61-
return Context(
62-
trace_id=trace_id,
63-
span_id=parent_span_id,
64-
sampling_priority=sampling_priority,
65-
)
62+
try:
63+
trace_id = int(headers.get(HTTP_HEADER_TRACE_ID, 0))
64+
parent_span_id = int(headers.get(HTTP_HEADER_PARENT_ID, 0))
65+
sampling_priority = headers.get(HTTP_HEADER_SAMPLING_PRIORITY)
66+
if sampling_priority is not None:
67+
sampling_priority = int(sampling_priority)
68+
69+
return Context(
70+
trace_id=trace_id,
71+
span_id=parent_span_id,
72+
sampling_priority=sampling_priority,
73+
)
74+
# If headers are invalid and cannot be parsed, return a new context and log the issue.
75+
except Exception as error:
76+
try:
77+
log.debug(
78+
"invalid x-datadog-* headers, trace-id: %s, parent-id: %s, priority: %s, error: %s",
79+
headers.get(HTTP_HEADER_TRACE_ID, 0),
80+
headers.get(HTTP_HEADER_PARENT_ID, 0),
81+
headers.get(HTTP_HEADER_SAMPLING_PRIORITY),
82+
error,
83+
)
84+
# We might fail on string formatting errors ; in that case only format the first error
85+
except Exception:
86+
log.debug(error)
87+
return Context()

0 commit comments

Comments
 (0)