Skip to content

Commit

Permalink
Handle B3 trace_id and span_id correctly
Browse files Browse the repository at this point in the history
Fixes open-telemetry#933

These fields are not being handled correctly when one or both of them
receive invalid values.
  • Loading branch information
ocelotl committed Aug 5, 2020
1 parent 8b1da35 commit c03f2e0
Showing 1 changed file with 19 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
# limitations under the License.

import typing
from re import fullmatch

import opentelemetry.trace as trace
from opentelemetry.sdk.trace import generate_trace_id, generate_span_id
from opentelemetry.context import Context
from opentelemetry.trace.propagation.httptextformat import (
Getter,
Expand Down Expand Up @@ -95,19 +97,33 @@ def extract(
or flags
)

if (
fullmatch(r"[\da-fA-F]{16}|[\da-fA-F]{32}", trace_id) is None or
fullmatch(r"[\da-fA-F]{16}", span_id) is None
):
trace_id = generate_trace_id()
span_id = generate_span_id()

options = 0
# The b3 spec provides no defined behavior for both sample and
# flag values set. Since the setting of at least one implies
# the desire for some form of sampling, propagate if either
# header is set to allow.
if sampled in self._SAMPLE_PROPAGATE_VALUES or flags == "1":
options |= trace.TraceFlags.SAMPLED

if isinstance(trace_id, str):
trace_id = int(trace_id, 16)

if isinstance(span_id, str):
span_id = int(span_id, 16)

return trace.set_span_in_context(
trace.DefaultSpan(
trace.SpanContext(
# trace an span ids are encoded in hex, so must be converted
trace_id=int(trace_id, 16),
span_id=int(span_id, 16),
trace_id=trace_id,
span_id=span_id,
is_remote=True,
trace_flags=trace.TraceFlags(options),
trace_state=trace.TraceState(),
Expand All @@ -123,7 +139,7 @@ def inject(
) -> None:
span = trace.get_current_span(context=context)

if span.get_context() == trace.INVALID_SPAN_CONTEXT:
if span is None:
return

sampled = (trace.TraceFlags.SAMPLED & span.context.trace_flags) != 0
Expand Down

0 comments on commit c03f2e0

Please sign in to comment.