/
spancontext_test.go
483 lines (422 loc) · 12.5 KB
/
spancontext_test.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// 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 2016 Datadog, Inc.
package tracer
import (
"context"
"math"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
"gopkg.in/DataDog/dd-trace-go.v1/internal/samplernames"
)
func setupteardown(start, max int) func() {
oldStartSize := traceStartSize
oldMaxSize := traceMaxSize
traceStartSize = start
traceMaxSize = max
return func() {
traceStartSize = oldStartSize
traceMaxSize = oldMaxSize
}
}
func TestNewSpanContextPushError(t *testing.T) {
defer setupteardown(2, 2)()
tp := new(testLogger)
_, _, _, stop := startTestTracer(t, WithLogger(tp), WithLambdaMode(true))
defer stop()
parent := newBasicSpan("test1") // 1st span in trace
parent.context.trace.push(newBasicSpan("test2")) // 2nd span in trace
child := newSpan("child", "", "", 0, 0, 0)
// new context having a parent with a trace of two spans.
// One more should overflow.
child.context = newSpanContext(child, parent.context)
log.Flush()
assert.Contains(t, removeAppSec(tp.Lines())[0], "ERROR: trace buffer full (2)")
}
func TestAsyncSpanRace(t *testing.T) {
// This tests a regression where asynchronously finishing spans would
// modify a flushing root's sampling priority.
_, _, _, stop := startTestTracer(t)
defer stop()
for i := 0; i < 100; i++ {
// The test has 100 iterations because it is not easy to reproduce the race.
t.Run("", func(t *testing.T) {
root, ctx := StartSpanFromContext(context.Background(), "root", Tag(ext.SamplingPriority, ext.PriorityUserKeep))
var wg sync.WaitGroup
done := make(chan struct{})
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-done:
root.Finish()
for i := 0; i < 500; i++ {
for range root.(*span).Metrics {
// this range simulates iterating over the metrics map
// as we do when encoding msgpack upon flushing.
}
}
return
}
}()
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-done:
root.Finish()
for i := 0; i < 500; i++ {
for range root.(*span).Meta {
// this range simulates iterating over the meta map
// as we do when encoding msgpack upon flushing.
}
}
return
}
}()
wg.Add(1)
go func() {
defer wg.Done()
select {
case <-done:
for i := 0; i < 50; i++ {
// to trigger the bug, the child should be created after the root was finished,
// as its being flushed
child, _ := StartSpanFromContext(ctx, "child", Tag(ext.SamplingPriority, ext.PriorityUserKeep))
child.Finish()
}
return
}
}()
// closing will attempt trigger the two goroutines at approximately the same time.
close(done)
wg.Wait()
})
}
// Test passes if no panic occurs while running.
}
func TestSpanTracePushOne(t *testing.T) {
defer setupteardown(2, 5)()
assert := assert.New(t)
_, transport, flush, stop := startTestTracer(t)
defer stop()
traceID := random.Uint64()
root := newSpan("name1", "a-service", "a-resource", traceID, traceID, 0)
trace := root.context.trace
assert.Len(trace.spans, 1)
assert.Equal(root, trace.spans[0], "the span is the one pushed before")
root.Finish()
flush(1)
traces := transport.Traces()
assert.Len(traces, 1)
trc := traces[0]
assert.Len(trc, 1, "there was a trace in the channel")
comparePayloadSpans(t, root, trc[0])
assert.Equal(0, len(trace.spans), "no more spans in the trace")
}
func TestSpanTracePushNoFinish(t *testing.T) {
defer setupteardown(2, 5)()
assert := assert.New(t)
tp := new(testLogger)
_, _, _, stop := startTestTracer(t, WithLogger(tp), WithLambdaMode(true))
defer stop()
buffer := newTrace()
assert.NotNil(buffer)
assert.Len(buffer.spans, 0)
traceID := random.Uint64()
root := newSpan("name1", "a-service", "a-resource", traceID, traceID, 0)
root.context.trace = buffer
buffer.push(root)
assert.Len(buffer.spans, 1, "there is one span in the buffer")
assert.Equal(root, buffer.spans[0], "the span is the one pushed before")
<-time.After(time.Second / 10)
log.Flush()
assert.Len(removeAppSec(tp.Lines()), 0)
t.Logf("expected timeout, nothing should show up in buffer as the trace is not finished")
}
func TestSpanTracePushSeveral(t *testing.T) {
defer setupteardown(2, 5)()
assert := assert.New(t)
_, transport, flush, stop := startTestTracer(t)
defer stop()
buffer := newTrace()
assert.NotNil(buffer)
assert.Len(buffer.spans, 0)
traceID := random.Uint64()
root := newSpan("name1", "a-service", "a-resource", traceID, traceID, 0)
span2 := newSpan("name2", "a-service", "a-resource", random.Uint64(), traceID, root.SpanID)
span3 := newSpan("name3", "a-service", "a-resource", random.Uint64(), traceID, root.SpanID)
span3a := newSpan("name3", "a-service", "a-resource", random.Uint64(), traceID, span3.SpanID)
trace := []*span{root, span2, span3, span3a}
for i, span := range trace {
span.context.trace = buffer
buffer.push(span)
assert.Len(buffer.spans, i+1, "there is one more span in the buffer")
assert.Equal(span, buffer.spans[i], "the span is the one pushed before")
}
for _, span := range trace {
span.Finish()
}
flush(1)
traces := transport.Traces()
assert.Len(traces, 1)
trace = traces[0]
assert.Len(trace, 4, "there was one trace with the right number of spans in the channel")
for _, span := range trace {
assert.Contains(trace, span, "the trace contains the spans")
}
}
// TestSpanFinishPriority asserts that the root span will have the sampling
// priority metric set by inheriting it from a child.
func TestSpanFinishPriority(t *testing.T) {
assert := assert.New(t)
tracer, transport, flush, stop := startTestTracer(t)
defer stop()
root := tracer.StartSpan(
"root",
Tag(ext.SamplingPriority, 1),
)
child := tracer.StartSpan(
"child",
ChildOf(root.Context()),
Tag(ext.SamplingPriority, 2),
)
child.Finish()
root.Finish()
flush(1)
traces := transport.Traces()
assert.Len(traces, 1)
trace := traces[0]
assert.Len(trace, 2)
for _, span := range trace {
if span.Name == "root" {
// root should have inherited child's sampling priority
assert.Equal(span.Metrics[keySamplingPriority], 2.)
return
}
}
assert.Fail("span not found")
}
func TestNewSpanContext(t *testing.T) {
t.Run("basic", func(t *testing.T) {
span := &span{
TraceID: 1,
SpanID: 2,
ParentID: 3,
}
ctx := newSpanContext(span, nil)
assert := assert.New(t)
assert.Equal(ctx.traceID, span.TraceID)
assert.Equal(ctx.spanID, span.SpanID)
assert.NotNil(ctx.trace)
assert.Nil(ctx.trace.priority)
assert.Equal(ctx.trace.root, span)
assert.Contains(ctx.trace.spans, span)
})
t.Run("priority", func(t *testing.T) {
span := &span{
TraceID: 1,
SpanID: 2,
ParentID: 3,
Metrics: map[string]float64{keySamplingPriority: 1},
}
ctx := newSpanContext(span, nil)
assert := assert.New(t)
assert.Equal(ctx.traceID, span.TraceID)
assert.Equal(ctx.spanID, span.SpanID)
assert.Equal(ctx.TraceID(), span.TraceID)
assert.Equal(ctx.SpanID(), span.SpanID)
assert.Equal(*ctx.trace.priority, 1.)
assert.Equal(ctx.trace.root, span)
assert.Contains(ctx.trace.spans, span)
})
t.Run("root", func(t *testing.T) {
_, _, _, stop := startTestTracer(t)
defer stop()
assert := assert.New(t)
ctx, err := NewPropagator(nil).Extract(TextMapCarrier(map[string]string{
DefaultTraceIDHeader: "1",
DefaultParentIDHeader: "2",
DefaultPriorityHeader: "3",
}))
assert.Nil(err)
sctx, ok := ctx.(*spanContext)
assert.True(ok)
span := StartSpan("some-span", ChildOf(ctx))
assert.EqualValues(sctx.traceID, 1)
assert.EqualValues(sctx.spanID, 2)
assert.EqualValues(*sctx.trace.priority, 3)
assert.Equal(sctx.trace.root, span)
})
}
func TestSpanContextParent(t *testing.T) {
s := &span{
TraceID: 1,
SpanID: 2,
ParentID: 3,
}
for name, parentCtx := range map[string]*spanContext{
"basic": &spanContext{
baggage: map[string]string{"A": "A", "B": "B"},
hasBaggage: 1,
trace: newTrace(),
},
"nil-trace": &spanContext{},
"priority": &spanContext{
baggage: map[string]string{"A": "A", "B": "B"},
hasBaggage: 1,
trace: &trace{
spans: []*span{newBasicSpan("abc")},
priority: func() *float64 { v := new(float64); *v = 2; return v }(),
},
},
"sampling_decision": &spanContext{
baggage: map[string]string{"A": "A", "B": "B"},
hasBaggage: 1,
trace: &trace{
spans: []*span{newBasicSpan("abc")},
samplingDecision: decisionKeep,
},
},
"origin": &spanContext{
trace: &trace{spans: []*span{newBasicSpan("abc")}},
origin: "synthetics",
},
} {
t.Run(name, func(t *testing.T) {
ctx := newSpanContext(s, parentCtx)
assert := assert.New(t)
assert.Equal(ctx.traceID, s.TraceID)
assert.Equal(ctx.spanID, s.SpanID)
if parentCtx.trace != nil {
assert.Equal(len(ctx.trace.spans), len(parentCtx.trace.spans))
}
assert.NotNil(ctx.trace)
assert.Contains(ctx.trace.spans, s)
if parentCtx.trace != nil {
assert.Equal(ctx.trace.priority, parentCtx.trace.priority)
assert.Equal(ctx.trace.samplingDecision, parentCtx.trace.samplingDecision)
}
assert.Equal(parentCtx.baggage, ctx.baggage)
assert.Equal(parentCtx.origin, ctx.origin)
})
}
}
func TestSpanContextPushFull(t *testing.T) {
defer func(old int) { traceMaxSize = old }(traceMaxSize)
traceMaxSize = 2
tp := new(testLogger)
_, _, _, stop := startTestTracer(t, WithLogger(tp), WithLambdaMode(true))
defer stop()
span1 := newBasicSpan("span1")
span2 := newBasicSpan("span2")
span3 := newBasicSpan("span3")
buffer := newTrace()
assert := assert.New(t)
buffer.push(span1)
log.Flush()
assert.Len(removeAppSec(tp.Lines()), 0)
buffer.push(span2)
log.Flush()
assert.Len(removeAppSec(tp.Lines()), 0)
buffer.push(span3)
log.Flush()
assert.Contains(removeAppSec(tp.Lines())[0], "ERROR: trace buffer full (2)")
}
func TestSpanContextBaggage(t *testing.T) {
assert := assert.New(t)
var ctx spanContext
ctx.setBaggageItem("key", "value")
assert.Equal("value", ctx.baggage["key"])
}
func TestSpanContextIterator(t *testing.T) {
assert := assert.New(t)
got := make(map[string]string)
ctx := spanContext{baggage: map[string]string{"key": "value"}, hasBaggage: 1}
ctx.ForeachBaggageItem(func(k, v string) bool {
got[k] = v
return true
})
assert.Len(got, 1)
assert.Equal("value", got["key"])
}
func TestSpanContextIteratorBreak(t *testing.T) {
got := make(map[string]string)
ctx := spanContext{baggage: map[string]string{"key": "value"}}
ctx.ForeachBaggageItem(func(k, v string) bool {
return false
})
assert.Len(t, got, 0)
}
func TestBuildNewUpstreamServices(t *testing.T) {
var testCases = []struct {
service string
priority int
sampler samplernames.SamplerName
rate float64
expected string
}{
{"service-account", 1, samplernames.AgentRate, 0.99, "c2VydmljZS1hY2NvdW50|1|1|0.9900"},
{"service-storage", 2, samplernames.Manual, math.NaN(), "c2VydmljZS1zdG9yYWdl|2|4|"},
{"service-video", 1, samplernames.RuleRate, 1, "c2VydmljZS12aWRlbw|1|3|1.0000"},
}
for _, tt := range testCases {
assert.Equal(t, tt.expected, compactUpstreamServices(tt.service, tt.priority, tt.sampler, tt.rate))
}
}
// testLogger implements a mock Printer.
type testLogger struct {
mu sync.RWMutex
lines []string
}
// Print implements log.Printer.
func (tp *testLogger) Log(msg string) {
tp.mu.Lock()
defer tp.mu.Unlock()
tp.lines = append(tp.lines, msg)
}
// Lines returns the lines that were printed using this printer.
func (tp *testLogger) Lines() []string {
tp.mu.RLock()
defer tp.mu.RUnlock()
return tp.lines
}
// Reset resets the printer's internal buffer.
func (tp *testLogger) Reset() {
tp.mu.Lock()
defer tp.mu.Unlock()
tp.lines = tp.lines[:0]
}
func BenchmarkBaggageItemPresent(b *testing.B) {
ctx := spanContext{baggage: map[string]string{"key": "value"}, hasBaggage: 1}
for n := 0; n < b.N; n++ {
ctx.ForeachBaggageItem(func(k, v string) bool {
return true
})
}
}
func BenchmarkBaggageItemEmpty(b *testing.B) {
ctx := spanContext{}
for n := 0; n < b.N; n++ {
ctx.ForeachBaggageItem(func(k, v string) bool {
return true
})
}
}
// Remove the appsec logs from the given log lines
func removeAppSec(lines []string) []string {
res := make([]string, 0, len(lines))
for _, line := range lines {
if strings.Contains(line, "appsec:") {
continue
}
res = append(res, line)
}
return res
}