...

Source file src/go.opentelemetry.io/otel/propagation/trace_context.go

Documentation: go.opentelemetry.io/otel/propagation

     1  // Copyright The OpenTelemetry Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package propagation // import "go.opentelemetry.io/otel/propagation"
    16  
    17  import (
    18  	"context"
    19  	"encoding/hex"
    20  	"fmt"
    21  	"regexp"
    22  
    23  	"go.opentelemetry.io/otel/trace"
    24  )
    25  
    26  const (
    27  	supportedVersion  = 0
    28  	maxVersion        = 254
    29  	traceparentHeader = "traceparent"
    30  	tracestateHeader  = "tracestate"
    31  )
    32  
    33  // TraceContext is a propagator that supports the W3C Trace Context format
    34  // (https://www.w3.org/TR/trace-context/)
    35  //
    36  // This propagator will propagate the traceparent and tracestate headers to
    37  // guarantee traces are not broken. It is up to the users of this propagator
    38  // to choose if they want to participate in a trace by modifying the
    39  // traceparent header and relevant parts of the tracestate header containing
    40  // their proprietary information.
    41  type TraceContext struct{}
    42  
    43  var (
    44  	_              TextMapPropagator = TraceContext{}
    45  	traceCtxRegExp                   = regexp.MustCompile("^(?P<version>[0-9a-f]{2})-(?P<traceID>[a-f0-9]{32})-(?P<spanID>[a-f0-9]{16})-(?P<traceFlags>[a-f0-9]{2})(?:-.*)?$")
    46  )
    47  
    48  // Inject set tracecontext from the Context into the carrier.
    49  func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
    50  	sc := trace.SpanContextFromContext(ctx)
    51  	if !sc.IsValid() {
    52  		return
    53  	}
    54  
    55  	if ts := sc.TraceState().String(); ts != "" {
    56  		carrier.Set(tracestateHeader, ts)
    57  	}
    58  
    59  	// Clear all flags other than the trace-context supported sampling bit.
    60  	flags := sc.TraceFlags() & trace.FlagsSampled
    61  
    62  	h := fmt.Sprintf("%.2x-%s-%s-%s",
    63  		supportedVersion,
    64  		sc.TraceID(),
    65  		sc.SpanID(),
    66  		flags)
    67  	carrier.Set(traceparentHeader, h)
    68  }
    69  
    70  // Extract reads tracecontext from the carrier into a returned Context.
    71  //
    72  // The returned Context will be a copy of ctx and contain the extracted
    73  // tracecontext as the remote SpanContext. If the extracted tracecontext is
    74  // invalid, the passed ctx will be returned directly instead.
    75  func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context {
    76  	sc := tc.extract(carrier)
    77  	if !sc.IsValid() {
    78  		return ctx
    79  	}
    80  	return trace.ContextWithRemoteSpanContext(ctx, sc)
    81  }
    82  
    83  func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
    84  	h := carrier.Get(traceparentHeader)
    85  	if h == "" {
    86  		return trace.SpanContext{}
    87  	}
    88  
    89  	matches := traceCtxRegExp.FindStringSubmatch(h)
    90  
    91  	if len(matches) == 0 {
    92  		return trace.SpanContext{}
    93  	}
    94  
    95  	if len(matches) < 5 { // four subgroups plus the overall match
    96  		return trace.SpanContext{}
    97  	}
    98  
    99  	if len(matches[1]) != 2 {
   100  		return trace.SpanContext{}
   101  	}
   102  	ver, err := hex.DecodeString(matches[1])
   103  	if err != nil {
   104  		return trace.SpanContext{}
   105  	}
   106  	version := int(ver[0])
   107  	if version > maxVersion {
   108  		return trace.SpanContext{}
   109  	}
   110  
   111  	if version == 0 && len(matches) != 5 { // four subgroups plus the overall match
   112  		return trace.SpanContext{}
   113  	}
   114  
   115  	if len(matches[2]) != 32 {
   116  		return trace.SpanContext{}
   117  	}
   118  
   119  	var scc trace.SpanContextConfig
   120  
   121  	scc.TraceID, err = trace.TraceIDFromHex(matches[2][:32])
   122  	if err != nil {
   123  		return trace.SpanContext{}
   124  	}
   125  
   126  	if len(matches[3]) != 16 {
   127  		return trace.SpanContext{}
   128  	}
   129  	scc.SpanID, err = trace.SpanIDFromHex(matches[3])
   130  	if err != nil {
   131  		return trace.SpanContext{}
   132  	}
   133  
   134  	if len(matches[4]) != 2 {
   135  		return trace.SpanContext{}
   136  	}
   137  	opts, err := hex.DecodeString(matches[4])
   138  	if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) {
   139  		return trace.SpanContext{}
   140  	}
   141  	// Clear all flags other than the trace-context supported sampling bit.
   142  	scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
   143  
   144  	// Ignore the error returned here. Failure to parse tracestate MUST NOT
   145  	// affect the parsing of traceparent according to the W3C tracecontext
   146  	// specification.
   147  	scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader))
   148  	scc.Remote = true
   149  
   150  	sc := trace.NewSpanContext(scc)
   151  	if !sc.IsValid() {
   152  		return trace.SpanContext{}
   153  	}
   154  
   155  	return sc
   156  }
   157  
   158  // Fields returns the keys who's values are set with Inject.
   159  func (tc TraceContext) Fields() []string {
   160  	return []string{traceparentHeader, tracestateHeader}
   161  }
   162  

View as plain text