Debian Codegraph @

sdk/trace/provider_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package trace
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "math/rand/v2"
11 "testing"
12
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15
16 "go.opentelemetry.io/otel"
17 "go.opentelemetry.io/otel/attribute"
18 "go.opentelemetry.io/otel/metric"
19 "go.opentelemetry.io/otel/trace"
20 )
21
22 const (
23 envTracesSampler = "OTEL_TRACES_SAMPLER"
24 envTracesSamplerArg = "OTEL_TRACES_SAMPLER_ARG"
25 )
26
27 type basicSpanProcessor struct {
28 flushed bool
29 closed bool
30 injectShutdownError error
31 injectExportError error
32 }
33
34 func (t *basicSpanProcessor) Shutdown(context.Context) error {
35 t.closed = true
36 return t.injectShutdownError
37 }
38
39 func (*basicSpanProcessor) OnStart(context.Context, ReadWriteSpan) {}
40 func (*basicSpanProcessor) OnEnd(ReadOnlySpan) {}
41 func (t *basicSpanProcessor) ForceFlush(context.Context) error {
42 t.flushed = true
43 return t.injectExportError
44 }
45
46 type shutdownSpanProcessor struct {
47 shutdown func(context.Context) error
48 }
49
50 func (t *shutdownSpanProcessor) Shutdown(ctx context.Context) error {
51 return t.shutdown(ctx)
52 }
53
54 func (*shutdownSpanProcessor) OnStart(context.Context, ReadWriteSpan) {}
55 func (*shutdownSpanProcessor) OnEnd(ReadOnlySpan) {}
56 func (*shutdownSpanProcessor) ForceFlush(context.Context) error {
57 return nil
58 }
59
60 func TestShutdownCallsTracerMethod(t *testing.T) {
61 stp := NewTracerProvider()
62 sp := &shutdownSpanProcessor{
63 shutdown: func(context.Context) error {
64 _ = stp.Tracer("abc") // must not deadlock
65 return nil
66 },
67 }
68 stp.RegisterSpanProcessor(sp)
69 assert.NoError(t, stp.Shutdown(t.Context()))
70 assert.True(t, stp.isShutdown.Load())
71 }
72
73 func TestForceFlushAndShutdownTraceProviderWithoutProcessor(t *testing.T) {
74 stp := NewTracerProvider()
75 assert.NoError(t, stp.ForceFlush(t.Context()))
76 assert.NoError(t, stp.Shutdown(t.Context()))
77 assert.True(t, stp.isShutdown.Load())
78 }
79
80 func TestUnregisterFirst(t *testing.T) {
81 stp := NewTracerProvider()
82 sp1 := &basicSpanProcessor{}
83 sp2 := &basicSpanProcessor{}
84 sp3 := &basicSpanProcessor{}
85 stp.RegisterSpanProcessor(sp1)
86 stp.RegisterSpanProcessor(sp2)
87 stp.RegisterSpanProcessor(sp3)
88
89 stp.UnregisterSpanProcessor(sp1)
90
91 sps := stp.getSpanProcessors()
92 require.Len(t, sps, 2)
93 assert.Same(t, sp2, sps[0].sp)
94 assert.Same(t, sp3, sps[1].sp)
95 }
96
97 func TestUnregisterMiddle(t *testing.T) {
98 stp := NewTracerProvider()
99 sp1 := &basicSpanProcessor{}
100 sp2 := &basicSpanProcessor{}
101 sp3 := &basicSpanProcessor{}
102 stp.RegisterSpanProcessor(sp1)
103 stp.RegisterSpanProcessor(sp2)
104 stp.RegisterSpanProcessor(sp3)
105
106 stp.UnregisterSpanProcessor(sp2)
107
108 sps := stp.getSpanProcessors()
109 require.Len(t, sps, 2)
110 assert.Same(t, sp1, sps[0].sp)
111 assert.Same(t, sp3, sps[1].sp)
112 }
113
114 func TestUnregisterLast(t *testing.T) {
115 stp := NewTracerProvider()
116 sp1 := &basicSpanProcessor{}
117 sp2 := &basicSpanProcessor{}
118 sp3 := &basicSpanProcessor{}
119 stp.RegisterSpanProcessor(sp1)
120 stp.RegisterSpanProcessor(sp2)
121 stp.RegisterSpanProcessor(sp3)
122
123 stp.UnregisterSpanProcessor(sp3)
124
125 sps := stp.getSpanProcessors()
126 require.Len(t, sps, 2)
127 assert.Same(t, sp1, sps[0].sp)
128 assert.Same(t, sp2, sps[1].sp)
129 }
130
131 func TestShutdownTraceProvider(t *testing.T) {
132 stp := NewTracerProvider()
133 sp := &basicSpanProcessor{}
134 stp.RegisterSpanProcessor(sp)
135
136 assert.NoError(t, stp.ForceFlush(t.Context()))
137 assert.True(t, sp.flushed, "error ForceFlush basicSpanProcessor")
138 assert.NoError(t, stp.Shutdown(t.Context()))
139 assert.True(t, stp.isShutdown.Load())
140 assert.True(t, sp.closed, "error Shutdown basicSpanProcessor")
141 }
142
143 func TestFailedProcessorShutdown(t *testing.T) {
144 stp := NewTracerProvider()
145 spErr := errors.New("basic span processor shutdown failure")
146 sp := &basicSpanProcessor{
147 injectShutdownError: spErr,
148 }
149 stp.RegisterSpanProcessor(sp)
150
151 err := stp.Shutdown(t.Context())
152 assert.Error(t, err)
153 assert.ErrorIs(t, err, spErr)
154 assert.True(t, stp.isShutdown.Load())
155 }
156
157 func TestFailedProcessorsShutdown(t *testing.T) {
158 stp := NewTracerProvider()
159 spErr1 := errors.New("basic span processor shutdown failure1")
160 spErr2 := errors.New("basic span processor shutdown failure2")
161 sp1 := &basicSpanProcessor{
162 injectShutdownError: spErr1,
163 }
164 sp2 := &basicSpanProcessor{
165 injectShutdownError: spErr2,
166 }
167 stp.RegisterSpanProcessor(sp1)
168 stp.RegisterSpanProcessor(sp2)
169
170 err := stp.Shutdown(t.Context())
171 assert.Error(t, err)
172 assert.ErrorIs(t, err, spErr1)
173 assert.ErrorIs(t, err, spErr2)
174 assert.True(t, sp1.closed)
175 assert.True(t, sp2.closed)
176 assert.True(t, stp.isShutdown.Load())
177 }
178
179 func TestFailedProcessorShutdownInUnregister(t *testing.T) {
180 handler.Reset()
181 stp := NewTracerProvider()
182 spErr := errors.New("basic span processor shutdown failure")
183 sp := &basicSpanProcessor{
184 injectShutdownError: spErr,
185 }
186 stp.RegisterSpanProcessor(sp)
187 stp.UnregisterSpanProcessor(sp)
188
189 assert.Contains(t, handler.errs, spErr)
190
191 err := stp.Shutdown(t.Context())
192 assert.NoError(t, err)
193 assert.True(t, stp.isShutdown.Load())
194 }
195
196 func TestSchemaURL(t *testing.T) {
197 stp := NewTracerProvider()
198 schemaURL := "https://opentelemetry.io/schemas/1.21.0"
199 tracerIface := stp.Tracer("tracername", trace.WithSchemaURL(schemaURL))
200
201 // Verify that the SchemaURL of the constructed Tracer is correctly populated.
202 tracerStruct := tracerIface.(*tracer)
203 assert.Equal(t, schemaURL, tracerStruct.instrumentationScope.SchemaURL)
204 }
205
206 func TestRegisterAfterShutdownWithoutProcessors(t *testing.T) {
207 stp := NewTracerProvider()
208 err := stp.Shutdown(t.Context())
209 assert.NoError(t, err)
210 assert.True(t, stp.isShutdown.Load())
211
212 sp := &basicSpanProcessor{}
213 stp.RegisterSpanProcessor(sp) // no-op
214 assert.Empty(t, stp.getSpanProcessors())
215 }
216
217 func TestRegisterAfterShutdownWithProcessors(t *testing.T) {
218 stp := NewTracerProvider()
219 sp1 := &basicSpanProcessor{}
220
221 stp.RegisterSpanProcessor(sp1)
222 err := stp.Shutdown(t.Context())
223 assert.NoError(t, err)
224 assert.True(t, stp.isShutdown.Load())
225 assert.Empty(t, stp.getSpanProcessors())
226
227 sp2 := &basicSpanProcessor{}
228 stp.RegisterSpanProcessor(sp2) // no-op
229 assert.Empty(t, stp.getSpanProcessors())
230 }
231
232 func TestTracerProviderForceFlush(t *testing.T) {
233 t.Run("AfterShutdown", func(t *testing.T) {
234 stp := NewTracerProvider()
235 sp1 := &basicSpanProcessor{}
236 stp.RegisterSpanProcessor(sp1)
237 ctx := t.Context()
238
239 require.NoError(t, stp.ForceFlush(ctx))
240 require.True(t, sp1.flushed, "SpanProcessor ForceFlush not called")
241
242 sp1.flushed = false
243 require.NoError(t, stp.Shutdown(ctx))
244
245 require.NoError(t, stp.ForceFlush(ctx))
246 assert.False(t, sp1.flushed, "SpanProcessor ForceFlush called after Shutdown")
247 })
248
249 t.Run("Multi", func(t *testing.T) {
250 stp := NewTracerProvider()
251 sp1 := &basicSpanProcessor{}
252 sp2 := &basicSpanProcessor{}
253 stp.RegisterSpanProcessor(sp1)
254 stp.RegisterSpanProcessor(sp2)
255 ctx := t.Context()
256
257 require.NoError(t, stp.ForceFlush(ctx))
258 require.True(t, sp1.flushed, "SpanProcessor ForceFlush not called")
259 require.True(t, sp2.flushed, "SpanProcessor ForceFlush not called")
260 })
261
262 t.Run("Error", func(t *testing.T) {
263 stp := NewTracerProvider()
264 sp1 := &basicSpanProcessor{injectExportError: assert.AnError}
265 sp2 := &basicSpanProcessor{}
266 stp.RegisterSpanProcessor(sp1)
267 stp.RegisterSpanProcessor(sp2)
268 ctx := t.Context()
269
270 assert.ErrorIs(t, stp.ForceFlush(ctx), assert.AnError, "span processor error not returned")
271 require.True(t, sp1.flushed, "SpanProcessor ForceFlush not called")
272 require.True(t, sp2.flushed, "SpanProcessor ForceFlush not called")
273 })
274
275 t.Run("WithCancel", func(t *testing.T) {
276 stp := NewTracerProvider()
277 sp1 := &basicSpanProcessor{}
278 stp.RegisterSpanProcessor(sp1)
279 ctx, cancel := context.WithCancel(t.Context())
280 cancel()
281 assert.ErrorIs(t, stp.ForceFlush(ctx), context.Canceled)
282 })
283 }
284
285 func TestTracerProviderSamplerConfigFromEnv(t *testing.T) {
286 type testCase struct {
287 sampler string
288 samplerArg string
289 argOptional bool
290 description string
291 errorType error
292 invalidArgErrorType any
293 }
294
295 randFloat := rand.Float64()
296
297 tests := []testCase{
298 {
299 sampler: "invalid-sampler",
300 argOptional: true,
301 description: ParentBased(AlwaysSample()).Description(),
302 errorType: errUnsupportedSampler("invalid-sampler"),
303 invalidArgErrorType: func() *errUnsupportedSampler { e := errUnsupportedSampler("invalid-sampler"); return &e }(),
304 },
305 {
306 sampler: "always_on",
307 argOptional: true,
308 description: AlwaysSample().Description(),
309 },
310 {
311 sampler: "always_off",
312 argOptional: true,
313 description: NeverSample().Description(),
314 },
315 {
316 sampler: "traceidratio",
317 samplerArg: fmt.Sprintf("%g", randFloat),
318 description: TraceIDRatioBased(randFloat).Description(),
319 },
320 {
321 sampler: "traceidratio",
322 samplerArg: fmt.Sprintf("%g", -randFloat),
323 description: TraceIDRatioBased(1.0).Description(),
324 errorType: errNegativeTraceIDRatio,
325 },
326 {
327 sampler: "traceidratio",
328 samplerArg: fmt.Sprintf("%g", 1+randFloat),
329 description: TraceIDRatioBased(1.0).Description(),
330 errorType: errGreaterThanOneTraceIDRatio,
331 },
332 {
333 sampler: "traceidratio",
334 argOptional: true,
335 description: TraceIDRatioBased(1.0).Description(),
336 invalidArgErrorType: new(samplerArgParseError),
337 },
338 {
339 sampler: "parentbased_always_on",
340 argOptional: true,
341 description: ParentBased(AlwaysSample()).Description(),
342 },
343 {
344 sampler: "parentbased_always_off",
345 argOptional: true,
346 description: ParentBased(NeverSample()).Description(),
347 },
348 {
349 sampler: "parentbased_traceidratio",
350 samplerArg: fmt.Sprintf("%g", randFloat),
351 description: ParentBased(TraceIDRatioBased(randFloat)).Description(),
352 },
353 {
354 sampler: "parentbased_traceidratio",
355 samplerArg: fmt.Sprintf("%g", -randFloat),
356 description: ParentBased(TraceIDRatioBased(1.0)).Description(),
357 errorType: errNegativeTraceIDRatio,
358 },
359 {
360 sampler: "parentbased_traceidratio",
361 samplerArg: fmt.Sprintf("%g", 1+randFloat),
362 description: ParentBased(TraceIDRatioBased(1.0)).Description(),
363 errorType: errGreaterThanOneTraceIDRatio,
364 },
365 {
366 sampler: "parentbased_traceidratio",
367 argOptional: true,
368 description: ParentBased(TraceIDRatioBased(1.0)).Description(),
369 invalidArgErrorType: new(samplerArgParseError),
370 },
371 }
372
373 handler.Reset()
374
375 for _, test := range tests {
376 t.Run(test.sampler, func(t *testing.T) {
377 t.Setenv(envTracesSampler, test.sampler)
378
379 if test.samplerArg != "" {
380 t.Setenv(envTracesSamplerArg, test.samplerArg)
381 }
382
383 stp := NewTracerProvider(WithSyncer(NewTestExporter()))
384 assert.Equal(t, test.description, stp.sampler.Description())
385 if test.errorType != nil {
386 testStoredError(t, test.errorType)
387 } else {
388 assert.Empty(t, handler.errs)
389 }
390
391 if test.argOptional {
392 t.Run("invalid sampler arg", func(t *testing.T) {
393 t.Setenv(envTracesSampler, test.sampler)
394 t.Setenv(envTracesSamplerArg, "invalid-ignored-string")
395
396 stp := NewTracerProvider(WithSyncer(NewTestExporter()))
397 t.Cleanup(func() {
398 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
399 require.NoError(t, stp.Shutdown(context.Background()))
400 })
401 assert.Equal(t, test.description, stp.sampler.Description())
402
403 if test.invalidArgErrorType != nil {
404 testStoredError(t, test.invalidArgErrorType)
405 } else {
406 assert.Empty(t, handler.errs)
407 }
408 })
409 }
410 })
411 }
412 }
413
414 func testStoredError(t *testing.T, target any) {
415 t.Helper()
416
417 if assert.Len(t, handler.errs, 1) && assert.Error(t, handler.errs[0]) {
418 err := handler.errs[0]
419
420 require.Implements(t, (*error)(nil), target)
421 require.Error(t, target.(error))
422
423 defer handler.Reset()
424 if errors.Is(err, target.(error)) {
425 return
426 }
427
428 assert.ErrorAs(t, err, target)
429 }
430 }
431
432 func TestTracerProviderReturnsSameTracer(t *testing.T) {
433 p := NewTracerProvider()
434
435 t0, t1, t2 := p.Tracer(
436 "t0",
437 ), p.Tracer(
438 "t1",
439 ), p.Tracer(
440 "t0",
441 trace.WithInstrumentationAttributes(attribute.String("foo", "bar")),
442 )
443 assert.NotSame(t, t0, t1)
444 assert.NotSame(t, t0, t2)
445 assert.NotSame(t, t1, t2)
446
447 t3, t4, t5 := p.Tracer(
448 "t0",
449 ), p.Tracer(
450 "t1",
451 ), p.Tracer(
452 "t0",
453 trace.WithInstrumentationAttributes(attribute.String("foo", "bar")),
454 )
455 assert.Same(t, t0, t3)
456 assert.Same(t, t1, t4)
457 assert.Same(t, t2, t5)
458 }
459
460 func TestTracerProviderObservability(t *testing.T) {
461 handler.Reset()
462 p := NewTracerProvider()
463
464 // Enable observability
465 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
466
467 tr := p.Tracer("test-tracer")
468 require.IsType(t, &tracer{}, tr)
469
470 tStruct := tr.(*tracer)
471 assert.True(t, tStruct.inst.Enabled(), "observability should be enabled")
472
473 // Verify errors are passed to the otel handler
474 handlerErrs := handler.errs
475 assert.Empty(t, handlerErrs, "No errors should occur during instrument creation")
476 }
477
478 func TestTracerProviderObservabilityErrorsHandled(t *testing.T) {
479 handler.Reset()
480
481 orig := otel.GetMeterProvider()
482 t.Cleanup(func() { otel.SetMeterProvider(orig) })
483 otel.SetMeterProvider(&errMeterProvider{err: assert.AnError})
484
485 p := NewTracerProvider()
486
487 // Enable observability
488 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
489
490 // Create a tracer to trigger instrument creation.
491 tr := p.Tracer("test-tracer")
492 _ = tr
493
494 require.Len(t, handler.errs, 1)
495 assert.ErrorIs(t, handler.errs[0], assert.AnError)
496 }
497
498 type errMeterProvider struct {
499 metric.MeterProvider
500
501 err error
502 }
503
504 func (mp *errMeterProvider) Meter(string, ...metric.MeterOption) metric.Meter {
505 return &errMeter{err: mp.err}
506 }
507
508 type errMeter struct {
509 metric.Meter
510
511 err error
512 }
513
514 func (m *errMeter) Int64Counter(string, ...metric.Int64CounterOption) (metric.Int64Counter, error) {
515 return nil, m.err
516 }
517
518 func (m *errMeter) Int64UpDownCounter(string, ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error) {
519 return nil, m.err
520 }