1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
|
# 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.
# type: ignore
import typing
import unittest
from unittest.mock import Mock, patch
from opentelemetry import trace
from opentelemetry.context import Context
from opentelemetry.trace.propagation import tracecontext
from opentelemetry.trace.span import TraceState
FORMAT = tracecontext.TraceContextTextMapPropagator()
class TestTraceContextFormat(unittest.TestCase):
TRACE_ID = int("12345678901234567890123456789012", 16) # type:int
SPAN_ID = int("1234567890123456", 16) # type:int
def test_no_traceparent_header(self):
"""When tracecontext headers are not present, a new SpanContext
should be created.
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.
"""
output: typing.Dict[str, typing.List[str]] = {}
span = trace.get_current_span(FORMAT.extract(output))
self.assertIsInstance(span.get_span_context(), trace.SpanContext)
def test_headers_with_tracestate(self):
"""When there is a traceparent and tracestate header, data from
both should be added to the SpanContext.
"""
traceparent_value = (
f"00-{format(self.TRACE_ID, '032x')}-"
f"{format(self.SPAN_ID, '016x')}-00"
)
tracestate_value = "foo=1,bar=2,baz=3"
span_context = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [traceparent_value],
"tracestate": [tracestate_value],
},
)
).get_span_context()
self.assertEqual(span_context.trace_id, self.TRACE_ID)
self.assertEqual(span_context.span_id, self.SPAN_ID)
self.assertEqual(
span_context.trace_state, {"foo": "1", "bar": "2", "baz": "3"}
)
self.assertTrue(span_context.is_remote)
output: typing.Dict[str, str] = {}
span = trace.NonRecordingSpan(span_context)
ctx = trace.set_span_in_context(span)
FORMAT.inject(output, context=ctx)
self.assertEqual(output["traceparent"], traceparent_value)
for pair in ["foo=1", "bar=2", "baz=3"]:
self.assertIn(pair, output["tracestate"])
self.assertEqual(output["tracestate"].count(","), 2)
def test_invalid_trace_id(self):
"""If the trace id is invalid, we must ignore the full traceparent header,
and return a random, valid trace.
Also ignore any tracestate.
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.
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.
"""
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-00000000000000000000000000000000-1234567890123456-00"
],
"tracestate": ["foo=1,bar=2,foo=3"],
},
)
)
self.assertEqual(span.get_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.
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).
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.
"""
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-00000000000000000000000000000000-0000000000000000-00"
],
"tracestate": ["foo=1,bar=2,foo=3"],
},
)
)
self.assertEqual(span.get_span_context(), trace.INVALID_SPAN_CONTEXT)
def test_no_send_empty_tracestate(self):
"""If the tracestate is empty, do not set the header.
RFC 3.3.1.1
Empty and whitespace-only list members are allowed. Vendors MUST accept
empty tracestate headers but SHOULD avoid sending them.
"""
output: typing.Dict[str, str] = {}
span = trace.NonRecordingSpan(
trace.SpanContext(self.TRACE_ID, self.SPAN_ID, is_remote=False)
)
ctx = trace.set_span_in_context(span)
FORMAT.inject(output, context=ctx)
self.assertTrue("traceparent" in output)
self.assertFalse("tracestate" in output)
def test_format_not_supported(self):
"""If the traceparent does not adhere to the supported format, discard it and
create a new tracecontext.
RFC 4.3
If the version cannot be parsed, return an invalid trace header.
"""
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-12345678901234567890123456789012-"
"1234567890123456-00-residue"
],
"tracestate": ["foo=1,bar=2,foo=3"],
},
)
)
self.assertEqual(span.get_span_context(), trace.INVALID_SPAN_CONTEXT)
def test_propagate_invalid_context(self):
"""Do not propagate invalid trace context."""
output: typing.Dict[str, str] = {}
ctx = trace.set_span_in_context(trace.INVALID_SPAN)
FORMAT.inject(output, context=ctx)
self.assertFalse("traceparent" in output)
def test_tracestate_empty_header(self):
"""Test tracestate with an additional empty header (should be ignored)"""
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-12345678901234567890123456789012-1234567890123456-00"
],
"tracestate": ["foo=1", ""],
},
)
)
self.assertEqual(span.get_span_context().trace_state["foo"], "1")
def test_tracestate_header_with_trailing_comma(self):
"""Do not propagate invalid trace context."""
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-12345678901234567890123456789012-1234567890123456-00"
],
"tracestate": ["foo=1,"],
},
)
)
self.assertEqual(span.get_span_context().trace_state["foo"], "1")
def test_tracestate_keys(self):
"""Test for valid key patterns in the tracestate"""
tracestate_value = ",".join(
[
"1a-2f@foo=bar1",
"1a-_*/2b@foo=bar2",
"foo=bar3",
"foo-_*/bar=bar4",
]
)
span = trace.get_current_span(
FORMAT.extract(
{
"traceparent": [
"00-12345678901234567890123456789012-"
"1234567890123456-00"
],
"tracestate": [tracestate_value],
},
)
)
self.assertEqual(
span.get_span_context().trace_state["1a-2f@foo"], "bar1"
)
self.assertEqual(
span.get_span_context().trace_state["1a-_*/2b@foo"], "bar2"
)
self.assertEqual(span.get_span_context().trace_state["foo"], "bar3")
self.assertEqual(
span.get_span_context().trace_state["foo-_*/bar"], "bar4"
)
@patch("opentelemetry.trace.INVALID_SPAN_CONTEXT")
@patch("opentelemetry.trace.get_current_span")
def test_fields(self, mock_get_current_span, mock_invalid_span_context):
mock_get_current_span.configure_mock(
return_value=Mock(
**{
"get_span_context.return_value": Mock(
**{
"trace_id": 1,
"span_id": 2,
"trace_flags": 3,
"trace_state": TraceState([("a", "b")]),
}
)
}
)
)
mock_setter = Mock()
FORMAT.inject({}, setter=mock_setter)
inject_fields = set()
for mock_call in mock_setter.mock_calls:
inject_fields.add(mock_call[1][1])
self.assertEqual(inject_fields, FORMAT.fields)
def test_extract_no_trace_parent_to_explicit_ctx(self):
carrier = {"tracestate": ["foo=1"]}
orig_ctx = Context({"k1": "v1"})
ctx = FORMAT.extract(carrier, orig_ctx)
self.assertDictEqual(orig_ctx, ctx)
def test_extract_no_trace_parent_to_implicit_ctx(self):
carrier = {"tracestate": ["foo=1"]}
ctx = FORMAT.extract(carrier)
self.assertDictEqual(Context(), ctx)
def test_extract_invalid_trace_parent_to_explicit_ctx(self):
trace_parent_headers = [
"invalid",
"00-00000000000000000000000000000000-1234567890123456-00",
"00-12345678901234567890123456789012-0000000000000000-00",
"00-12345678901234567890123456789012-1234567890123456-00-residue",
]
for trace_parent in trace_parent_headers:
with self.subTest(trace_parent=trace_parent):
carrier = {
"traceparent": [trace_parent],
"tracestate": ["foo=1"],
}
orig_ctx = Context({"k1": "v1"})
ctx = FORMAT.extract(carrier, orig_ctx)
self.assertDictEqual(orig_ctx, ctx)
def test_extract_invalid_trace_parent_to_implicit_ctx(self):
trace_parent_headers = [
"invalid",
"00-00000000000000000000000000000000-1234567890123456-00",
"00-12345678901234567890123456789012-0000000000000000-00",
"00-12345678901234567890123456789012-1234567890123456-00-residue",
]
for trace_parent in trace_parent_headers:
with self.subTest(trace_parent=trace_parent):
carrier = {
"traceparent": [trace_parent],
"tracestate": ["foo=1"],
}
ctx = FORMAT.extract(carrier)
self.assertDictEqual(Context(), ctx)
|