Skip to content

Commit

Permalink
Added experimental HTTP backpropagators
Browse files Browse the repository at this point in the history
The experimental back propagators inject trace response headers into
HTTP responses. These are meant to be used by instrumentations and are
not considered stable.
  • Loading branch information
owais committed Apr 13, 2021
1 parent 6f8c077 commit f6b04c4
Show file tree
Hide file tree
Showing 3 changed files with 205 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added `py.typed` file to every package. This should resolve a bunch of mypy
errors for users.
([#1720](https://github.com/open-telemetry/opentelemetry-python/pull/1720))
- Added experimental HTTP back propagators.
([#1762](https://github.com/open-telemetry/opentelemetry-python/pull/1762))

### Changed
- Adjust `B3Format` propagator to be spec compliant by not modifying context
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import typing

import opentelemetry.trace as trace
from opentelemetry.context.context import Context
from opentelemetry.propagators import textmap
from opentelemetry.trace import format_span_id, format_trace_id

_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"
_BACK_PROPAGATOR = None


def get_global_back_propagator():
return _BACK_PROPAGATOR


def set_global_back_propagator(propagator):
global _BACK_PROPAGATOR # pylint:disable=global-statement
_BACK_PROPAGATOR = propagator


class DictHeaderSetter:
def set(self, carrier, key, value): # pylint: disable=no-self-use
old_value = carrier.get(key, "")
if old_value:
value = "{0}, {1}".format(old_value, value)
carrier[key] = value


default_setter = DictHeaderSetter()


class FuncSetter:
def __init__(self, func):
self._func = func

def set(self, carrier, key, value):
self._func(carrier, key, value)


class TraceResponsePropagator:
"""Experimental propagator that injects tracecontext into HTTP responses."""

_HEADER_NAME = "traceresponse"

def _format_header(self, span_context): # pylint: disable=no-self-use
return "00-{trace_id}-{span_id}-{:02x}".format(
span_context.trace_flags,
trace_id=format_trace_id(span_context.trace_id),
span_id=format_span_id(span_context.span_id),
)

def inject(
self,
carrier: textmap.CarrierT,
context: typing.Optional[Context] = None,
setter: textmap.Setter = default_setter,
) -> None:
"""Injects SpanContext into the HTTP response carrier."""
span = trace.get_current_span(context)
span_context = span.get_span_context()
if span_context == trace.INVALID_SPAN_CONTEXT:
return

setter.set(
carrier, self._HEADER_NAME, self._format_header(span_context)
)
setter.set(
carrier,
_HTTP_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS,
self._HEADER_NAME,
)


class ServerTimingPropagator(TraceResponsePropagator):

_HEADER_NAME = "Server-Timing"

def _format_header(self, span_context):
return 'traceparent;desc="00-{trace_id}-{span_id}-{:02x}"'.format(
span_context.trace_flags,
trace_id=format_trace_id(span_context.trace_id),
span_id=format_span_id(span_context.span_id),
)
106 changes: 106 additions & 0 deletions opentelemetry-instrumentation/tests/test_propagators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# pylint: disable=protected-access

from opentelemetry import trace
from opentelemetry.instrumentation import propagators
from opentelemetry.instrumentation.propagators import (
DictHeaderSetter,
ServerTimingPropagator,
TraceResponsePropagator,
get_global_back_propagator,
set_global_back_propagator,
)
from opentelemetry.test.test_base import TestBase


class TestGlobals(TestBase):
def test_get_set(self):
original = propagators._BACK_PROPAGATOR

propagators._BACK_PROPAGATOR = None
self.assertIsNone(get_global_back_propagator())

prop = TraceResponsePropagator()
set_global_back_propagator(prop)
self.assertIs(prop, get_global_back_propagator())

propagators._BACK_PROPAGATOR = original


class TestDictHeaderSetter(TestBase):
def test_simple(self):
setter = DictHeaderSetter()
carrier = {}
setter.set(carrier, "kk", "vv")
self.assertIn("kk", carrier)
self.assertEqual(carrier["kk"], "vv")

def test_append(self):
setter = DictHeaderSetter()
carrier = {"kk": "old"}
setter.set(carrier, "kk", "vv")
self.assertIn("kk", carrier)
self.assertEqual(carrier["kk"], "old, vv")


class TestTraceResponsePropagator(TestBase):
def test_inject(self):
span = trace.NonRecordingSpan(
trace.SpanContext(
trace_id=1,
span_id=2,
is_remote=False,
trace_flags=trace.DEFAULT_TRACE_OPTIONS,
trace_state=trace.DEFAULT_TRACE_STATE,
),
)

ctx = trace.set_span_in_context(span)
prop = TraceResponsePropagator()
carrier = {}
prop.inject(carrier, ctx)
self.assertEqual(
carrier["Access-Control-Expose-Headers"], "traceresponse"
)
self.assertEqual(
carrier["traceresponse"],
"00-00000000000000000000000000000001-0000000000000002-00",
)


class TestServerTimingPropagator(TestBase):
def test_inject(self):
span = trace.NonRecordingSpan(
trace.SpanContext(
trace_id=1,
span_id=2,
is_remote=False,
trace_flags=trace.DEFAULT_TRACE_OPTIONS,
trace_state=trace.DEFAULT_TRACE_STATE,
),
)

ctx = trace.set_span_in_context(span)
prop = ServerTimingPropagator()
carrier = {}
prop.inject(carrier, ctx)
self.assertEqual(
carrier["Access-Control-Expose-Headers"], "Server-Timing"
)
self.assertEqual(
carrier["Server-Timing"],
'traceparent;desc="00-00000000000000000000000000000001-0000000000000002-00"',
)

0 comments on commit f6b04c4

Please sign in to comment.