1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2024-12-26 21:05:00 +02:00
opentelemetry-go/propagation/trace_context.go

157 lines
4.1 KiB
Go
Raw Normal View History

// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package propagation // import "go.opentelemetry.io/otel/propagation"
import (
"context"
"encoding/hex"
"fmt"
"strings"
"go.opentelemetry.io/otel/trace"
)
const (
supportedVersion = 0
maxVersion = 254
traceparentHeader = "traceparent"
tracestateHeader = "tracestate"
delimiter = "-"
)
// TraceContext is a propagator that supports the W3C Trace Context format
// (https://www.w3.org/TR/trace-context/)
//
// This propagator will propagate the traceparent and tracestate headers to
// guarantee traces are not broken. It is up to the users of this propagator
// to choose if they want to participate in a trace by modifying the
// traceparent header and relevant parts of the tracestate header containing
// their proprietary information.
type TraceContext struct{}
var (
_ TextMapPropagator = TraceContext{}
versionPart = fmt.Sprintf("%.2X", supportedVersion)
)
// Inject injects the trace context from ctx into carrier.
func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
sc := trace.SpanContextFromContext(ctx)
if !sc.IsValid() {
return
}
if ts := sc.TraceState().String(); ts != "" {
carrier.Set(tracestateHeader, ts)
}
// Clear all flags other than the trace-context supported sampling bit.
flags := sc.TraceFlags() & trace.FlagsSampled
var sb strings.Builder
sb.Grow(2 + 32 + 16 + 2 + 3)
_, _ = sb.WriteString(versionPart)
traceID := sc.TraceID()
spanID := sc.SpanID()
flagByte := [1]byte{byte(flags)}
var buf [32]byte
for _, src := range [][]byte{traceID[:], spanID[:], flagByte[:]} {
_ = sb.WriteByte(delimiter[0])
n := hex.Encode(buf[:], src)
_, _ = sb.Write(buf[:n])
}
carrier.Set(traceparentHeader, sb.String())
}
// Extract reads tracecontext from the carrier into a returned Context.
//
// The returned Context will be a copy of ctx and contain the extracted
// tracecontext as the remote SpanContext. If the extracted tracecontext is
// invalid, the passed ctx will be returned directly instead.
func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context {
sc := tc.extract(carrier)
if !sc.IsValid() {
return ctx
}
return trace.ContextWithRemoteSpanContext(ctx, sc)
}
func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
h := carrier.Get(traceparentHeader)
if h == "" {
return trace.SpanContext{}
}
var ver [1]byte
if !extractPart(ver[:], &h, 2) {
return trace.SpanContext{}
}
version := int(ver[0])
if version > maxVersion {
return trace.SpanContext{}
}
var scc trace.SpanContextConfig
if !extractPart(scc.TraceID[:], &h, 32) {
return trace.SpanContext{}
}
if !extractPart(scc.SpanID[:], &h, 16) {
return trace.SpanContext{}
}
var opts [1]byte
if !extractPart(opts[:], &h, 2) {
return trace.SpanContext{}
}
if version == 0 && (h != "" || opts[0] > 2) {
// version 0 not allow extra
// version 0 not allow other flag
return trace.SpanContext{}
}
Fix B3 propagator and add tests (#882) * Correct B3 propagators and add tests * Break up external integration and internal unit tests * Add changes to Changelog. * Update Changelog with PR number * Fix lint issues * Update trace flags Add a new "not sampled" mask to complement the existing "sampled" one. Rename `FlagsUnused` to `FlagsUnset`. Add documentation for each of the flags to help understand their purpose. * Update extractSingle to support unset sampling * Update existing tests to appropriately use FlagsUnset * Remove bogus debug flag test The B3 specification states "Debug is encoded as `X-B3-Flags: 1`. Absent or any other values can be ignored", so testing of other values should not result in an error. * B3 Extract now supports parsing both headers Remove test cases that would fail if the fallback header format was expected to not be used. * Feedback * Switch to bitmask inject encoding field Add the B3Encoding and valid HTTP based values. Change the B3 propagator to use these bitmask fields to specify the inject encoding it will propagate. * Add comments * Migrate B3 integration tests to existing testtrace * Update comment * Benchmark invalid B3 injects as well * Update trace flags Add a FlagsDebug and FlagsDeferred to track the B3 trace state. Add helper methods to the SpanContext to check the debug and deferred bit of the trace flags. Update SpanContext.IsSampled to return if the sampling decision is to sample rather than if the sample bit is set. This means that if the debug bit is also set it will return true. * Revert SpanContext.IsSampled back * Add comment to b3 test data generation * Update Changelog * Fix trace flag name in Changelog * Fix Changelog formatting * Update Changelog * Remove valid check at start of B3 injectg This check makes sample only headers not propagate. * Update B3 inject integration tests Use the passed SpanContext and check directly the span ID. * Update B3 integration tests Run update checked SpanID to match sent. Add tests to validate sample only transmissions and debug flag support. * Rename injectTest parentSc to sc This is no longer the parent. * Update GetAllKeys for B3 * Un-Export the B3 headers The B3SingleHeader name will conflict with the upcoming change to prefix the SingleHeader encoding with "B3". There are a few options to address this conflict, but in the end we do not need to be exporting these values. They are duplicates of the OpenZipkin package and users should use those. * Rename B3 encodings and move support method to B3Encoding Include a `B3` prefix to scope the encoding names. Move the related support method to the B3Encoding itself, instead of the B3 propagator. Add tests to provide a sanity check for encoding bitmasks. * Update span_context_test tests Update test name to better describe how unused bits have no affect on the sampling decision. Include the inverse of this test as well: not sampled but has unused bits. * Use named const for Single Header decoding widths * Update api/trace/b3_propagator.go Co-authored-by: Anthony Mirabella <a9@aneurysm9.com> Co-authored-by: Anthony Mirabella <a9@aneurysm9.com>
2020-07-08 01:38:52 +02:00
// Clear all flags other than the trace-context supported sampling bit.
scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
// Ignore the error returned here. Failure to parse tracestate MUST NOT
// affect the parsing of traceparent according to the W3C tracecontext
// specification.
scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader))
scc.Remote = true
sc := trace.NewSpanContext(scc)
if !sc.IsValid() {
return trace.SpanContext{}
}
return sc
}
// upperHex detect hex is upper case Unicode characters.
func upperHex(v string) bool {
for _, c := range v {
if c >= 'A' && c <= 'F' {
return true
}
}
return false
}
func extractPart(dst []byte, h *string, n int) bool {
part, left, _ := strings.Cut(*h, delimiter)
*h = left
// hex.Decode decodes unsupported upper-case characters, so exclude explicitly.
if len(part) != n || upperHex(part) {
return false
}
if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 {
return false
}
return true
}
// Fields returns the keys who's values are set with Inject.
func (tc TraceContext) Fields() []string {
return []string{traceparentHeader, tracestateHeader}
}