Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add AWS X-Ray Propagator #248

Merged
merged 4 commits into from
Nov 21, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
### Added

- `otelhttp.{Get,Head,Post,PostForm}` convenience wrappers for their `http` counterparts. (#390)
- Add propagator for AWS X-Ray (#248)

### Changed

Expand Down
180 changes: 180 additions & 0 deletions propagators/awsxray/awsxray_propagator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
// 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 aws

import (
"context"
"errors"
"strings"

"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/api/trace"
)

const (
traceHeaderKey = "X-Amzn-Trace-Id"
traceHeaderDelimiter = ";"
kvDelimiter = "="
traceIdKey = "Root"
sampleFlagKey = "Sampled"
parentIdKey = "Parent"
traceIdVersion = "1"
traceIdDelimiter = "-"
KKelvinLo marked this conversation as resolved.
Show resolved Hide resolved
isSampled = "1"
notSampled = "0"

traceFlagNone = 0x0
traceFlagSampled = 0x1 << 0
traceIdLength = 35
traceIdDelimitterIndex1 = 1
traceIdDelimitterIndex2 = 10
traceIdFirstPartLength = 8
parentIdLength = 16
sampledFlagLength = 1
)

var (
empty = trace.EmptySpanContext()
errInvalidTraceHeader = errors.New("invalid X-Amzn-Trace-Id header value, should contain 3 different part separated by ;")
errMalformedTraceID = errors.New("cannot decode trace id from header, should be a string of hex, lowercase trace id can't be all zero")
errInvalidSpanIDLength = errors.New("invalid span id length, must be 16")
)

// AwsXray propagator serializes Span Context to/from AWS X-Ray headers
//
// AWS X-Ray format
//
// X-Amzn-Trace-Id: Root={traceId};Parent={parentId};Sampled={samplingFlag}
type AwsXray struct{}

var _ otel.TextMapPropagator = &AwsXray{}
KKelvinLo marked this conversation as resolved.
Show resolved Hide resolved

// Inject injects a context to the carrier following AWS X-Ray format.
func (awsxray AwsXray) Inject(ctx context.Context, carrier otel.TextMapCarrier) {
sc := trace.SpanFromContext(ctx).SpanContext()
headers := []string{}
if !sc.TraceID.IsValid() || !sc.SpanID.IsValid() {
return
}
otTraceId := sc.TraceID.String()
xrayTraceId := traceIdVersion + traceIdDelimiter + otTraceId[0:traceIdFirstPartLength] +
traceIdDelimiter + otTraceId[traceIdFirstPartLength:]
parentId := sc.SpanID
samplingFlag := notSampled
if sc.TraceFlags == traceFlagSampled {
samplingFlag = isSampled
}

headers = append(headers, traceIdKey, kvDelimiter, xrayTraceId, traceHeaderDelimiter, parentIdKey,
kvDelimiter, parentId.String(), traceHeaderDelimiter, sampleFlagKey, kvDelimiter, samplingFlag)

carrier.Set(traceHeaderKey, strings.Join(headers, ""))
}

// Extract extracts a context from the carrier if it contains AWS X-Ray headers.
func (awsxray AwsXray) Extract(ctx context.Context, carrier otel.TextMapCarrier) context.Context {
// extract tracing information
if h := carrier.Get(traceHeaderKey); h != "" {
KKelvinLo marked this conversation as resolved.
Show resolved Hide resolved
sc, err := extract(h)
if err == nil && sc.IsValid() {
return trace.ContextWithRemoteSpanContext(ctx, sc)
}
}
return ctx
}

func extract(headerVal string) (trace.SpanContext, error) {
var (
sc = trace.SpanContext{}
err error
delimiterIndex int
part string
)
pos := 0
for pos < len(headerVal) {
delimiterIndex = indexOf(headerVal, traceHeaderDelimiter, pos)
if delimiterIndex >= 0 {
part = headerVal[pos:delimiterIndex]
pos = delimiterIndex + 1
} else {
//last part
part = strings.TrimSpace(headerVal[pos:])
pos = len(headerVal)
}
equalsIndex := strings.Index(part, kvDelimiter)
if equalsIndex < 0 {
return empty, errInvalidTraceHeader
}
value := part[equalsIndex+1:]
if strings.HasPrefix(part, traceIdKey) {
sc.TraceID, err = parseTraceId(value)
if err != nil {
return empty, errMalformedTraceID
}
} else if strings.HasPrefix(part, parentIdKey) {
//extract parentId
sc.SpanID, err = trace.SpanIDFromHex(value)
if err != nil {
return empty, errInvalidSpanIDLength
}
} else if strings.HasPrefix(part, sampleFlagKey) {
//extract traceflag
sc.TraceFlags = parseTraceFlag(value)
}
}
return sc, nil
}

//returns position of the first occurence of a substring starting at pos index
func indexOf(str string, substr string, pos int) int {
index := strings.Index(str[pos:], substr)
if index > -1 {
index += pos
}
return index
}

//returns trace Id if valid else return invalid trace Id
func parseTraceId(xrayTraceId string) (trace.ID, error) {
if len(xrayTraceId) != traceIdLength {
return empty.TraceID, errMalformedTraceID
}
if !strings.HasPrefix(xrayTraceId, traceIdVersion) {
return empty.TraceID, errMalformedTraceID
}

if xrayTraceId[traceIdDelimitterIndex1:traceIdDelimitterIndex1+1] != traceIdDelimiter ||
xrayTraceId[traceIdDelimitterIndex2:+traceIdDelimitterIndex2+1] != traceIdDelimiter {
KKelvinLo marked this conversation as resolved.
Show resolved Hide resolved
return empty.TraceID, errMalformedTraceID
}

epochPart := xrayTraceId[traceIdDelimitterIndex1+1 : traceIdDelimitterIndex2]
uniquePart := xrayTraceId[traceIdDelimitterIndex2+1 : traceIdLength]

result := epochPart + uniquePart
return trace.IDFromHex(result)
}

//returns traceFlag
func parseTraceFlag(xraySampledFlag string) byte {
if len(xraySampledFlag) == sampledFlagLength && xraySampledFlag != isSampled {
return traceFlagNone
}
return trace.FlagsSampled
}

func (awsxray AwsXray) Fields() []string {
return []string{traceHeaderKey}
}
105 changes: 105 additions & 0 deletions propagators/awsxray/awsxray_propagator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// 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 aws

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
"go.opentelemetry.io/otel/api/trace"
)

var (
traceID = trace.ID{0x8a, 0x3c, 0x60, 0xf7, 0xd1, 0x88, 0xf8, 0xfa, 0x79, 0xd4, 0x8a, 0x39, 0x1a, 0x77, 0x8f, 0xa6}
xrayTraceId = "1-8a3c60f7-d188f8fa79d48a391a778fa6"
parentID64Str = "53995c3f42cd8ad8"
parentSpanID = trace.SpanID{0x53, 0x99, 0x5c, 0x3f, 0x42, 0xcd, 0x8a, 0xd8}
sampledTraceFlag = trace.FlagsSampled
zeroSpanIDStr = "0000000000000000"
invalidSpanIDStr = "0000000000010"
zeroTraceIDStr = "1-00000000-000000000000000000000000"
invalidTraceHeaderID = "1b00000000b000000000000000000000000"
wrongVersionTraceHeaderID = "5b00000000b000000000000000000000000"
)

func TestJaeger_Extract(t *testing.T) {
testData := []struct {
traceID string
parentSpanID string
samplingFlag string
expected trace.SpanContext
err error
}{
{
xrayTraceId, parentID64Str, notSampled,
trace.SpanContext{
TraceID: traceID,
SpanID: parentSpanID,
TraceFlags: traceFlagNone,
},
nil,
},
{
xrayTraceId, parentID64Str, isSampled,
trace.SpanContext{
TraceID: traceID,
SpanID: parentSpanID,
TraceFlags: traceFlagSampled,
},
nil,
},
{
zeroTraceIDStr, parentID64Str, isSampled,
trace.SpanContext{},
errMalformedTraceID,
},
{
xrayTraceId, zeroSpanIDStr, isSampled,
trace.SpanContext{},
errInvalidSpanIDLength,
},
{
invalidTraceHeaderID, parentID64Str, isSampled,
trace.SpanContext{},
errMalformedTraceID,
},
{
wrongVersionTraceHeaderID, parentID64Str, isSampled,
trace.SpanContext{},
errMalformedTraceID,
},
}

for _, test := range testData {
headerVal := strings.Join([]string{traceIdKey, kvDelimiter, test.traceID, traceHeaderDelimiter, parentIdKey, kvDelimiter,
test.parentSpanID, traceHeaderDelimiter, sampleFlagKey, kvDelimiter, test.samplingFlag}, "")

sc, err := extract(headerVal)

info := []interface{}{
"trace ID: %q, parent span ID: %q, sampling flag: %q",
test.traceID,
test.parentSpanID,
test.samplingFlag,
}

if !assert.Equal(t, test.err, err, info...) {
continue
}

assert.Equal(t, test.expected, sc, info...)
}
}
1 change: 1 addition & 0 deletions propagators/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.opentelemetry.io v0.1.0 h1:EANZoRCOP+A3faIlw/iN6YEWoYb1vleZRKm1EvH8T48=
go.opentelemetry.io/otel v0.13.0 h1:2isEnyzjjJZq6r2EKMsFj4TxiQiexsM04AVhwbR/oBA=
go.opentelemetry.io/otel v0.13.0/go.mod h1:dlSNewoRYikTkotEnxdmuBHgzT+k/idJSfDv/FxEnOY=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
Expand Down