forked from jaegertracing/jaeger-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
propagation_test.go
341 lines (297 loc) Β· 11.9 KB
/
propagation_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
// Copyright (c) 2017 Uber Technologies, Inc.
//
// 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 jaeger
import (
"bytes"
"encoding/base64"
"net/http"
"strings"
"testing"
"time"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/uber/jaeger-lib/metrics/metricstest"
)
func initMetrics() (*metricstest.Factory, *Metrics) {
factory := metricstest.NewFactory(0)
return factory, NewMetrics(factory, nil)
}
func TestSpanPropagator(t *testing.T) {
const op = "test"
reporter := NewInMemoryReporter()
metricsFactory, metrics := initMetrics()
tracer, closer := NewTracer("x", NewConstSampler(true), reporter, TracerOptions.Metrics(metrics), TracerOptions.ZipkinSharedRPCSpan(true))
mapc := opentracing.TextMapCarrier(make(map[string]string))
httpc := opentracing.HTTPHeadersCarrier(http.Header{})
tests := []struct {
format, carrier, formatName interface{}
}{
{SpanContextFormat, new(SpanContext), "TraceContextFormat"},
{opentracing.Binary, new(bytes.Buffer), "Binary"},
{opentracing.TextMap, mapc, "TextMap"},
{opentracing.HTTPHeaders, httpc, "HTTPHeaders"},
}
sp := tracer.StartSpan(op)
sp.SetTag("x", "y") // to avoid later comparing nil vs. []
sp.SetBaggageItem("foo", "bar")
for _, test := range tests {
// starting normal child to extract its serialized context
child := tracer.StartSpan(op, opentracing.ChildOf(sp.Context()))
err := tracer.Inject(child.Context(), test.format, test.carrier)
assert.NoError(t, err)
// Note: we're not finishing the above span
childCtx, err := tracer.Extract(test.format, test.carrier)
assert.NoError(t, err)
child = tracer.StartSpan(test.formatName.(string), ext.RPCServerOption(childCtx))
child.SetTag("x", "y") // to avoid later comparing nil vs. []
child.Finish()
}
sp.Finish()
otSpans := reporter.GetSpans()
require.Equal(t, len(tests)+1, len(otSpans), "unexpected number of spans reporter")
spans := make([]*Span, len(otSpans))
for i, s := range otSpans {
spans[i] = s.(*Span)
}
closer.Close()
// The last span is the original one.
exp, spans := spans[len(spans)-1], spans[:len(spans)-1]
exp.duration = time.Duration(123)
exp.startTime = time.Time{}.Add(1)
require.Len(t, exp.logs, 1) // The parent span should have baggage logs
fields := exp.logs[0].Fields
require.Len(t, fields, 3)
require.Equal(t, "event", fields[0].Key())
require.Equal(t, "baggage", fields[0].Value().(string))
require.Equal(t, "key", fields[1].Key())
require.Equal(t, "foo", fields[1].Value().(string))
require.Equal(t, "value", fields[2].Key())
require.Equal(t, "bar", fields[2].Value().(string))
if exp.context.ParentID() != 0 {
t.Fatalf("Root span's ParentID %d is not 0", exp.context.ParentID())
}
expTags := exp.tags[2:] // skip two sampler.xxx tags
for i, sp := range spans {
formatName := sp.operationName
if a, e := sp.context.ParentID(), exp.context.SpanID(); a != e {
t.Fatalf("%d: ParentID %d does not match expectation %d", i, a, e)
} else {
// Prepare for comparison.
sp.duration, sp.startTime = exp.duration, exp.startTime
}
assert.Equal(t, exp.context.traceID, sp.context.traceID, formatName)
assert.Equal(t, exp.context.Flags(), sp.context.Flags(), formatName)
assert.Equal(t, exp.context.baggage, sp.context.baggage, formatName)
assert.Equal(t, "span.kind", sp.tags[0].key)
assert.Equal(t, expTags, sp.tags[1:] /*skip span.kind tag*/, formatName)
assert.Empty(t, sp.logs, formatName)
// Override collections to avoid tripping comparison on different pointers
sp.context = exp.context
sp.tags = exp.tags
sp.logs = exp.logs
sp.operationName = op
sp.references = exp.references
// Compare the rest of the fields
assert.Equal(t, exp, sp, formatName)
}
metricsFactory.AssertCounterMetrics(t, []metricstest.ExpectedMetric{
{Name: "jaeger.tracer.started_spans", Tags: map[string]string{"sampled": "y"}, Value: 1 + 2*len(tests)},
{Name: "jaeger.tracer.finished_spans", Tags: map[string]string{"sampled": "y"}, Value: 1 + len(tests)},
{Name: "jaeger.tracer.traces", Tags: map[string]string{"state": "started", "sampled": "y"}, Value: 1},
{Name: "jaeger.tracer.traces", Tags: map[string]string{"state": "joined", "sampled": "y"}, Value: len(tests)},
}...)
}
func TestBinaryCorruption(t *testing.T) {
const op = "test"
reporter := NewInMemoryReporter()
tracer, closer := NewTracer("x", NewConstSampler(true), reporter)
sp := tracer.StartSpan(op)
carrier := new(bytes.Buffer)
err := tracer.Inject(sp.Context(), opentracing.Binary, carrier)
assert.NoError(t, err)
// suppose we encode the data then forget to decode it
data := base64.StdEncoding.EncodeToString(carrier.Bytes())
_, err = tracer.Extract(opentracing.Binary, strings.NewReader(data))
if assert.Error(t, err) {
assert.Equal(t, opentracing.ErrSpanContextCorrupted, err)
}
sp.Finish()
closer.Close()
}
func TestSpanIntegrityAfterSerialize(t *testing.T) {
serializedString := "f6c385a2c57ed8d7:00b04a90b7723bdc:76c385a2c57ed8d7:1"
context, err := ContextFromString(serializedString)
require.NoError(t, err)
require.True(t, context.traceID.Low > (uint64(1)<<63))
require.True(t, int64(context.traceID.Low) < 0)
newSerializedString := context.String()
require.Equal(t, serializedString, newSerializedString)
}
func TestDecodingError(t *testing.T) {
reporter := NewInMemoryReporter()
metricsFactory, metrics := initMetrics()
tracer, closer := NewTracer("x", NewConstSampler(true), reporter, TracerOptions.Metrics(metrics))
defer closer.Close()
badHeader := "x.x.x.x"
httpHeader := http.Header{}
httpHeader.Add(TraceContextHeaderName, badHeader)
tmc := opentracing.HTTPHeadersCarrier(httpHeader)
_, err := tracer.Extract(opentracing.HTTPHeaders, tmc)
assert.Error(t, err)
metricsFactory.AssertCounterMetrics(t, metricstest.ExpectedMetric{Name: "jaeger.tracer.span_context_decoding_errors", Value: 1})
}
func TestBaggagePropagationHTTP(t *testing.T) {
tracer, closer := NewTracer("DOOP", NewConstSampler(true), NewNullReporter())
defer closer.Close()
sp1 := tracer.StartSpan("s1").(*Span)
sp1.SetBaggageItem("Some_Key", "12345")
assert.Equal(t, "12345", sp1.BaggageItem("Some_Key"), "baggage: %+v", sp1.context.baggage)
assert.Empty(t, sp1.BaggageItem("some-KEY"), "baggage: %+v", sp1.context.baggage)
sp1.SetBaggageItem("Some_Key", "98:765")
assert.Equal(t, "98:765", sp1.BaggageItem("Some_Key"), "baggage: %+v", sp1.context.baggage)
assert.Empty(t, sp1.BaggageItem("some-KEY"), "baggage: %+v", sp1.context.baggage)
h := http.Header{}
h.Add("header1", "value1") // make sure this does not get unmarshalled as baggage
err := tracer.Inject(sp1.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(h))
require.NoError(t, err)
// check that colon : was encoded as %3A
assert.Equal(t, "98%3A765", h.Get(TraceBaggageHeaderPrefix+"Some_Key"), "headers: %+v", h)
sp2, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(h))
require.NoError(t, err)
assert.Equal(t, map[string]string{"some_key": "98:765"}, sp2.(SpanContext).baggage)
}
// TestOnlyBaggageHeaders verifies that if only baggage headers (in both default formats)
// are present in the request without a trace ID header, then the baggage is still captured
// into the new span.
func TestOnlyBaggageHeaders(t *testing.T) {
tracer, closer := NewTracer("DOOP", NewConstSampler(true), NewNullReporter())
defer closer.Close()
// both formats of baggage headers should be parsed and
h := http.Header{
"uberctx-key1": []string{"val1"},
"jaeger-baggage": []string{"key2=val2"},
}
spc, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(h))
require.NoError(t, err)
require.Equal(t, map[string]string{"key1": "val1", "key2": "val2"}, spc.(SpanContext).baggage)
sp := tracer.StartSpan("baggage", opentracing.ChildOf(spc))
assert.Equal(t, "val1", sp.BaggageItem("key1"))
assert.Equal(t, "val2", sp.BaggageItem("key2"))
assert.Len(t, sp.(*Span).References(), 0, "must be a root span")
}
func TestJaegerBaggageHeader(t *testing.T) {
var testcases = []struct {
refFunc func(opentracing.SpanContext) opentracing.SpanReference
}{
{
refFunc: opentracing.ChildOf,
},
{
refFunc: opentracing.FollowsFrom,
},
}
for _, testcase := range testcases {
t.Run("", func(t *testing.T) {
metricsFactory, metrics := initMetrics()
tracer, closer := NewTracer("DOOP",
NewConstSampler(true),
NewNullReporter(),
TracerOptions.Metrics(metrics),
)
defer closer.Close()
h := http.Header{}
h.Add(JaegerBaggageHeader, "key1=value1, key 2=value two")
ctx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(h))
require.NoError(t, err)
sp := tracer.StartSpan("root", testcase.refFunc(ctx)).(*Span)
assert.Equal(t, "value1", sp.BaggageItem("key1"))
assert.Equal(t, "value two", sp.BaggageItem("key 2"))
// ensure that traces.started counter is incremented, not traces.joined
metricsFactory.AssertCounterMetrics(t,
metricstest.ExpectedMetric{
Name: "jaeger.tracer.traces", Tags: map[string]string{"state": "started", "sampled": "y"}, Value: 1,
},
)
})
}
}
func TestParseCommaSeperatedMap(t *testing.T) {
var testcases = []struct {
in string
out map[string]string
}{
{"hobbit=Bilbo Baggins", map[string]string{"hobbit": "Bilbo Baggins"}},
{"hobbit=Bilbo Baggins, dwarf= Thrain", map[string]string{"hobbit": "Bilbo Baggins", "dwarf": " Thrain"}},
{"kevin spacey=actor", map[string]string{"kevin spacey": "actor"}},
{"kevin%20spacey=se7en%3Aactor", map[string]string{"kevin spacey": "se7en:actor"}},
{"key1=, key2=", map[string]string{"key1": "", "key2": ""}},
{"malformed", map[string]string{}},
{"malformed, string", map[string]string{}},
{"another malformed string", map[string]string{}},
{"key2=value2, key3 = value3 ", map[string]string{"key2": "value2", "key3": " value3"}},
}
for _, testcase := range testcases {
m := (&TextMapPropagator{
headerKeys: getDefaultHeadersConfig(),
}).parseCommaSeparatedMap(testcase.in)
assert.Equal(t, testcase.out, m)
}
}
func TestDebugCorrelationID(t *testing.T) {
var testcases = []struct {
refType string
refFunc func(opentracing.SpanContext) opentracing.SpanReference
}{
{
refFunc: opentracing.ChildOf,
},
{
refFunc: opentracing.FollowsFrom,
},
}
for _, testcase := range testcases {
t.Run("", func(t *testing.T) {
metricsFactory, metrics := initMetrics()
tracer, closer := NewTracer("DOOP",
NewConstSampler(true),
NewNullReporter(),
TracerOptions.Metrics(metrics),
)
defer closer.Close()
h := http.Header{}
val := "value1"
h.Add(JaegerDebugHeader, val)
ctx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(h))
require.NoError(t, err)
assert.EqualValues(t, 0, ctx.(SpanContext).parentID)
assert.EqualValues(t, val, ctx.(SpanContext).debugID)
sp := tracer.StartSpan("root", testcase.refFunc(ctx)).(*Span)
assert.EqualValues(t, 0, sp.context.parentID)
assert.True(t, sp.context.traceID.IsValid())
assert.True(t, sp.context.IsSampled())
assert.True(t, sp.context.IsDebug())
tag := findDomainTag(sp, JaegerDebugHeader)
assert.NotNil(t, tag)
assert.Equal(t, val, tag.value)
// ensure that traces.started counter is incremented, not traces.joined
metricsFactory.AssertCounterMetrics(t,
metricstest.ExpectedMetric{
Name: "jaeger.tracer.traces", Tags: map[string]string{"state": "started", "sampled": "y"}, Value: 1,
},
)
})
}
}