diff --git a/CHANGELOG.md b/CHANGELOG.md index 4102c1f8c3..5d5c5ceaa8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased](https://github.com/open-telemetry/opentelemetry-python-contrib/compare/v0.18b0...HEAD) - Updated instrumentations to use `opentelemetry.trace.use_span` instead of `Tracer.use_span()` ([#364](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/364)) +- `opentelemetry-propagator-ot-trace` Do not throw an exception when headers are not present + ([#378](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/378)) ### Changed - Rename `IdsGenerator` to `IdGenerator` diff --git a/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py b/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py index 3aef2cfcb0..603096cb6e 100644 --- a/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py +++ b/propagator/opentelemetry-propagator-ot-trace/src/opentelemetry/propagators/ot_trace/__init__.py @@ -13,7 +13,7 @@ # limitations under the License. from re import compile as re_compile -from typing import Iterable, Optional +from typing import Any, Iterable, Optional from opentelemetry.baggage import get_all, set_baggage from opentelemetry.context import Context @@ -55,10 +55,12 @@ def extract( ) -> Context: traceid = _extract_first_element( - getter.get(carrier, OT_TRACE_ID_HEADER) + getter.get(carrier, OT_TRACE_ID_HEADER), INVALID_TRACE_ID ) - spanid = _extract_first_element(getter.get(carrier, OT_SPAN_ID_HEADER)) + spanid = _extract_first_element( + getter.get(carrier, OT_SPAN_ID_HEADER), INVALID_SPAN_ID + ) sampled = _extract_first_element( getter.get(carrier, OT_SAMPLED_HEADER) @@ -163,8 +165,8 @@ def fields(self): def _extract_first_element( - items: Iterable[TextMapPropagatorT], + items: Iterable[TextMapPropagatorT], default: Any = None, ) -> Optional[TextMapPropagatorT]: if items is None: - return None + return default return next(iter(items), None) diff --git a/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py b/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py index 5af8129d7a..e8b19e44a0 100644 --- a/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py +++ b/propagator/opentelemetry-propagator-ot-trace/tests/test_ot_trace_propagator.py @@ -366,3 +366,12 @@ def test_extract_baggage(self): self.assertEqual(baggage["abc"], "abc") self.assertEqual(baggage["def"], "def") + + def test_extract_empty(self): + "Test extraction when no headers are present" + + span_context = get_current_span( + self.ot_trace_propagator.extract(carrier_getter, {}) + ).get_span_context() + + self.assertEqual(span_context, INVALID_SPAN_CONTEXT)