From c506e99b0121f6a740d48ed73203660ebecc6443 Mon Sep 17 00:00:00 2001 From: Tyler Yahn Date: Tue, 7 Jul 2020 16:38:52 -0700 Subject: [PATCH] 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 Co-authored-by: Anthony Mirabella --- CHANGELOG.md | 22 + api/trace/b3_propagator.go | 397 +++++--- api/trace/b3_propagator_test.go | 324 +++++++ api/trace/span_context.go | 30 +- api/trace/span_context_test.go | 11 +- .../testtrace/b3_propagator_benchmark_test.go | 61 +- .../testtrace/b3_propagator_data_test.go | 907 +++++++++++++----- api/trace/testtrace/b3_propagator_test.go | 138 +-- api/trace/testtrace/propagator_test.go | 5 +- .../trace_context_propagator_test.go | 21 +- api/trace/trace_context_propagator.go | 3 +- 11 files changed, 1431 insertions(+), 488 deletions(-) create mode 100644 api/trace/b3_propagator_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b5fd6aee1..9dcd8db84a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm ### Added +- The `B3Encoding` type to represent the B3 encoding(s) the B3 propagator can inject. + A value for HTTP supported encodings (Multiple Header: `MultipleHeader`, Single Header: `SingleHeader`) are included. (#882) +- The `FlagsDeferred` trace flag to indicate if the trace sampling decision has been deferred. (#882) +- The `FlagsDebug` trace flag to indicate if the trace is a debug trace. (#882) - Add `peer.service` semantic attribute. (#898) - Add database-specific semantic attributes. (#899) - Add semantic convention for `faas.coldstart` and `container.id`. (#909) @@ -18,10 +22,28 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Update `CONTRIBUTING.md` to ask for updates to `CHANGELOG.md` with each pull request. (#879) - Use lowercase header names for B3 Multiple Headers. (#881) +- The B3 propagator `SingleHeader` field has been replaced with `InjectEncoding`. + This new field can be set to combinations of the `B3Encoding` bitmasks and will inject trace information in these encodings. + If no encoding is set, the propagator will default to `MultipleHeader` encoding. (#882) +- The B3 propagator now extracts from either HTTP encoding of B3 (Single Header or Multiple Header) based on what is contained in the header. + Preference is given to Single Header encoding with Multiple Header being the fallback if Single Header is not found or is invalid. + This behavior change is made to dynamically support all correctly encoded traces received instead of having to guess the expected encoding prior to receiving. (#882) + +### Removed + +- The `FlagsUnused` trace flag is removed. + The purpose of this flag was to act as the inverse of `FlagsSampled`, the inverse of `FlagsSampled` is used instead. (#882) +- The B3 header constants (`B3SingleHeader`, `B3DebugFlagHeader`, `B3TraceIDHeader`, `B3SpanIDHeader`, `B3SampledHeader`, `B3ParentSpanIDHeader`) are removed. + If B3 header keys are needed [the authoritative OpenZipkin package constants](https://pkg.go.dev/github.com/openzipkin/zipkin-go@v0.2.2/propagation/b3?tab=doc#pkg-constants) should be used instead. (#882) ### Fixed - The B3 Single Header name is now correctly `b3` instead of the previous `X-B3`. (#881) +- The B3 propagator now correctly supports sampling only values (`b3: 0`, `b3: 1`, or `b3: d`) for a Single B3 Header. (#882) +- The B3 propagator now propagates the debug flag. + This removes the behavior of changing the debug flag into a set sampling bit. + Instead, this now follow the B3 specification and omits the `X-B3-Sampling` header. (#882) +- The B3 propagator now tracks "unset" sampling state (meaning "defer the decision") and does not set the `X-B3-Sampling` header when injecting. (#882) - Ensure span status is not set to `Unknown` when no HTTP status code is provided as it is assumed to be `200 OK`. (#908) - Ensure `httptrace.clientTracer` closes `http.headers` span. (#912) - Prometheus exporter will not apply stale updates or forget inactive metrics. (#903) diff --git a/api/trace/b3_propagator.go b/api/trace/b3_propagator.go index e0c96e9b97c..4627618f70b 100644 --- a/api/trace/b3_propagator.go +++ b/api/trace/b3_propagator.go @@ -16,7 +16,7 @@ package trace import ( "context" - "fmt" + "errors" "strings" "go.opentelemetry.io/otel/api/propagation" @@ -24,195 +24,320 @@ import ( const ( // Default B3 Header names. - B3SingleHeader = "b3" - B3DebugFlagHeader = "x-b3-flags" - B3TraceIDHeader = "x-b3-traceid" - B3SpanIDHeader = "x-b3-spanid" - B3SampledHeader = "x-b3-sampled" - B3ParentSpanIDHeader = "x-b3-parentspanid" + b3ContextHeader = "b3" + b3DebugFlagHeader = "x-b3-flags" + b3TraceIDHeader = "x-b3-traceid" + b3SpanIDHeader = "x-b3-spanid" + b3SampledHeader = "x-b3-sampled" + b3ParentSpanIDHeader = "x-b3-parentspanid" b3TraceIDPadding = "0000000000000000" + + // B3 Single Header encoding widths. + separatorWidth = 1 // Single "-" character. + samplingWidth = 1 // Single hex character. + traceID64BitsWidth = 64 / 4 // 16 hex character Trace ID. + traceID128BitsWidth = 128 / 4 // 32 hex character Trace ID. + spanIDWidth = 16 // 16 hex character ID. + parentSpanIDWidth = 16 // 16 hex character ID. +) + +var ( + empty = EmptySpanContext() + + errInvalidSampledByte = errors.New("invalid B3 Sampled found") + errInvalidSampledHeader = errors.New("invalid B3 Sampled header found") + errInvalidTraceIDHeader = errors.New("invalid B3 TraceID header found") + errInvalidSpanIDHeader = errors.New("invalid B3 SpanID header found") + errInvalidParentSpanIDHeader = errors.New("invalid B3 ParentSpanID header found") + errInvalidScope = errors.New("require either both TraceID and SpanID or none") + errInvalidScopeParent = errors.New("ParentSpanID requires both TraceID and SpanID to be available") + errInvalidScopeParentSingle = errors.New("ParentSpanID requires TraceID, SpanID and Sampled to be available") + errEmptyContext = errors.New("empty request context") + errInvalidTraceIDValue = errors.New("invalid B3 TraceID value found") + errInvalidSpanIDValue = errors.New("invalid B3 SpanID value found") + errInvalidParentSpanIDValue = errors.New("invalid B3 ParentSpanID value found") +) + +// B3Encoding is a bitmask representation of the B3 encoding type. +type B3Encoding uint8 + +// supports returns if e has o bit(s) set. +func (e B3Encoding) supports(o B3Encoding) bool { + return e&o == o +} + +const ( + // B3MultipleHeader is a B3 encoding that uses multiple headers to + // transmit tracing information all prefixed with `x-b3-`. + B3MultipleHeader B3Encoding = 1 << iota + // B3SingleHeader is a B3 encoding that uses a single header named `b3` + // to transmit tracing information. + B3SingleHeader + // B3Unspecified is an unspecified B3 encoding. + B3Unspecified B3Encoding = 0 ) // B3 propagator serializes SpanContext to/from B3 Headers. -// This propagator supports both version of B3 headers, -// 1. Single Header : -// X-B3: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} +// This propagator supports both versions of B3 headers, +// 1. Single Header: +// b3: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} // 2. Multiple Headers: -// X-B3-TraceId: {TraceId} -// X-B3-ParentSpanId: {ParentSpanId} -// X-B3-SpanId: {SpanId} -// X-B3-Sampled: {SamplingState} -// X-B3-Flags: {DebugFlag} -// -// If SingleHeader is set to true then X-B3 header is used to inject and extract. Otherwise, -// separate headers are used to inject and extract. +// x-b3-traceid: {TraceId} +// x-b3-parentspanid: {ParentSpanId} +// x-b3-spanid: {SpanId} +// x-b3-sampled: {SamplingState} +// x-b3-flags: {DebugFlag} type B3 struct { - SingleHeader bool + // InjectEncoding are the B3 encodings used when injecting trace + // information. If no encoding is specified (i.e. `B3Unspecified`) + // `B3MultipleHeader` will be used as the default. + InjectEncoding B3Encoding } var _ propagation.HTTPPropagator = B3{} +// Inject injects a context into the supplier as B3 headers. +// The parent span ID is omitted because it is not tracked in the +// SpanContext. func (b3 B3) Inject(ctx context.Context, supplier propagation.HTTPSupplier) { sc := SpanFromContext(ctx).SpanContext() - if !sc.IsValid() { - return + + if b3.InjectEncoding.supports(B3SingleHeader) { + header := []string{} + if sc.TraceID.IsValid() && sc.SpanID.IsValid() { + header = append(header, sc.TraceID.String(), sc.SpanID.String()) + } + + if sc.isDebug() { + header = append(header, "d") + } else if !sc.isDeferred() { + if sc.IsSampled() { + header = append(header, "1") + } else { + header = append(header, "0") + } + } + + supplier.Set(b3ContextHeader, strings.Join(header, "-")) } - if b3.SingleHeader { - sampled := sc.TraceFlags & FlagsSampled - supplier.Set(B3SingleHeader, - fmt.Sprintf("%s-%s-%.1d", sc.TraceID, sc.SpanID, sampled)) - } else { - supplier.Set(B3TraceIDHeader, sc.TraceID.String()) - supplier.Set(B3SpanIDHeader, sc.SpanID.String()) - var sampled string - if sc.IsSampled() { - sampled = "1" - } else { - sampled = "0" + if b3.InjectEncoding.supports(B3MultipleHeader) || b3.InjectEncoding == B3Unspecified { + if sc.TraceID.IsValid() && sc.SpanID.IsValid() { + supplier.Set(b3TraceIDHeader, sc.TraceID.String()) + supplier.Set(b3SpanIDHeader, sc.SpanID.String()) + } + + if sc.isDebug() { + // Since Debug implies deferred, don't also send "X-B3-Sampled". + supplier.Set(b3DebugFlagHeader, "1") + } else if !sc.isDeferred() { + if sc.IsSampled() { + supplier.Set(b3SampledHeader, "1") + } else { + supplier.Set(b3SampledHeader, "0") + } } - supplier.Set(B3SampledHeader, sampled) } } -// Extract retrieves B3 Headers from the supplier +// Extract extracts a context from the supplier if it contains B3 headers. func (b3 B3) Extract(ctx context.Context, supplier propagation.HTTPSupplier) context.Context { - var sc SpanContext - if b3.SingleHeader { - sc = b3.extractSingleHeader(supplier) - } else { - sc = b3.extract(supplier) + var ( + sc SpanContext + err error + ) + + // Default to Single Header if a valid value exists. + if h := supplier.Get(b3ContextHeader); h != "" { + sc, err = extractSingle(h) + if err == nil && sc.IsValid() { + return ContextWithRemoteSpanContext(ctx, sc) + } + // The Single Header value was invalid, fallback to Multiple Header. } - if !sc.IsValid() { + + var ( + traceID = supplier.Get(b3TraceIDHeader) + spanID = supplier.Get(b3SpanIDHeader) + parentSpanID = supplier.Get(b3ParentSpanIDHeader) + sampled = supplier.Get(b3SampledHeader) + debugFlag = supplier.Get(b3DebugFlagHeader) + ) + sc, err = extractMultiple(traceID, spanID, parentSpanID, sampled, debugFlag) + if err != nil || !sc.IsValid() { return ctx } return ContextWithRemoteSpanContext(ctx, sc) } -func fixB3TID(in string) string { - if len(in) == 16 { - in = b3TraceIDPadding + in +func (b3 B3) GetAllKeys() []string { + header := []string{} + if b3.InjectEncoding.supports(B3SingleHeader) { + header = append(header, b3ContextHeader) + } + if b3.InjectEncoding.supports(B3MultipleHeader) || b3.InjectEncoding == B3Unspecified { + header = append(header, b3TraceIDHeader, b3SpanIDHeader, b3SampledHeader, b3DebugFlagHeader) } - return in + return header } -func (b3 B3) extract(supplier propagation.HTTPSupplier) SpanContext { - tid, err := IDFromHex(fixB3TID(supplier.Get(B3TraceIDHeader))) - if err != nil { - return EmptySpanContext() - } - sid, err := SpanIDFromHex(supplier.Get(B3SpanIDHeader)) - if err != nil { - return EmptySpanContext() +// extractMultiple reconstructs a SpanContext from header values based on B3 +// Multiple header. It is based on the implementation found here: +// https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go +// and adapted to support a SpanContext. +func extractMultiple(traceID, spanID, parentSpanID, sampled, flags string) (SpanContext, error) { + var ( + err error + requiredCount int + sc = SpanContext{} + ) + + // correct values for an existing sampled header are "0" and "1". + // For legacy support and being lenient to other tracing implementations we + // allow "true" and "false" as inputs for interop purposes. + switch strings.ToLower(sampled) { + case "0", "false": + // Zero value for TraceFlags sample bit is unset. + case "1", "true": + sc.TraceFlags = FlagsSampled + case "": + sc.TraceFlags = FlagsDeferred + default: + return empty, errInvalidSampledHeader } - sampled, ok := b3.extractSampledState(supplier.Get(B3SampledHeader)) - if !ok { - return EmptySpanContext() + + // The only accepted value for Flags is "1". This will set Debug to + // true. All other values and omission of header will be ignored. + if flags == "1" { + sc.TraceFlags |= FlagsDebug } - debug, ok := b3.extracDebugFlag(supplier.Get(B3DebugFlagHeader)) - if !ok { - return EmptySpanContext() + if traceID != "" { + requiredCount++ + id := traceID + if len(traceID) == 16 { + // Pad 64-bit trace IDs. + id = b3TraceIDPadding + traceID + } + if sc.TraceID, err = IDFromHex(id); err != nil { + return empty, errInvalidTraceIDHeader + } } - if debug == FlagsSampled { - sampled = FlagsSampled + + if spanID != "" { + requiredCount++ + if sc.SpanID, err = SpanIDFromHex(spanID); err != nil { + return empty, errInvalidSpanIDHeader + } } - sc := SpanContext{ - TraceID: tid, - SpanID: sid, - TraceFlags: sampled, + if requiredCount != 0 && requiredCount != 2 { + return empty, errInvalidScope } - if !sc.IsValid() { - return EmptySpanContext() + if parentSpanID != "" { + if requiredCount == 0 { + return empty, errInvalidScopeParent + } + // Validate parent span ID but we do not use it so do not save it. + if _, err = SpanIDFromHex(parentSpanID); err != nil { + return empty, errInvalidParentSpanIDHeader + } } - return sc + return sc, nil } -func (b3 B3) extractSingleHeader(supplier propagation.HTTPSupplier) SpanContext { - h := supplier.Get(B3SingleHeader) - if h == "" || h == "0" { - return EmptySpanContext() - } - sc := SpanContext{} - parts := strings.Split(h, "-") - l := len(parts) - if l > 4 { - return EmptySpanContext() +// extractSingle reconstructs a SpanContext from contextHeader based on a B3 +// Single header. It is based on the implementation found here: +// https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go +// and adapted to support a SpanContext. +func extractSingle(contextHeader string) (SpanContext, error) { + if contextHeader == "" { + return empty, errEmptyContext } - if l < 2 { - return EmptySpanContext() - } + var ( + sc = SpanContext{} + sampling string + ) - var err error - sc.TraceID, err = IDFromHex(fixB3TID(parts[0])) - if err != nil { - return EmptySpanContext() - } - - sc.SpanID, err = SpanIDFromHex(parts[1]) - if err != nil { - return EmptySpanContext() - } + headerLen := len(contextHeader) - if l > 2 { - var ok bool - sc.TraceFlags, ok = b3.extractSampledState(parts[2]) - if !ok { - return EmptySpanContext() + if headerLen == samplingWidth { + sampling = contextHeader + } else if headerLen == traceID64BitsWidth || headerLen == traceID128BitsWidth { + // Trace ID by itself is invalid. + return empty, errInvalidScope + } else if headerLen >= traceID64BitsWidth+spanIDWidth+separatorWidth { + pos := 0 + var traceID string + if string(contextHeader[traceID64BitsWidth]) == "-" { + // traceID must be 64 bits + pos += traceID64BitsWidth // {traceID} + traceID = b3TraceIDPadding + string(contextHeader[0:pos]) + } else if string(contextHeader[32]) == "-" { + // traceID must be 128 bits + pos += traceID128BitsWidth // {traceID} + traceID = string(contextHeader[0:pos]) + } else { + return empty, errInvalidTraceIDValue } - } - if l == 4 { - _, err = SpanIDFromHex(parts[3]) + var err error + sc.TraceID, err = IDFromHex(traceID) if err != nil { - return EmptySpanContext() + return empty, errInvalidTraceIDValue } - } + pos += separatorWidth // {traceID}- - if !sc.IsValid() { - return EmptySpanContext() - } + sc.SpanID, err = SpanIDFromHex(contextHeader[pos : pos+spanIDWidth]) + if err != nil { + return empty, errInvalidSpanIDValue + } + pos += spanIDWidth // {traceID}-{spanID} - return sc -} + if headerLen > pos { + if headerLen == pos+separatorWidth { + // {traceID}-{spanID}- is invalid. + return empty, errInvalidSampledByte + } + pos += separatorWidth // {traceID}-{spanID}- -// extractSampledState parses the value of the X-B3-Sampled b3Header. -func (b3 B3) extractSampledState(sampled string) (flag byte, ok bool) { - switch sampled { - case "", "0": - return 0, true - case "1": - return FlagsSampled, true - case "true": - if !b3.SingleHeader { - return FlagsSampled, true - } - case "d": - if b3.SingleHeader { - return FlagsSampled, true + if headerLen == pos+samplingWidth { + sampling = string(contextHeader[pos]) + } else if headerLen == pos+parentSpanIDWidth { + // {traceID}-{spanID}-{parentSpanID} is invalid. + return empty, errInvalidScopeParentSingle + } else if headerLen == pos+samplingWidth+separatorWidth+parentSpanIDWidth { + sampling = string(contextHeader[pos]) + pos += samplingWidth + separatorWidth // {traceID}-{spanID}-{sampling}- + + // Validate parent span ID but we do not use it so do not + // save it. + _, err = SpanIDFromHex(contextHeader[pos:]) + if err != nil { + return empty, errInvalidParentSpanIDValue + } + } else { + return empty, errInvalidParentSpanIDValue + } } + } else { + return empty, errInvalidTraceIDValue } - return 0, false -} - -// extracDebugFlag parses the value of the X-B3-Sampled b3Header. -func (b3 B3) extracDebugFlag(debug string) (flag byte, ok bool) { - switch debug { - case "", "0": - return 0, true + switch sampling { + case "": + sc.TraceFlags = FlagsDeferred + case "d": + sc.TraceFlags = FlagsDebug case "1": - return FlagsSampled, true + sc.TraceFlags = FlagsSampled + case "0": + // Zero value for TraceFlags sample bit is unset. + default: + return empty, errInvalidSampledByte } - return 0, false -} -func (b3 B3) GetAllKeys() []string { - if b3.SingleHeader { - return []string{B3SingleHeader} - } - return []string{B3TraceIDHeader, B3SpanIDHeader, B3SampledHeader} + return sc, nil } diff --git a/api/trace/b3_propagator_test.go b/api/trace/b3_propagator_test.go new file mode 100644 index 00000000000..b558a76b75e --- /dev/null +++ b/api/trace/b3_propagator_test.go @@ -0,0 +1,324 @@ +// 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. + +package trace + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +var ( + traceID = ID{0, 0, 0, 0, 0, 0, 0, 0x7b, 0, 0, 0, 0, 0, 0, 0x1, 0xc8} + traceIDStr = "000000000000007b00000000000001c8" + spanID = SpanID{0, 0, 0, 0, 0, 0, 0, 0x7b} + spanIDStr = "000000000000007b" +) + +func TestExtractMultiple(t *testing.T) { + tests := []struct { + traceID string + spanID string + parentSpanID string + sampled string + flags string + expected SpanContext + err error + }{ + { + "", "", "", "0", "", + SpanContext{}, + nil, + }, + { + "", "", "", "", "", + SpanContext{TraceFlags: FlagsDeferred}, + nil, + }, + { + "", "", "", "1", "", + SpanContext{TraceFlags: FlagsSampled}, + nil, + }, + { + "", "", "", "", "1", + SpanContext{TraceFlags: FlagsDeferred | FlagsDebug}, + nil, + }, + { + "", "", "", "0", "1", + SpanContext{TraceFlags: FlagsDebug}, + nil, + }, + { + "", "", "", "1", "1", + SpanContext{TraceFlags: FlagsSampled | FlagsDebug}, + nil, + }, + { + traceIDStr, spanIDStr, "", "", "", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsDeferred}, + nil, + }, + { + traceIDStr, spanIDStr, "", "0", "", + SpanContext{TraceID: traceID, SpanID: spanID}, + nil, + }, + // Ensure backwards compatibility. + { + traceIDStr, spanIDStr, "", "false", "", + SpanContext{TraceID: traceID, SpanID: spanID}, + nil, + }, + { + traceIDStr, spanIDStr, "", "1", "", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled}, + nil, + }, + // Ensure backwards compatibility. + { + traceIDStr, spanIDStr, "", "true", "", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled}, + nil, + }, + { + traceIDStr, spanIDStr, "", "a", "", + empty, + errInvalidSampledHeader, + }, + { + traceIDStr, spanIDStr, "", "1", "1", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled | FlagsDebug}, + nil, + }, + // Invalid flags are discarded. + { + traceIDStr, spanIDStr, "", "1", "invalid", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled}, + nil, + }, + // Support short trace IDs. + { + "00000000000001c8", spanIDStr, "", "0", "", + SpanContext{ + TraceID: ID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1, 0xc8}, + SpanID: spanID, + }, + nil, + }, + { + "00000000000001c", spanIDStr, "", "0", "", + empty, + errInvalidTraceIDHeader, + }, + { + "00000000000001c80", spanIDStr, "", "0", "", + empty, + errInvalidTraceIDHeader, + }, + { + traceIDStr[:len(traceIDStr)-2], spanIDStr, "", "0", "", + empty, + errInvalidTraceIDHeader, + }, + { + traceIDStr + "0", spanIDStr, "", "0", "", + empty, + errInvalidTraceIDHeader, + }, + { + traceIDStr, "00000000000001c", "", "0", "", + empty, + errInvalidSpanIDHeader, + }, + { + traceIDStr, "00000000000001c80", "", "0", "", + empty, + errInvalidSpanIDHeader, + }, + { + traceIDStr, "", "", "0", "", + empty, + errInvalidScope, + }, + { + "", spanIDStr, "", "0", "", + empty, + errInvalidScope, + }, + { + "", "", spanIDStr, "0", "", + empty, + errInvalidScopeParent, + }, + { + traceIDStr, spanIDStr, "00000000000001c8", "0", "", + SpanContext{TraceID: traceID, SpanID: spanID}, + nil, + }, + { + traceIDStr, spanIDStr, "00000000000001c", "0", "", + empty, + errInvalidParentSpanIDHeader, + }, + { + traceIDStr, spanIDStr, "00000000000001c80", "0", "", + empty, + errInvalidParentSpanIDHeader, + }, + } + + for _, test := range tests { + actual, err := extractMultiple( + test.traceID, + test.spanID, + test.parentSpanID, + test.sampled, + test.flags, + ) + info := []interface{}{ + "trace ID: %q, span ID: %q, parent span ID: %q, sampled: %q, flags: %q", + test.traceID, + test.spanID, + test.parentSpanID, + test.sampled, + test.flags, + } + if !assert.Equal(t, test.err, err, info...) { + continue + } + assert.Equal(t, test.expected, actual, info...) + } +} + +func TestExtractSingle(t *testing.T) { + tests := []struct { + header string + expected SpanContext + err error + }{ + {"0", SpanContext{}, nil}, + {"1", SpanContext{TraceFlags: FlagsSampled}, nil}, + {"d", SpanContext{TraceFlags: FlagsDebug}, nil}, + {"a", empty, errInvalidSampledByte}, + {"3", empty, errInvalidSampledByte}, + {"000000000000007b", empty, errInvalidScope}, + {"000000000000007b00000000000001c8", empty, errInvalidScope}, + // Support short trace IDs. + { + "00000000000001c8-000000000000007b", + SpanContext{ + TraceID: ID{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x1, 0xc8}, + SpanID: spanID, + TraceFlags: FlagsDeferred, + }, + nil, + }, + { + "000000000000007b00000000000001c8-000000000000007b", + SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: FlagsDeferred, + }, + nil, + }, + { + "000000000000007b00000000000001c8-000000000000007b-", + empty, + errInvalidSampledByte, + }, + { + "000000000000007b00000000000001c8-000000000000007b-3", + empty, + errInvalidSampledByte, + }, + { + "000000000000007b00000000000001c8-000000000000007b-00000000000001c8", + empty, + errInvalidScopeParentSingle, + }, + { + "000000000000007b00000000000001c8-000000000000007b-1", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled}, + nil, + }, + // ParentSpanID is discarded, but should still restult in a parsable + // header. + { + "000000000000007b00000000000001c8-000000000000007b-1-00000000000001c8", + SpanContext{TraceID: traceID, SpanID: spanID, TraceFlags: FlagsSampled}, + nil, + }, + { + "000000000000007b00000000000001c8-000000000000007b-1-00000000000001c", + empty, + errInvalidParentSpanIDValue, + }, + {"", empty, errEmptyContext}, + } + + for _, test := range tests { + actual, err := extractSingle(test.header) + if !assert.Equal(t, test.err, err, "header: %s", test.header) { + continue + } + assert.Equal(t, test.expected, actual, "header: %s", test.header) + } +} + +func TestB3EncodingOperations(t *testing.T) { + encodings := []B3Encoding{ + B3MultipleHeader, + B3SingleHeader, + B3Unspecified, + } + + // Test for overflow (or something really unexpected). + for i, e := range encodings { + for j := i + 1; j < i+len(encodings); j++ { + o := encodings[j%len(encodings)] + assert.False(t, e == o, "%v == %v", e, o) + } + } + + // B3Unspecified is a special case, it supports only itself, but is + // supported by everything. + assert.True(t, B3Unspecified.supports(B3Unspecified)) + for _, e := range encodings[:len(encodings)-1] { + assert.False(t, B3Unspecified.supports(e), e) + assert.True(t, e.supports(B3Unspecified), e) + } + + // Skip the special case for B3Unspecified. + for i, e := range encodings[:len(encodings)-1] { + // Everything should support itself. + assert.True(t, e.supports(e)) + for j := i + 1; j < i+len(encodings); j++ { + o := encodings[j%len(encodings)] + // Any "or" combination should be supportive of an operand. + assert.True(t, (e | o).supports(e), "(%[0]v|%[1]v).supports(%[0]v)", e, o) + // Bitmasks should be unique. + assert.False(t, o.supports(e), "%v.supports(%v)", o, e) + } + } + + // B3Encoding.supports should be more inclusive than equality. + all := ^B3Unspecified + for _, e := range encodings { + assert.True(t, all.supports(e)) + } +} diff --git a/api/trace/span_context.go b/api/trace/span_context.go index b15975568bb..abce3f76a65 100644 --- a/api/trace/span_context.go +++ b/api/trace/span_context.go @@ -21,13 +21,15 @@ import ( ) const ( - traceFlagsBitMaskSampled = byte(0x01) - traceFlagsBitMaskUnused = byte(0xFE) - - // FlagsSampled is a byte with sampled bit set. It is a convenient value initializer - // for SpanContext TraceFlags field when a trace is sampled. - FlagsSampled = traceFlagsBitMaskSampled - FlagsUnused = traceFlagsBitMaskUnused + // FlagsSampled is a bitmask with the sampled bit set. A SpanContext + // with the sampling bit set means the span is sampled. + FlagsSampled = byte(0x01) + // FlagsDeferred is a bitmask with the deferred bit set. A SpanContext + // with the deferred bit set means the sampling decision has been + // defered to the receiver. + FlagsDeferred = byte(0x02) + // FlagsDebug is a bitmask with the debug bit set. + FlagsDebug = byte(0x04) ErrInvalidHexID errorConst = "trace-id and span-id can only contain [0-9a-f] characters, all lowercase" @@ -179,7 +181,17 @@ func (sc SpanContext) HasSpanID() bool { return sc.SpanID.IsValid() } -// IsSampled check if the sampling bit in trace flags is set. +// isDeferred returns if the deferred bit is set in the trace flags. +func (sc SpanContext) isDeferred() bool { + return sc.TraceFlags&FlagsDeferred == FlagsDeferred +} + +// isDebug returns if the debug bit is set in the trace flags. +func (sc SpanContext) isDebug() bool { + return sc.TraceFlags&FlagsDebug == FlagsDebug +} + +// IsSampled returns if the sampling bit is set in the trace flags. func (sc SpanContext) IsSampled() bool { - return sc.TraceFlags&traceFlagsBitMaskSampled == traceFlagsBitMaskSampled + return sc.TraceFlags&FlagsSampled == FlagsSampled } diff --git a/api/trace/span_context_test.go b/api/trace/span_context_test.go index 74a314bd39a..39e85439b2a 100644 --- a/api/trace/span_context_test.go +++ b/api/trace/span_context_test.go @@ -173,10 +173,17 @@ func TestSpanContextIsSampled(t *testing.T) { }, want: true, }, { - name: "sampled plus unused", + name: "unused bits are ignored, still not sampled", sc: trace.SpanContext{ TraceID: trace.ID([16]byte{1}), - TraceFlags: trace.FlagsSampled | trace.FlagsUnused, + TraceFlags: ^trace.FlagsSampled, + }, + want: false, + }, { + name: "unused bits are ignored, still sampled", + sc: trace.SpanContext{ + TraceID: trace.ID([16]byte{1}), + TraceFlags: trace.FlagsSampled | ^trace.FlagsSampled, }, want: true, }, { diff --git a/api/trace/testtrace/b3_propagator_benchmark_test.go b/api/trace/testtrace/b3_propagator_benchmark_test.go index bbd3e67f05e..42870dc8d90 100644 --- a/api/trace/testtrace/b3_propagator_benchmark_test.go +++ b/api/trace/testtrace/b3_propagator_benchmark_test.go @@ -20,39 +20,25 @@ import ( "testing" "go.opentelemetry.io/otel/api/trace" - mocktrace "go.opentelemetry.io/otel/internal/trace" ) func BenchmarkExtractB3(b *testing.B) { testGroup := []struct { - singleHeader bool - name string - tests []extractTest + name string + tests []extractTest }{ { - singleHeader: false, - name: "multiple headers", - tests: extractMultipleHeaders, + name: "valid headers", + tests: extractHeaders, }, { - singleHeader: true, - name: "single headers", - tests: extractSingleHeader, - }, - { - singleHeader: false, - name: "invalid multiple headers", - tests: extractInvalidB3MultipleHeaders, - }, - { - singleHeader: true, - name: "invalid single headers", - tests: extractInvalidB3SingleHeader, + name: "invalid headers", + tests: extractInvalidHeaders, }, } for _, tg := range testGroup { - propagator := trace.B3{SingleHeader: tg.singleHeader} + propagator := trace.B3{} for _, tt := range tg.tests { traceBenchmark(tg.name+"/"+tt.name, b, func(b *testing.B) { ctx := context.Background() @@ -71,40 +57,29 @@ func BenchmarkExtractB3(b *testing.B) { } func BenchmarkInjectB3(b *testing.B) { - var id uint64 testGroup := []struct { - singleHeader bool - name string - tests []injectTest + name string + tests []injectTest }{ { - singleHeader: false, - name: "multiple headers", - tests: injectB3MultipleHeader, + name: "valid headers", + tests: injectHeader, }, { - singleHeader: true, - name: "single headers", - tests: injectB3SingleleHeader, + name: "invalid headers", + tests: injectInvalidHeader, }, } - mockTracer := &mocktrace.MockTracer{ - Sampled: false, - StartSpanID: &id, - } - for _, tg := range testGroup { - id = 0 - propagator := trace.B3{SingleHeader: tg.singleHeader} for _, tt := range tg.tests { + propagator := trace.B3{InjectEncoding: tt.encoding} traceBenchmark(tg.name+"/"+tt.name, b, func(b *testing.B) { req, _ := http.NewRequest("GET", "http://example.com", nil) - ctx := context.Background() - if tt.parentSc.IsValid() { - ctx = trace.ContextWithRemoteSpanContext(ctx, tt.parentSc) - } - ctx, _ = mockTracer.Start(ctx, "inject") + ctx := trace.ContextWithSpan( + context.Background(), + testSpan{sc: tt.sc}, + ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/api/trace/testtrace/b3_propagator_data_test.go b/api/trace/testtrace/b3_propagator_data_test.go index 432ce4995d9..262bbe8be6e 100644 --- a/api/trace/testtrace/b3_propagator_data_test.go +++ b/api/trace/testtrace/b3_propagator_data_test.go @@ -15,9 +15,20 @@ package testtrace_test import ( + "fmt" + "go.opentelemetry.io/otel/api/trace" ) +const ( + b3Context = "b3" + b3Flags = "x-b3-flags" + b3TraceID = "x-b3-traceid" + b3SpanID = "x-b3-spanid" + b3Sampled = "x-b3-sampled" + b3ParentSpanID = "x-b3-parentspanid" +) + type extractTest struct { name string headers map[string]string @@ -28,24 +39,30 @@ var ( traceID64bitPadded = mustTraceIDFromHex("0000000000000000a3ce929d0e0e4736") ) -var extractMultipleHeaders = []extractTest{ +var extractHeaders = []extractTest{ + { + name: "empty", + headers: map[string]string{}, + wantSc: trace.EmptySpanContext(), + }, { - name: "sampling state defer", + name: "multiple: sampling state defer", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, }, wantSc: trace.SpanContext{ - TraceID: traceID, - SpanID: spanID, + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, }, }, { - name: "sampling state deny", + name: "multiple: sampling state deny", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "0", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -53,11 +70,11 @@ var extractMultipleHeaders = []extractTest{ }, }, { - name: "sampling state accept", + name: "multiple: sampling state accept", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -66,11 +83,11 @@ var extractMultipleHeaders = []extractTest{ }, }, { - name: "sampling state as a boolean", + name: "multiple: sampling state as a boolean: true", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "true", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "true", }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -79,28 +96,37 @@ var extractMultipleHeaders = []extractTest{ }, }, { - name: "debug flag set", + name: "multiple: sampling state as a boolean: false", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3DebugFlagHeader: "1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "false", + }, + wantSc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + }, + }, + { + name: "multiple: debug flag set", + headers: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", }, wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: trace.FlagsSampled, + TraceFlags: trace.FlagsDeferred | trace.FlagsDebug, }, }, { - // spec is not clear on the behavior for this case. If debug flag is set - // then sampled state should not be set. From that perspective debug - // takes precedence. Hence, it is sampled. - name: "debug flag set and sampling state is deny", + name: "multiple: debug flag set to not 1 (ignored)", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "0", - trace.B3DebugFlagHeader: "1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", + b3Flags: "2", }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -109,12 +135,29 @@ var extractMultipleHeaders = []extractTest{ }, }, { - name: "with parent span id", + // spec explicitly states "Debug implies an accept decision, so don't + // also send the X-B3-Sampled header", make sure sampling is + // deferred. + name: "multiple: debug flag set and sampling state is deny", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "1", - trace.B3ParentSpanIDHeader: "00f067aa0ba90200", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", + b3Flags: "1", + }, + wantSc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDebug, + }, + }, + { + name: "multiple: with parent span id", + headers: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", + b3ParentSpanID: "00f067aa0ba90200", }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -123,40 +166,39 @@ var extractMultipleHeaders = []extractTest{ }, }, { - name: "with only sampled state header", + name: "multiple: with only sampled state header", headers: map[string]string{ - trace.B3SampledHeader: "0", + b3Sampled: "0", }, wantSc: trace.EmptySpanContext(), }, { - name: "left-padding 64-bit traceID", + name: "multiple: left-padding 64-bit traceID", headers: map[string]string{ - trace.B3TraceIDHeader: "a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", + b3TraceID: "a3ce929d0e0e4736", + b3SpanID: spanIDStr, }, wantSc: trace.SpanContext{ - TraceID: traceID64bitPadded, - SpanID: spanID, + TraceID: traceID64bitPadded, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, }, }, -} - -var extractSingleHeader = []extractTest{ { - name: "sampling state defer", + name: "single: sampling state defer", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7", + b3Context: fmt.Sprintf("%s-%s", traceIDStr, spanIDStr), }, wantSc: trace.SpanContext{ - TraceID: traceID, - SpanID: spanID, + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, }, }, { - name: "sampling state deny", + name: "single: sampling state deny", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-0", + b3Context: fmt.Sprintf("%s-%s-0", traceIDStr, spanIDStr), }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -164,9 +206,9 @@ var extractSingleHeader = []extractTest{ }, }, { - name: "sampling state accept", + name: "single: sampling state accept", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1", + b3Context: fmt.Sprintf("%s-%s-1", traceIDStr, spanIDStr), }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -175,20 +217,20 @@ var extractSingleHeader = []extractTest{ }, }, { - name: "sampling state debug", + name: "single: sampling state debug", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-d", + b3Context: fmt.Sprintf("%s-%s-d", traceIDStr, spanIDStr), }, wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: trace.FlagsSampled, + TraceFlags: trace.FlagsDebug, }, }, { - name: "with parent span id", + name: "single: with parent span id", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1-00000000000000cd", + b3Context: fmt.Sprintf("%s-%s-1-00000000000000cd", traceIDStr, spanIDStr), }, wantSc: trace.SpanContext{ TraceID: traceID, @@ -197,373 +239,782 @@ var extractSingleHeader = []extractTest{ }, }, { - name: "with only sampling state deny", + name: "single: with only sampling state deny", headers: map[string]string{ - trace.B3SingleHeader: "0", + b3Context: "0", }, wantSc: trace.EmptySpanContext(), }, { - name: "left-padding 64-bit traceID", + name: "single: left-padding 64-bit traceID", headers: map[string]string{ - trace.B3SingleHeader: "a3ce929d0e0e4736-00f067aa0ba902b7", + b3Context: fmt.Sprintf("a3ce929d0e0e4736-%s", spanIDStr), }, wantSc: trace.SpanContext{ - TraceID: traceID64bitPadded, - SpanID: spanID, + TraceID: traceID64bitPadded, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, }, }, -} - -var extractInvalidB3MultipleHeaders = []extractTest{ { - name: "trace ID length > 32", + name: "both single and multiple: single priority", headers: map[string]string{ - trace.B3TraceIDHeader: "ab00000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3Context: fmt.Sprintf("%s-%s-1", traceIDStr, spanIDStr), + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", }, - }, - { - name: "trace ID length >16 and <32", - headers: map[string]string{ - trace.B3TraceIDHeader: "ab0000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + wantSc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled, }, }, + // An invalid Single Headers should fallback to multiple. { - name: "trace ID length <16", + name: "both single and multiple: invalid single", headers: map[string]string{ - trace.B3TraceIDHeader: "ab0000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3Context: fmt.Sprintf("%s-%s-", traceIDStr, spanIDStr), + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", }, - }, - { - name: "wrong span ID length", - headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "cd0000000000000000", - trace.B3SampledHeader: "1", + wantSc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, }, }, + // Invalid Mult Header should not be noticed as Single takes precedence. { - name: "wrong sampled flag length", + name: "both single and multiple: invalid multiple", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "10", + b3Context: fmt.Sprintf("%s-%s-1", traceIDStr, spanIDStr), + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "invalid", + }, + wantSc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled, }, }, +} + +var extractInvalidHeaders = []extractTest{ { - name: "bogus trace ID", + name: "multiple: trace ID length > 32", headers: map[string]string{ - trace.B3TraceIDHeader: "qw000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab00000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "bogus span ID", + name: "multiple: trace ID length >16 and <32", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "qw00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab0000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "bogus sampled flag", + name: "multiple: trace ID length <16", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "d", + b3TraceID: "ab0000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "bogus debug flag (string)", + name: "multiple: wrong span ID length", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", - trace.B3DebugFlagHeader: "d", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "cd0000000000000000", + b3Sampled: "1", }, }, { - name: "bogus debug flag (number)", + name: "multiple: wrong sampled flag length", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", - trace.B3DebugFlagHeader: "10", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "10", }, }, { - name: "upper case trace ID", + name: "multiple: bogus trace ID", headers: map[string]string{ - trace.B3TraceIDHeader: "AB000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "qw000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "upper case span ID", + name: "multiple: bogus span ID", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "CD00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "qw00000000000000", + b3Sampled: "1", }, }, { - name: "zero trace ID", + name: "multiple: bogus sampled flag", headers: map[string]string{ - trace.B3TraceIDHeader: "00000000000000000000000000000000", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "d", }, }, { - name: "zero span ID", + name: "multiple: upper case trace ID", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SpanIDHeader: "0000000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "AB000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "missing span ID", + name: "multiple: upper case span ID", headers: map[string]string{ - trace.B3TraceIDHeader: "ab000000000000000000000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "CD00000000000000", + b3Sampled: "1", }, }, { - name: "missing trace ID", + name: "multiple: zero trace ID", headers: map[string]string{ - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "00000000000000000000000000000000", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "missing trace ID with valid single header", + name: "multiple: zero span ID", headers: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1", - trace.B3SpanIDHeader: "cd00000000000000", - trace.B3SampledHeader: "1", + b3TraceID: "ab000000000000000000000000000000", + b3SpanID: "0000000000000000", + b3Sampled: "1", }, }, { - name: "sampled header set to 1 but trace ID and span ID are missing", + name: "multiple: missing span ID", headers: map[string]string{ - trace.B3SampledHeader: "1", + b3TraceID: "ab000000000000000000000000000000", + b3Sampled: "1", }, }, -} - -var extractInvalidB3SingleHeader = []extractTest{ { - name: "wrong trace ID length", + name: "multiple: missing trace ID", headers: map[string]string{ - trace.B3SingleHeader: "ab00000000000000000000000000000000-cd00000000000000-1", + b3SpanID: "cd00000000000000", + b3Sampled: "1", }, }, { - name: "wrong span ID length", + name: "multiple: sampled header set to 1 but trace ID and span ID are missing", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd0000000000000000-1", + b3Sampled: "1", }, }, { - name: "wrong sampled state length", + name: "single: wrong trace ID length", headers: map[string]string{ - trace.B3SingleHeader: "00-ab000000000000000000000000000000-cd00000000000000-01", + b3Context: "ab00000000000000000000000000000000-cd00000000000000-1", }, }, { - name: "wrong parent span ID length", + name: "single: wrong span ID length", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd00000000000000-1-cd0000000000000000", + b3Context: "ab000000000000000000000000000000-cd0000000000000000-1", }, }, { - name: "bogus trace ID", + name: "single: wrong sampled state length", headers: map[string]string{ - trace.B3SingleHeader: "qw000000000000000000000000000000-cd00000000000000-1", + b3Context: "00-ab000000000000000000000000000000-cd00000000000000-01", }, }, { - name: "bogus span ID", + name: "single: wrong parent span ID length", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-qw00000000000000-1", + b3Context: "ab000000000000000000000000000000-cd00000000000000-1-cd0000000000000000", }, }, { - name: "bogus sampled flag", + name: "single: bogus trace ID", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd00000000000000-q", + b3Context: "qw000000000000000000000000000000-cd00000000000000-1", }, }, { - name: "bogus parent span ID", + name: "single: bogus span ID", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd00000000000000-1-qw00000000000000", + b3Context: "ab000000000000000000000000000000-qw00000000000000-1", }, }, { - name: "upper case trace ID", + name: "single: bogus sampled flag", headers: map[string]string{ - trace.B3SingleHeader: "AB000000000000000000000000000000-cd00000000000000-1", + b3Context: "ab000000000000000000000000000000-cd00000000000000-q", }, }, { - name: "upper case span ID", + name: "single: bogus parent span ID", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-CD00000000000000-1", + b3Context: "ab000000000000000000000000000000-cd00000000000000-1-qw00000000000000", }, }, { - name: "upper case parent span ID", + name: "single: upper case trace ID", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd00000000000000-1-EF00000000000000", + b3Context: "AB000000000000000000000000000000-cd00000000000000-1", }, }, { - name: "zero trace ID and span ID", + name: "single: upper case span ID", headers: map[string]string{ - trace.B3SingleHeader: "00000000000000000000000000000000-0000000000000000-1", + b3Context: "ab000000000000000000000000000000-CD00000000000000-1", }, }, { - name: "missing single header with valid separate headers", + name: "single: upper case parent span ID", headers: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "1", + b3Context: "ab000000000000000000000000000000-cd00000000000000-1-EF00000000000000", }, }, { - name: "upper case span ID with valid separate headers", + name: "single: zero trace ID and span ID", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-CD00000000000000-1", - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "00f067aa0ba902b7", - trace.B3SampledHeader: "1", + b3Context: "00000000000000000000000000000000-0000000000000000-1", }, }, { - name: "with sampling set to true", + name: "single: with sampling set to true", headers: map[string]string{ - trace.B3SingleHeader: "ab000000000000000000000000000000-cd00000000000000-true", + b3Context: "ab000000000000000000000000000000-cd00000000000000-true", }, }, } type injectTest struct { name string - parentSc trace.SpanContext + encoding trace.B3Encoding + sc trace.SpanContext wantHeaders map[string]string doNotWantHeaders []string } -var injectB3MultipleHeader = []injectTest{ +var injectHeader = []injectTest{ { - name: "valid spancontext, sampled", - parentSc: trace.SpanContext{ + name: "none: sampled", + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, TraceFlags: trace.FlagsSampled, }, wantHeaders: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "0000000000000001", - trace.B3SampledHeader: "1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", }, doNotWantHeaders: []string{ - trace.B3ParentSpanIDHeader, + b3ParentSpanID, + b3Flags, + b3Context, }, }, { - name: "valid spancontext, not sampled", - parentSc: trace.SpanContext{ + name: "none: not sampled", + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, wantHeaders: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "0000000000000002", - trace.B3SampledHeader: "0", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", }, doNotWantHeaders: []string{ - trace.B3ParentSpanIDHeader, + b3ParentSpanID, + b3Flags, + b3Context, }, }, { - name: "valid spancontext, with unsupported bit set in traceflags", - parentSc: trace.SpanContext{ + name: "none: unset sampled", + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: 0xff, + TraceFlags: trace.FlagsDeferred, }, wantHeaders: map[string]string{ - trace.B3TraceIDHeader: "4bf92f3577b34da6a3ce929d0e0e4736", - trace.B3SpanIDHeader: "0000000000000003", - trace.B3SampledHeader: "1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, }, doNotWantHeaders: []string{ - trace.B3ParentSpanIDHeader, + b3Sampled, + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "none: sampled only", + sc: trace.SpanContext{ + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3Sampled: "1", + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "none: debug", + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Context, + }, + }, + { + name: "none: debug omitting sample", + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled | trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Context, + }, + }, + { + name: "multiple: sampled", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", + }, + doNotWantHeaders: []string{ + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "multiple: not sampled", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", + }, + doNotWantHeaders: []string{ + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "multiple: unset sampled", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "multiple: sampled only", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3Sampled: "1", + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "multiple: debug", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Context, + }, + }, + { + name: "multiple: debug omitting sample", + encoding: trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled | trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Context, + }, + }, + { + name: "single: sampled", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3Context: fmt.Sprintf("%s-%s-1", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3ParentSpanID, + b3Flags, + }, + }, + { + name: "single: not sampled", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + }, + wantHeaders: map[string]string{ + b3Context: fmt.Sprintf("%s-%s-0", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3ParentSpanID, + b3Flags, + }, + }, + { + name: "single: unset sampled", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, + }, + wantHeaders: map[string]string{ + b3Context: fmt.Sprintf("%s-%s", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3ParentSpanID, + b3Flags, + }, + }, + { + name: "single: sampled only", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3Context: "1", + }, + doNotWantHeaders: []string{ + b3Sampled, + b3TraceID, + b3SpanID, + b3ParentSpanID, + b3Flags, + b3Context, + }, + }, + { + name: "single: debug", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3Context: fmt.Sprintf("%s-%s-d", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3Flags, + b3Sampled, + b3ParentSpanID, + b3Context, + }, + }, + { + name: "single: debug omitting sample", + encoding: trace.B3SingleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled | trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3Context: fmt.Sprintf("%s-%s-d", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3TraceID, + b3SpanID, + b3Flags, + b3Sampled, + b3ParentSpanID, + b3Context, }, }, -} - -var injectB3SingleleHeader = []injectTest{ { - name: "valid spancontext, sampled", - parentSc: trace.SpanContext{ + name: "single+multiple: sampled", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, TraceFlags: trace.FlagsSampled, }, wantHeaders: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-0000000000000001-1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "1", + b3Context: fmt.Sprintf("%s-%s-1", traceIDStr, spanIDStr), }, doNotWantHeaders: []string{ - trace.B3TraceIDHeader, - trace.B3SpanIDHeader, - trace.B3SampledHeader, - trace.B3ParentSpanIDHeader, + b3ParentSpanID, + b3Flags, }, }, { - name: "valid spancontext, not sampled", - parentSc: trace.SpanContext{ + name: "single+multiple: not sampled", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, wantHeaders: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-0", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Sampled: "0", + b3Context: fmt.Sprintf("%s-%s-0", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3ParentSpanID, + b3Flags, + }, + }, + { + name: "single+multiple: unset sampled", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsDeferred, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Context: fmt.Sprintf("%s-%s", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + b3Flags, + }, + }, + { + name: "single+multiple: sampled only", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceFlags: trace.FlagsSampled, + }, + wantHeaders: map[string]string{ + b3Context: "1", + b3Sampled: "1", }, doNotWantHeaders: []string{ - trace.B3TraceIDHeader, - trace.B3SpanIDHeader, - trace.B3SampledHeader, - trace.B3ParentSpanIDHeader, + b3TraceID, + b3SpanID, + b3ParentSpanID, + b3Flags, }, }, { - name: "valid spancontext, with unsupported bit set in traceflags", - parentSc: trace.SpanContext{ + name: "single+multiple: debug", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: 0xff, + TraceFlags: trace.FlagsDebug, }, wantHeaders: map[string]string{ - trace.B3SingleHeader: "4bf92f3577b34da6a3ce929d0e0e4736-0000000000000003-1", + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + b3Context: fmt.Sprintf("%s-%s-d", traceIDStr, spanIDStr), }, doNotWantHeaders: []string{ - trace.B3TraceIDHeader, - trace.B3SpanIDHeader, - trace.B3SampledHeader, - trace.B3ParentSpanIDHeader, + b3Sampled, + b3ParentSpanID, }, }, + { + name: "single+multiple: debug omitting sample", + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: trace.SpanContext{ + TraceID: traceID, + SpanID: spanID, + TraceFlags: trace.FlagsSampled | trace.FlagsDebug, + }, + wantHeaders: map[string]string{ + b3TraceID: traceIDStr, + b3SpanID: spanIDStr, + b3Flags: "1", + b3Context: fmt.Sprintf("%s-%s-d", traceIDStr, spanIDStr), + }, + doNotWantHeaders: []string{ + b3Sampled, + b3ParentSpanID, + }, + }, +} + +var injectInvalidHeaderGenerator = []injectTest{ + { + name: "empty", + sc: trace.SpanContext{}, + }, + { + name: "missing traceID", + sc: trace.SpanContext{ + SpanID: spanID, + TraceFlags: trace.FlagsSampled, + }, + }, + { + name: "missing spanID", + sc: trace.SpanContext{ + TraceID: traceID, + TraceFlags: trace.FlagsSampled, + }, + }, + { + name: "missing traceID and spanID", + sc: trace.SpanContext{ + TraceFlags: trace.FlagsSampled, + }, + }, +} + +var injectInvalidHeader []injectTest + +func init() { + // Preform a test for each invalid injectTest with all combinations of + // encoding values. + injectInvalidHeader = make([]injectTest, 0, len(injectInvalidHeaderGenerator)*4) + allHeaders := []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3ParentSpanID, + b3Flags, + b3Context, + } + // Nothing should be set for any header regardless of encoding. + for _, t := range injectInvalidHeaderGenerator { + injectInvalidHeader = append(injectInvalidHeader, injectTest{ + name: "none: " + t.name, + sc: t.sc, + doNotWantHeaders: allHeaders, + }) + injectInvalidHeader = append(injectInvalidHeader, injectTest{ + name: "multiple: " + t.name, + encoding: trace.B3MultipleHeader, + sc: t.sc, + doNotWantHeaders: allHeaders, + }) + injectInvalidHeader = append(injectInvalidHeader, injectTest{ + name: "single: " + t.name, + encoding: trace.B3SingleHeader, + sc: t.sc, + doNotWantHeaders: allHeaders, + }) + injectInvalidHeader = append(injectInvalidHeader, injectTest{ + name: "single+multiple: " + t.name, + encoding: trace.B3SingleHeader | trace.B3MultipleHeader, + sc: t.sc, + doNotWantHeaders: allHeaders, + }) + } } diff --git a/api/trace/testtrace/b3_propagator_test.go b/api/trace/testtrace/b3_propagator_test.go index 8aba57a6127..5384a145557 100644 --- a/api/trace/testtrace/b3_propagator_test.go +++ b/api/trace/testtrace/b3_propagator_test.go @@ -23,39 +23,25 @@ import ( "go.opentelemetry.io/otel/api/propagation" "go.opentelemetry.io/otel/api/trace" - mocktrace "go.opentelemetry.io/otel/internal/trace" ) func TestExtractB3(t *testing.T) { testGroup := []struct { - singleHeader bool - name string - tests []extractTest + name string + tests []extractTest }{ { - singleHeader: false, - name: "multiple headers", - tests: extractMultipleHeaders, + name: "valid extract headers", + tests: extractHeaders, }, { - singleHeader: true, - name: "single headers", - tests: extractSingleHeader, - }, - { - singleHeader: false, - name: "invalid multiple headers", - tests: extractInvalidB3MultipleHeaders, - }, - { - singleHeader: true, - name: "invalid single headers", - tests: extractInvalidB3SingleHeader, + name: "invalid extract headers", + tests: extractInvalidHeaders, }, } for _, tg := range testGroup { - propagator := trace.B3{SingleHeader: tg.singleHeader} + propagator := trace.B3{} props := propagation.New(propagation.WithExtractors(propagator)) for _, tt := range tg.tests { @@ -76,43 +62,40 @@ func TestExtractB3(t *testing.T) { } } +type testSpan struct { + trace.NoopSpan + sc trace.SpanContext +} + +func (s testSpan) SpanContext() trace.SpanContext { + return s.sc +} + func TestInjectB3(t *testing.T) { - var id uint64 testGroup := []struct { - singleHeader bool - name string - tests []injectTest + name string + tests []injectTest }{ { - singleHeader: false, - name: "multiple headers", - tests: injectB3MultipleHeader, + name: "valid inject headers", + tests: injectHeader, }, { - singleHeader: true, - name: "single headers", - tests: injectB3SingleleHeader, + name: "invalid inject headers", + tests: injectInvalidHeader, }, } - mockTracer := &mocktrace.MockTracer{ - Sampled: false, - StartSpanID: &id, - } - for _, tg := range testGroup { - id = 0 - propagator := trace.B3{SingleHeader: tg.singleHeader} - props := propagation.New(propagation.WithInjectors(propagator)) for _, tt := range tg.tests { + propagator := trace.B3{InjectEncoding: tt.encoding} t.Run(tt.name, func(t *testing.T) { req, _ := http.NewRequest("GET", "http://example.com", nil) - ctx := context.Background() - if tt.parentSc.IsValid() { - ctx = trace.ContextWithRemoteSpanContext(ctx, tt.parentSc) - } - ctx, _ = mockTracer.Start(ctx, "inject") - propagation.InjectHTTP(ctx, props, req.Header) + ctx := trace.ContextWithSpan( + context.Background(), + testSpan{sc: tt.sc}, + ) + propagator.Inject(ctx, req.Header) for h, v := range tt.wantHeaders { got, want := req.Header.Get(h), v @@ -132,25 +115,54 @@ func TestInjectB3(t *testing.T) { } func TestB3Propagator_GetAllKeys(t *testing.T) { - propagator := trace.B3{SingleHeader: false} - want := []string{ - trace.B3TraceIDHeader, - trace.B3SpanIDHeader, - trace.B3SampledHeader, - } - got := propagator.GetAllKeys() - if diff := cmp.Diff(got, want); diff != "" { - t.Errorf("GetAllKeys: -got +want %s", diff) + tests := []struct { + name string + propagator trace.B3 + want []string + }{ + { + name: "no encoding specified", + propagator: trace.B3{}, + want: []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3Flags, + }, + }, + { + name: "B3MultipleHeader encoding specified", + propagator: trace.B3{InjectEncoding: trace.B3MultipleHeader}, + want: []string{ + b3TraceID, + b3SpanID, + b3Sampled, + b3Flags, + }, + }, + { + name: "B3SingleHeader encoding specified", + propagator: trace.B3{InjectEncoding: trace.B3SingleHeader}, + want: []string{ + b3Context, + }, + }, + { + name: "B3SingleHeader and B3MultipleHeader encoding specified", + propagator: trace.B3{InjectEncoding: trace.B3SingleHeader | trace.B3MultipleHeader}, + want: []string{ + b3Context, + b3TraceID, + b3SpanID, + b3Sampled, + b3Flags, + }, + }, } -} -func TestB3PropagatorWithSingleHeader_GetAllKeys(t *testing.T) { - propagator := trace.B3{SingleHeader: true} - want := []string{ - trace.B3SingleHeader, - } - got := propagator.GetAllKeys() - if diff := cmp.Diff(got, want); diff != "" { - t.Errorf("GetAllKeys: -got +want %s", diff) + for _, test := range tests { + if diff := cmp.Diff(test.propagator.GetAllKeys(), test.want); diff != "" { + t.Errorf("%s: GetAllKeys: -got +want %s", test.name, diff) + } } } diff --git a/api/trace/testtrace/propagator_test.go b/api/trace/testtrace/propagator_test.go index 09b75bcc853..4cbab89fc9f 100644 --- a/api/trace/testtrace/propagator_test.go +++ b/api/trace/testtrace/propagator_test.go @@ -66,8 +66,9 @@ func TestMultiplePropagators(t *testing.T) { ns := nilSupplier{} testProps := []propagation.HTTPPropagator{ trace.TraceContext{}, - trace.B3{SingleHeader: false}, - trace.B3{SingleHeader: true}, + trace.B3{}, + trace.B3{InjectEncoding: trace.B3SingleHeader}, + trace.B3{InjectEncoding: trace.B3SingleHeader | trace.B3MultipleHeader}, } bg := context.Background() // sanity check of oota propagator, ensuring that it really diff --git a/api/trace/testtrace/trace_context_propagator_test.go b/api/trace/testtrace/trace_context_propagator_test.go index 2a8fea2fcd0..10a7434e920 100644 --- a/api/trace/testtrace/trace_context_propagator_test.go +++ b/api/trace/testtrace/trace_context_propagator_test.go @@ -26,18 +26,31 @@ import ( mocktrace "go.opentelemetry.io/otel/internal/trace" ) +const ( + traceIDStr = "4bf92f3577b34da6a3ce929d0e0e4736" + spanIDStr = "00f067aa0ba902b7" +) + var ( - traceID = mustTraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") - spanID = mustSpanIDFromHex("00f067aa0ba902b7") + traceID = mustTraceIDFromHex(traceIDStr) + spanID = mustSpanIDFromHex(spanIDStr) ) func mustTraceIDFromHex(s string) (t trace.ID) { - t, _ = trace.IDFromHex(s) + var err error + t, err = trace.IDFromHex(s) + if err != nil { + panic(err) + } return } func mustSpanIDFromHex(s string) (t trace.SpanID) { - t, _ = trace.SpanIDFromHex(s) + var err error + t, err = trace.SpanIDFromHex(s) + if err != nil { + panic(err) + } return } diff --git a/api/trace/trace_context_propagator.go b/api/trace/trace_context_propagator.go index d8263745ef8..5413106f440 100644 --- a/api/trace/trace_context_propagator.go +++ b/api/trace/trace_context_propagator.go @@ -137,7 +137,8 @@ func (TraceContext) extract(supplier propagation.HTTPSupplier) SpanContext { if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) { return EmptySpanContext() } - sc.TraceFlags = opts[0] &^ FlagsUnused + // Clear all flags other than the trace-context supported sampling bit. + sc.TraceFlags = opts[0] & FlagsSampled if !sc.IsValid() { return EmptySpanContext()