Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for B3 parentspanid #286

Merged
merged 5 commits into from
Jan 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
from opentelemetry import propagators
from opentelemetry.ext.opentracing_shim import util
from opentelemetry.ext.opentracing_shim.version import __version__
from opentelemetry.trace import DefaultSpan

logger = logging.getLogger(__name__)

Expand All @@ -101,10 +102,10 @@ def create_tracer(otel_tracer_source):
:class:`opentracing.Tracer` using OpenTelemetry under the hood.

Args:
otel_tracer_source: A :class:`opentelemetry.trace.TracerSource` to be used for
constructing the :class:`TracerShim`. A tracer from this source will be used
to perform the actual tracing when user code is instrumented using
the OpenTracing API.
otel_tracer_source: A :class:`opentelemetry.trace.TracerSource` to be
used for constructing the :class:`TracerShim`. A tracer from this
source will be used to perform the actual tracing when user code is
instrumented using the OpenTracing API.

Returns:
The created :class:`TracerShim`.
Expand Down Expand Up @@ -667,12 +668,16 @@ def inject(self, span_context, format, carrier):
# uses the configured propagators in opentelemetry.propagators.
# TODO: Support Format.BINARY once it is supported in
# opentelemetry-python.

if format not in self._supported_formats:
raise opentracing.UnsupportedFormatException

propagator = propagators.get_global_httptextformat()

propagator.inject(
span_context.unwrap(), type(carrier).__setitem__, carrier
DefaultSpan(span_context.unwrap()),
type(carrier).__setitem__,
carrier,
)

def extract(self, format, carrier):
Expand Down
15 changes: 10 additions & 5 deletions ext/opentelemetry-ext-opentracing-shim/tests/test_shim.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import time
import unittest
from unittest import TestCase

import opentracing

Expand All @@ -24,7 +24,7 @@
from opentelemetry.sdk.trace import TracerSource


class TestShim(unittest.TestCase):
class TestShim(TestCase):
# pylint: disable=too-many-public-methods

def setUp(self):
Expand Down Expand Up @@ -486,6 +486,7 @@ def test_inject_text_map(self):

# Verify Format.TEXT_MAP
text_map = {}

self.shim.inject(context, opentracing.Format.TEXT_MAP, text_map)
self.assertEqual(text_map[MockHTTPTextFormat.TRACE_ID_KEY], str(1220))
self.assertEqual(text_map[MockHTTPTextFormat.SPAN_ID_KEY], str(7478))
Expand Down Expand Up @@ -551,6 +552,10 @@ def extract(cls, get_from_carrier, carrier):
)

@classmethod
def inject(cls, context, set_in_carrier, carrier):
set_in_carrier(carrier, cls.TRACE_ID_KEY, str(context.trace_id))
set_in_carrier(carrier, cls.SPAN_ID_KEY, str(context.span_id))
def inject(cls, span, set_in_carrier, carrier):
set_in_carrier(
carrier, cls.TRACE_ID_KEY, str(span.get_context().trace_id)
)
set_in_carrier(
carrier, cls.SPAN_ID_KEY, str(span.get_context().span_id)
)
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import abc
import typing

from opentelemetry.trace import SpanContext
from opentelemetry.trace import Span, SpanContext

_T = typing.TypeVar("_T")

