trace_context.go

  1// Copyright The OpenTelemetry Authors
  2// SPDX-License-Identifier: Apache-2.0
  3
  4package propagation // import "go.opentelemetry.io/otel/propagation"
  5
  6import (
  7	"context"
  8	"encoding/hex"
  9	"fmt"
 10	"strings"
 11
 12	"go.opentelemetry.io/otel/trace"
 13)
 14
 15const (
 16	supportedVersion  = 0
 17	maxVersion        = 254
 18	traceparentHeader = "traceparent"
 19	tracestateHeader  = "tracestate"
 20	delimiter         = "-"
 21)
 22
 23// TraceContext is a propagator that supports the W3C Trace Context format
 24// (https://www.w3.org/TR/trace-context/)
 25//
 26// This propagator will propagate the traceparent and tracestate headers to
 27// guarantee traces are not broken. It is up to the users of this propagator
 28// to choose if they want to participate in a trace by modifying the
 29// traceparent header and relevant parts of the tracestate header containing
 30// their proprietary information.
 31type TraceContext struct{}
 32
 33var (
 34	_           TextMapPropagator = TraceContext{}
 35	versionPart                   = fmt.Sprintf("%.2X", supportedVersion)
 36)
 37
 38// Inject injects the trace context from ctx into carrier.
 39func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
 40	sc := trace.SpanContextFromContext(ctx)
 41	if !sc.IsValid() {
 42		return
 43	}
 44
 45	if ts := sc.TraceState().String(); ts != "" {
 46		carrier.Set(tracestateHeader, ts)
 47	}
 48
 49	// Clear all flags other than the trace-context supported sampling bit.
 50	flags := sc.TraceFlags() & trace.FlagsSampled
 51
 52	var sb strings.Builder
 53	sb.Grow(2 + 32 + 16 + 2 + 3)
 54	_, _ = sb.WriteString(versionPart)
 55	traceID := sc.TraceID()
 56	spanID := sc.SpanID()
 57	flagByte := [1]byte{byte(flags)}
 58	var buf [32]byte
 59	for _, src := range [][]byte{traceID[:], spanID[:], flagByte[:]} {
 60		_ = sb.WriteByte(delimiter[0])
 61		n := hex.Encode(buf[:], src)
 62		_, _ = sb.Write(buf[:n])
 63	}
 64	carrier.Set(traceparentHeader, sb.String())
 65}
 66
 67// Extract reads tracecontext from the carrier into a returned Context.
 68//
 69// The returned Context will be a copy of ctx and contain the extracted
 70// tracecontext as the remote SpanContext. If the extracted tracecontext is
 71// invalid, the passed ctx will be returned directly instead.
 72func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context {
 73	sc := tc.extract(carrier)
 74	if !sc.IsValid() {
 75		return ctx
 76	}
 77	return trace.ContextWithRemoteSpanContext(ctx, sc)
 78}
 79
 80func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
 81	h := carrier.Get(traceparentHeader)
 82	if h == "" {
 83		return trace.SpanContext{}
 84	}
 85
 86	var ver [1]byte
 87	if !extractPart(ver[:], &h, 2) {
 88		return trace.SpanContext{}
 89	}
 90	version := int(ver[0])
 91	if version > maxVersion {
 92		return trace.SpanContext{}
 93	}
 94
 95	var scc trace.SpanContextConfig
 96	if !extractPart(scc.TraceID[:], &h, 32) {
 97		return trace.SpanContext{}
 98	}
 99	if !extractPart(scc.SpanID[:], &h, 16) {
100		return trace.SpanContext{}
101	}
102
103	var opts [1]byte
104	if !extractPart(opts[:], &h, 2) {
105		return trace.SpanContext{}
106	}
107	if version == 0 && (h != "" || opts[0] > 2) {
108		// version 0 not allow extra
109		// version 0 not allow other flag
110		return trace.SpanContext{}
111	}
112
113	// Clear all flags other than the trace-context supported sampling bit.
114	scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
115
116	// Ignore the error returned here. Failure to parse tracestate MUST NOT
117	// affect the parsing of traceparent according to the W3C tracecontext
118	// specification.
119	scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader))
120	scc.Remote = true
121
122	sc := trace.NewSpanContext(scc)
123	if !sc.IsValid() {
124		return trace.SpanContext{}
125	}
126
127	return sc
128}
129
130// upperHex detect hex is upper case Unicode characters.
131func upperHex(v string) bool {
132	for _, c := range v {
133		if c >= 'A' && c <= 'F' {
134			return true
135		}
136	}
137	return false
138}
139
140func extractPart(dst []byte, h *string, n int) bool {
141	part, left, _ := strings.Cut(*h, delimiter)
142	*h = left
143	// hex.Decode decodes unsupported upper-case characters, so exclude explicitly.
144	if len(part) != n || upperHex(part) {
145		return false
146	}
147	if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 {
148		return false
149	}
150	return true
151}
152
153// Fields returns the keys who's values are set with Inject.
154func (tc TraceContext) Fields() []string {
155	return []string{traceparentHeader, tracestateHeader}
156}