-
Notifications
You must be signed in to change notification settings - Fork 40
/
context.go
294 lines (246 loc) · 10.1 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
/*
* Unless explicitly stated otherwise all files in this repository are licensed
* under the Apache License Version 2.0.
*
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2021 Datadog, Inc.
*/
package trace
import (
"context"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"strconv"
"strings"
"github.com/DataDog/datadog-lambda-go/internal/extension"
"github.com/DataDog/datadog-lambda-go/internal/logger"
"github.com/aws/aws-xray-sdk-go/header"
"github.com/aws/aws-xray-sdk-go/xray"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
type (
eventWithHeaders struct {
Headers map[string]string `json:"headers"`
}
// TraceContext is map of headers containing a Datadog trace context.
TraceContext map[string]string
// ContextExtractor is a func type for extracting a root TraceContext.
ContextExtractor func(ctx context.Context, ev json.RawMessage) map[string]string
)
type contextKeytype int
// traceContextKey is the key used to store a TraceContext in a TraceContext object
var traceContextKey = new(contextKeytype)
// DefaultTraceExtractor is the default trace extractor. Extracts root trace from API Gateway headers.
var DefaultTraceExtractor = getHeadersFromEventHeaders
// contextWithRootTraceContext uses the incoming event and context object payloads to determine
// the root TraceContext and then adds that TraceContext to the context object.
func contextWithRootTraceContext(ctx context.Context, ev json.RawMessage, mergeXrayTraces bool, extractor ContextExtractor) (context.Context, error) {
datadogTraceContext, gotDatadogTraceContext := getTraceContext(ctx, extractor(ctx, ev))
xrayTraceContext, errGettingXrayContext := convertXrayTraceContextFromLambdaContext(ctx)
if errGettingXrayContext != nil {
logger.Error(fmt.Errorf("Couldn't convert X-Ray trace context: %v", errGettingXrayContext))
}
if gotDatadogTraceContext && errGettingXrayContext == nil {
err := createDummySubsegmentForXrayConverter(ctx, datadogTraceContext)
if err != nil {
logger.Error(fmt.Errorf("Couldn't create segment: %v", err))
}
}
if !mergeXrayTraces {
logger.Debug("Merge X-Ray Traces is off, using trace context from Datadog only")
return context.WithValue(ctx, traceContextKey, datadogTraceContext), nil
}
if !gotDatadogTraceContext {
logger.Debug("Merge X-Ray Traces is on, but did not get incoming Datadog trace context; using X-Ray trace context instead")
return context.WithValue(ctx, traceContextKey, xrayTraceContext), nil
}
logger.Debug("Using merged Datadog/X-Ray trace context")
mergedTraceContext := TraceContext{}
mergedTraceContext[traceIDHeader] = datadogTraceContext[traceIDHeader]
mergedTraceContext[samplingPriorityHeader] = datadogTraceContext[samplingPriorityHeader]
mergedTraceContext[parentIDHeader] = xrayTraceContext[parentIDHeader]
return context.WithValue(ctx, traceContextKey, mergedTraceContext), nil
}
// ConvertCurrentXrayTraceContext returns the current X-Ray trace context converted to Datadog headers, taking into account
// the current subsegment. It is designed for sending Datadog trace headers from functions instrumented with the X-Ray SDK.
func ConvertCurrentXrayTraceContext(ctx context.Context) TraceContext {
if xrayTraceContext, err := convertXrayTraceContextFromLambdaContext(ctx); err == nil {
// If there is an active X-Ray segment, use it as the parent
parentID := xrayTraceContext[parentIDHeader]
segment := xray.GetSegment(ctx)
if segment != nil {
newParentID, err := convertXRayEntityIDToDatadogParentID(segment.ID)
if err == nil {
parentID = newParentID
}
}
newTraceContext := map[string]string{}
newTraceContext[traceIDHeader] = xrayTraceContext[traceIDHeader]
newTraceContext[samplingPriorityHeader] = xrayTraceContext[samplingPriorityHeader]
newTraceContext[parentIDHeader] = parentID
return newTraceContext
}
return map[string]string{}
}
// createDummySubsegmentForXrayConverter creates a dummy X-Ray subsegment containing Datadog trace context metadata.
// This metadata is used by the Datadog X-Ray converter to parent the X-Ray trace under the Datadog trace.
// This subsegment will be dropped by the X-Ray converter and will not appear in Datadog.
func createDummySubsegmentForXrayConverter(ctx context.Context, traceCtx TraceContext) error {
_, segment := xray.BeginSubsegment(ctx, xraySubsegmentName)
traceID := traceCtx[traceIDHeader]
parentID := traceCtx[parentIDHeader]
sampled := traceCtx[samplingPriorityHeader]
metadata := map[string]string{
"trace-id": traceID,
"parent-id": parentID,
"sampling-priority": sampled,
}
err := segment.AddMetadataToNamespace(xraySubsegmentNamespace, xraySubsegmentKey, metadata)
if err != nil {
return fmt.Errorf("couldn't save trace context to XRay: %v", err)
}
segment.Close(nil)
return nil
}
func getTraceContext(ctx context.Context, headers map[string]string) (TraceContext, bool) {
tc := TraceContext{}
traceID := headers[traceIDHeader]
if traceID == "" {
if val, ok := ctx.Value(extension.DdTraceId).(string); ok {
traceID = val
}
}
if traceID == "" {
return tc, false
}
parentID := headers[parentIDHeader]
if parentID == "" {
if val, ok := ctx.Value(extension.DdParentId).(string); ok {
parentID = val
}
}
if parentID == "" {
return tc, false
}
samplingPriority := headers[samplingPriorityHeader]
if samplingPriority == "" {
if val, ok := ctx.Value(extension.DdSamplingPriority).(string); ok {
samplingPriority = val
}
}
if samplingPriority == "" {
samplingPriority = "1" //sampler-keep
}
tc[samplingPriorityHeader] = samplingPriority
tc[traceIDHeader] = traceID
tc[parentIDHeader] = parentID
return tc, true
}
// getHeadersFromEventHeaders extracts the Datadog trace context from an incoming Lambda event payload
// and creates a dummy X-Ray subsegment containing this information.
// This is used as the DefaultTraceExtractor.
func getHeadersFromEventHeaders(ctx context.Context, ev json.RawMessage) map[string]string {
eh := eventWithHeaders{}
headers := map[string]string{}
err := json.Unmarshal(ev, &eh)
if err != nil {
return headers
}
lowercaseHeaders := map[string]string{}
for k, v := range eh.Headers {
lowercaseHeaders[strings.ToLower(k)] = v
}
return lowercaseHeaders
}
func convertXrayTraceContextFromLambdaContext(ctx context.Context) (TraceContext, error) {
traceCtx := map[string]string{}
header := getXrayTraceHeaderFromContext(ctx)
if header == nil {
return traceCtx, fmt.Errorf("Couldn't read X-Ray trace context from Lambda context object")
}
traceID, err := convertXRayTraceIDToDatadogTraceID(header.TraceID)
if err != nil {
return traceCtx, fmt.Errorf("Couldn't read trace id from X-Ray: %v", err)
}
parentID, err := convertXRayEntityIDToDatadogParentID(header.ParentID)
if err != nil {
return traceCtx, fmt.Errorf("Couldn't read parent id from X-Ray: %v", err)
}
samplingPriority := convertXRaySamplingDecision(header.SamplingDecision)
traceCtx[traceIDHeader] = traceID
traceCtx[parentIDHeader] = parentID
traceCtx[samplingPriorityHeader] = samplingPriority
return traceCtx, nil
}
// getXrayTraceHeaderFromContext is used to extract xray segment metadata from the lambda context object.
// By default, the context object won't have any Segment, (xray.GetSegment(ctx) will return nil). However it
// will have the "LambdaTraceHeader" object, which contains the traceID/parentID/sampling info.
func getXrayTraceHeaderFromContext(ctx context.Context) *header.Header {
var traceHeader string
if traceHeaderValue := ctx.Value(xray.LambdaTraceHeaderKey); traceHeaderValue != nil {
traceHeader = traceHeaderValue.(string)
return header.FromString(traceHeader)
}
return nil
}
// Converts the last 63 bits of an X-Ray trace ID (hex) to a Datadog trace id (uint64).
func convertXRayTraceIDToDatadogTraceID(traceID string) (string, error) {
parts := strings.Split(traceID, "-")
if len(parts) != 3 {
return "0", fmt.Errorf("invalid x-ray trace id; expected 3 components in id")
}
if len(parts[2]) != 24 {
return "0", fmt.Errorf("x-ray trace id should be 96 bits")
}
traceIDLength := len(parts[2]) - 16
traceID = parts[2][traceIDLength : traceIDLength+16] // Per XRay Team: use the last 64 bits of the trace id
apmTraceID, err := convertHexIDToUint64(traceID)
if err != nil {
return "0", fmt.Errorf("while converting xray trace id: %v", err)
}
apmTraceID = 0x7FFFFFFFFFFFFFFF & apmTraceID // The APM Trace ID is restricted to 63 bits, so make sure the 64th bit is always 0
return strconv.FormatUint(apmTraceID, 10), nil
}
func convertHexIDToUint64(hexNumber string) (uint64, error) {
ba, err := hex.DecodeString(hexNumber)
if err != nil {
return 0, fmt.Errorf("couldn't convert hex to uint64: %v", err)
}
return binary.BigEndian.Uint64(ba), nil // TODO: Verify that this is correct
}
// Converts an X-Ray entity ID (hex) to a Datadog parent id (uint64).
func convertXRayEntityIDToDatadogParentID(entityID string) (string, error) {
if len(entityID) < 16 {
return "0", fmt.Errorf("couldn't convert to trace id, too short")
}
val, err := convertHexIDToUint64(entityID[len(entityID)-16:])
if err != nil {
return "0", fmt.Errorf("couldn't convert entity id to trace id: %v", err)
}
return strconv.FormatUint(val, 10), nil
}
// Converts an X-Ray sampling decision into its Datadog counterpart.
func convertXRaySamplingDecision(decision header.SamplingDecision) string {
if decision == header.Sampled {
return userKeep
}
return userReject
}
// ConvertTraceContextToSpanContext converts a TraceContext object to a SpanContext that can be used by dd-trace.
func ConvertTraceContextToSpanContext(traceCtx TraceContext) (ddtrace.SpanContext, error) {
spanCtx, err := propagator.Extract(tracer.TextMapCarrier(traceCtx))
if err != nil {
logger.Debug("Could not convert TraceContext to a SpanContext (most likely TraceContext was empty)")
return nil, err
}
return spanCtx, nil
}
// propagator is able to extract a SpanContext object from a TraceContext object
var propagator = tracer.NewPropagator(&tracer.PropagatorConfig{
TraceHeader: traceIDHeader,
ParentHeader: parentIDHeader,
PriorityHeader: samplingPriorityHeader,
})