1# Copyright (c) The OpenTracing Authors. 2# 3# Permission is hereby granted, free of charge, to any person obtaining a copy 4# of this software and associated documentation files (the "Software"), to deal 5# in the Software without restriction, including without limitation the rights 6# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7# copies of the Software, and to permit persons to whom the Software is 8# furnished to do so, subject to the following conditions: 9# 10# The above copyright notice and this permission notice shall be included in 11# all copies or substantial portions of the Software. 12# 13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19# THE SOFTWARE. 20 21from __future__ import absolute_import 22 23from opentracing import SpanContextCorruptedException 24 25from .context import SpanContext 26from .propagator import Propagator 27 28prefix_tracer_state = 'ot-tracer-' 29prefix_baggage = 'ot-baggage-' 30field_name_trace_id = prefix_tracer_state + 'traceid' 31field_name_span_id = prefix_tracer_state + 'spanid' 32field_count = 2 33 34 35class TextPropagator(Propagator): 36 """A MockTracer Propagator for Format.TEXT_MAP.""" 37 38 def inject(self, span_context, carrier): 39 carrier[field_name_trace_id] = '{0:x}'.format(span_context.trace_id) 40 carrier[field_name_span_id] = '{0:x}'.format(span_context.span_id) 41 if span_context.baggage is not None: 42 for k in span_context.baggage: 43 carrier[prefix_baggage+k] = span_context.baggage[k] 44 45 def extract(self, carrier): # noqa 46 count = 0 47 span_id, trace_id = (0, 0) 48 baggage = {} 49 for k in carrier: 50 v = carrier[k] 51 k = k.lower() 52 if k == field_name_span_id: 53 span_id = int(v, 16) 54 count += 1 55 elif k == field_name_trace_id: 56 trace_id = int(v, 16) 57 count += 1 58 elif k.startswith(prefix_baggage): 59 baggage[k[len(prefix_baggage):]] = v 60 61 if count != field_count: 62 raise SpanContextCorruptedException() 63 64 return SpanContext( 65 span_id=span_id, 66 trace_id=trace_id, 67 baggage=baggage) 68