Expand Down Expand Up @@ -95,9 +95,9 @@ def extract(

@abc.abstractmethod
def inject(
self, context: SpanContext, set_in_carrier: Setter[_T], carrier: _T
self, span: Span, set_in_carrier: Setter[_T], carrier: _T
) -> None:
"""Inject values from a SpanContext into a carrier.
"""Inject values from a Span into a carrier.

inject enables the propagation of values into HTTP clients or
other objects which perform an HTTP request. Implementations
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,13 @@ def extract(
@classmethod
def inject(
cls,
context: trace.SpanContext,
span: trace.Span,
set_in_carrier: httptextformat.Setter[_T],
carrier: _T,
) -> None:

context = span.get_context()

if context == trace.INVALID_SPAN_CONTEXT:
return
traceparent_string = "00-{:032x}-{:016x}-{:02x}".format(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def inject(
should know how to set header values on the carrier.
"""
get_global_httptextformat().inject(
tracer.get_current_span().get_context(), set_in_carrier, carrier
tracer.get_current_span(), set_in_carrier, carrier
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import typing
import unittest
from unittest.mock import Mock

from opentelemetry import trace
from opentelemetry.context.propagation import tracecontexthttptextformat
Expand All @@ -38,7 +39,8 @@ def test_no_traceparent_header(self):

RFC 4.2.2:

If no traceparent header is received, the vendor creates a new trace-id and parent-id that represents the current request.
If no traceparent header is received, the vendor creates a new
trace-id and parent-id that represents the current request.
"""
output = {} # type:typing.Dict[str, typing.List[str]]
span_context = FORMAT.extract(get_as_list, output)
Expand Down Expand Up @@ -66,8 +68,10 @@ def test_headers_with_tracestate(self):
span_context.trace_state, {"foo": "1", "bar": "2", "baz": "3"}
)

mock_span = Mock()
mock_span.configure_mock(**{"get_context.return_value": span_context})
output = {} # type:typing.Dict[str, str]
FORMAT.inject(span_context, dict.__setitem__, output)
FORMAT.inject(mock_span, dict.__setitem__, output)
self.assertEqual(output["traceparent"], traceparent_value)
for pair in ["foo=1", "bar=2", "baz=3"]:
self.assertIn(pair, output["tracestate"])
Expand All @@ -81,13 +85,16 @@ def test_invalid_trace_id(self):

RFC 3.2.2.3

If the trace-id value is invalid (for example if it contains non-allowed characters or all
zeros), vendors MUST ignore the traceparent.
If the trace-id value is invalid (for example if it contains
non-allowed characters or all zeros), vendors MUST ignore the
traceparent.

RFC 3.3

If the vendor failed to parse traceparent, it MUST NOT attempt to parse tracestate.
Note that the opposite is not true: failure to parse tracestate MUST NOT affect the parsing of traceparent.
If the vendor failed to parse traceparent, it MUST NOT attempt to
parse tracestate.
Note that the opposite is not true: failure to parse tracestate MUST
NOT affect the parsing of traceparent.
"""
span_context = FORMAT.extract(
get_as_list,
Expand All @@ -101,19 +108,22 @@ def test_invalid_trace_id(self):
self.assertEqual(span_context, trace.INVALID_SPAN_CONTEXT)

def test_invalid_parent_id(self):
"""If the parent id is invalid, we must ignore the full traceparent header.
"""If the parent id is invalid, we must ignore the full traceparent
header.

Also ignore any tracestate.

RFC 3.2.2.3

Vendors MUST ignore the traceparent when the parent-id is invalid (for example,
if it contains non-lowercase hex characters).
Vendors MUST ignore the traceparent when the parent-id is invalid (for
example, if it contains non-lowercase hex characters).

RFC 3.3

If the vendor failed to parse traceparent, it MUST NOT attempt to parse tracestate.
Note that the opposite is not true: failure to parse tracestate MUST NOT affect the parsing of traceparent.
If the vendor failed to parse traceparent, it MUST NOT attempt to parse
tracestate.
Note that the opposite is not true: failure to parse tracestate MUST
NOT affect the parsing of traceparent.
"""
span_context = FORMAT.extract(
get_as_list,
Expand All @@ -131,15 +141,19 @@ def test_no_send_empty_tracestate(self):

RFC 3.3.1.1

Empty and whitespace-only list members are allowed. Vendors MUST accept empty
tracestate headers but SHOULD avoid sending them.
Empty and whitespace-only list members are allowed. Vendors MUST accept
empty tracestate headers but SHOULD avoid sending them.
"""
output = {} # type:typing.Dict[str, str]
FORMAT.inject(
trace.SpanContext(self.TRACE_ID, self.SPAN_ID),
dict.__setitem__,
output,
mock_span = Mock()
mock_span.configure_mock(
**{
"get_context.return_value": trace.SpanContext(
self.TRACE_ID, self.SPAN_ID
)
}
)
FORMAT.inject(mock_span, dict.__setitem__, output)
self.assertTrue("traceparent" in output)
self.assertFalse("tracestate" in output)

Expand All @@ -155,22 +169,23 @@ def test_format_not_supported(self):
get_as_list,
{
"traceparent": [
"00-12345678901234567890123456789012-1234567890123456-00-residue"
"00-12345678901234567890123456789012-"
"1234567890123456-00-residue"
],
"tracestate": ["foo=1,bar=2,foo=3"],
},
)
self.assertEqual(span_context, trace.INVALID_SPAN_CONTEXT)

def test_propagate_invalid_context(self):
"""Do not propagate invalid trace context.
"""
"""Do not propagate invalid trace context."""
output = {} # type:typing.Dict[str, str]
FORMAT.inject(trace.INVALID_SPAN_CONTEXT, dict.__setitem__, output)
FORMAT.inject(trace.Span(), dict.__setitem__, output)
self.assertFalse("traceparent" in output)

def test_tracestate_empty_header(self):
"""Test tracestate with an additional empty header (should be ignored)"""
"""Test tracestate with an additional empty header (should be ignored)
"""
span_context = FORMAT.extract(
get_as_list,
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class B3Format(HTTPTextFormat):
SINGLE_HEADER_KEY = "b3"
TRACE_ID_KEY = "x-b3-traceid"
SPAN_ID_KEY = "x-b3-spanid"
PARENT_SPAN_ID_KEY = "x-b3-parentspanid"
SAMPLED_KEY = "x-b3-sampled"
FLAGS_KEY = "x-b3-flags"
_SAMPLE_PROPAGATE_VALUES = set(["1", "True", "true", "d"])
Expand Down Expand Up @@ -55,7 +56,7 @@ def extract(cls, get_from_carrier, carrier):
elif len(fields) == 3:
trace_id, span_id, sampled = fields
elif len(fields) == 4:
trace_id, span_id, sampled, _parent_span_id = fields
trace_id, span_id, sampled, _ = fields
else:
return trace.INVALID_SPAN_CONTEXT
else:
Expand Down Expand Up @@ -100,14 +101,22 @@ def extract(cls, get_from_carrier, carrier):
)

@classmethod
def inject(cls, context, set_in_carrier, carrier):
sampled = (trace.TraceOptions.SAMPLED & context.trace_options) != 0
def inject(cls, span, set_in_carrier, carrier):
sampled = (
trace.TraceOptions.SAMPLED & span.context.trace_options
) != 0
set_in_carrier(
carrier, cls.TRACE_ID_KEY, format_trace_id(context.trace_id)
carrier, cls.TRACE_ID_KEY, format_trace_id(span.context.trace_id)
)
set_in_carrier(
carrier, cls.SPAN_ID_KEY, format_span_id(context.span_id)
carrier, cls.SPAN_ID_KEY, format_span_id(span.context.span_id)
)
if span.parent is not None:
set_in_carrier(
carrier,
cls.PARENT_SPAN_ID_KEY,
format_span_id(span.parent.context.span_id),
)
set_in_carrier(carrier, cls.SAMPLED_KEY, "1" if sampled else "0")


Expand Down
Loading