Debian Codegraph @

otelconf/trace_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelconf
5
6 import (
7 "bytes"
8 "context"
9 "crypto/tls"
10 "crypto/x509"
11 "errors"
12 "net"
13 "net/http"
14 "net/http/httptest"
15 "os"
16 "path/filepath"
17 "reflect"
18 "runtime"
19 "testing"
20 "time"
21
22 "github.com/stretchr/testify/assert"
23 "github.com/stretchr/testify/require"
24 "go.opentelemetry.io/otel/attribute"
25 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc"
26 "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
27 "go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
28 "go.opentelemetry.io/otel/sdk/resource"
29 sdktrace "go.opentelemetry.io/otel/sdk/trace"
30 "go.opentelemetry.io/otel/sdk/trace/tracetest"
31 "go.opentelemetry.io/otel/trace"
32 "go.opentelemetry.io/otel/trace/noop"
33 v1 "go.opentelemetry.io/proto/otlp/collector/trace/v1"
34 "google.golang.org/grpc"
35 "google.golang.org/grpc/credentials"
36 )
37
38 func TestTracerProvider(t *testing.T) {
39 tests := []struct {
40 name string
41 cfg configOptions
42 wantProvider trace.TracerProvider
43 wantErr error
44 }{
45 {
46 name: "no-tracer-provider-configured",
47 wantProvider: noop.NewTracerProvider(),
48 },
49 {
50 name: "error-in-config",
51 cfg: configOptions{
52 opentelemetryConfig: OpenTelemetryConfiguration{
53 TracerProvider: &TracerProvider{
54 Processors: []SpanProcessor{
55 {
56 Batch: &BatchSpanProcessor{},
57 Simple: &SimpleSpanProcessor{},
58 },
59 },
60 },
61 },
62 },
63 wantProvider: noop.NewTracerProvider(),
64 wantErr: newErrInvalid("must not specify multiple span processor type"),
65 },
66 {
67 name: "multiple-errors-in-config",
68 cfg: configOptions{
69 opentelemetryConfig: OpenTelemetryConfiguration{
70 TracerProvider: &TracerProvider{
71 Processors: []SpanProcessor{
72 {
73 Batch: &BatchSpanProcessor{},
74 Simple: &SimpleSpanProcessor{},
75 },
76 {
77 Simple: &SimpleSpanProcessor{
78 Exporter: SpanExporter{
79 Console: ConsoleExporter{},
80 OTLPHttp: &OTLPHttpExporter{},
81 },
82 },
83 },
84 },
85 },
86 },
87 },
88 wantProvider: noop.NewTracerProvider(),
89 wantErr: newErrInvalid("must not specify multiple exporters"),
90 },
91 {
92 name: "invalid-sampler-config",
93 cfg: configOptions{
94 opentelemetryConfig: OpenTelemetryConfiguration{
95 TracerProvider: &TracerProvider{
96 Processors: []SpanProcessor{
97 {
98 Simple: &SimpleSpanProcessor{
99 Exporter: SpanExporter{
100 Console: ConsoleExporter{},
101 },
102 },
103 },
104 },
105 Sampler: &Sampler{},
106 },
107 },
108 },
109 wantProvider: noop.NewTracerProvider(),
110 wantErr: errInvalidSamplerConfiguration,
111 },
112 {
113 name: "with-limits",
114 cfg: configOptions{
115 opentelemetryConfig: OpenTelemetryConfiguration{
116 TracerProvider: &TracerProvider{
117 Limits: &SpanLimits{
118 AttributeCountLimit: ptr(50),
119 AttributeValueLengthLimit: ptr(100),
120 },
121 },
122 },
123 },
124 },
125 }
126 for _, tt := range tests {
127 t.Run(tt.name, func(t *testing.T) {
128 tp, shutdown, err := tracerProvider(tt.cfg, resource.Default())
129 if tt.wantProvider != nil {
130 require.Equal(t, tt.wantProvider, tp)
131 } else {
132 require.NotNil(t, tp)
133 require.IsType(t, &sdktrace.TracerProvider{}, tp)
134 }
135 assert.ErrorIs(t, err, tt.wantErr)
136 require.NoError(t, shutdown(t.Context()))
137 })
138 }
139 }
140
141 func TestTracerProviderOptions(t *testing.T) {
142 var calls int
143 srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
144 calls++
145 }))
146 defer srv.Close()
147
148 cfg := OpenTelemetryConfiguration{
149 TracerProvider: &TracerProvider{
150 Processors: []SpanProcessor{{
151 Simple: &SimpleSpanProcessor{
152 Exporter: SpanExporter{
153 OTLPHttp: &OTLPHttpExporter{
154 Endpoint: ptr(srv.URL),
155 },
156 },
157 },
158 }},
159 },
160 }
161
162 var buf bytes.Buffer
163 stdouttraceExporter, err := stdouttrace.New(stdouttrace.WithWriter(&buf))
164 require.NoError(t, err)
165
166 res := resource.NewSchemaless(attribute.String("foo", "bar"))
167 sdk, err := NewSDK(
168 WithOpenTelemetryConfiguration(cfg),
169 WithTracerProviderOptions(sdktrace.WithSyncer(stdouttraceExporter)),
170 WithTracerProviderOptions(sdktrace.WithResource(res)),
171 )
172 require.NoError(t, err)
173 defer func() {
174 assert.NoError(t, sdk.Shutdown(t.Context()))
175 }()
176
177 // The exporter, which we passed in as an extra option to NewSDK,
178 // should be wired up to the provider in addition to the
179 // configuration-based OTLP exporter.
180 tracer := sdk.TracerProvider().Tracer("test")
181 _, span := tracer.Start(t.Context(), "span")
182 span.End()
183 assert.NotZero(t, buf)
184 assert.Equal(t, 1, calls)
185 // Options provided by WithMeterProviderOptions may be overridden
186 // by configuration, e.g. the resource is always defined via
187 // configuration.
188 assert.NotContains(t, buf.String(), "foo")
189 }
190
191 func TestSpanProcessorLimits(t *testing.T) {
192 tests := []struct {
193 name string
194 limits SpanLimits
195 wantAdditionalOpts int
196 }{
197 {
198 name: "no-limits",
199 limits: SpanLimits{},
200 wantAdditionalOpts: 0,
201 },
202 {
203 name: "attribute-count-limit-only",
204 limits: SpanLimits{
205 AttributeCountLimit: ptr(50),
206 },
207 wantAdditionalOpts: 1,
208 },
209 {
210 name: "attribute-value-length-limit-only",
211 limits: SpanLimits{
212 AttributeValueLengthLimit: ptr(100),
213 },
214 wantAdditionalOpts: 1,
215 },
216 {
217 name: "both-limits",
218 limits: SpanLimits{
219 AttributeCountLimit: ptr(50),
220 AttributeValueLengthLimit: ptr(100),
221 },
222 wantAdditionalOpts: 1,
223 },
224 }
225
226 for _, tt := range tests {
227 t.Run(tt.name, func(t *testing.T) {
228 initialOpts := []sdktrace.TracerProviderOption{}
229 result := spanProcessorLimits(initialOpts, tt.limits)
230
231 assert.Len(t, result, tt.wantAdditionalOpts, "unexpected number of options returned")
232 })
233 }
234 }
235
236 func TestSpanProcessor(t *testing.T) {
237 consoleExporter, err := stdouttrace.New(
238 stdouttrace.WithPrettyPrint(),
239 )
240 require.NoError(t, err)
241 ctx := t.Context()
242 otlpGRPCExporter, err := otlptracegrpc.New(ctx)
243 require.NoError(t, err)
244 otlpHTTPExporter, err := otlptracehttp.New(ctx)
245 require.NoError(t, err)
246 testCases := []struct {
247 name string
248 processor SpanProcessor
249 args any
250 wantErrT error
251 wantProcessor sdktrace.SpanProcessor
252 }{
253 {
254 name: "no processor",
255 wantErrT: newErrInvalid("unsupported span processor type, must be one of simple or batch"),
256 },
257 {
258 name: "multiple processor types",
259 processor: SpanProcessor{
260 Batch: &BatchSpanProcessor{
261 Exporter: SpanExporter{},
262 },
263 Simple: &SimpleSpanProcessor{},
264 },
265 wantErrT: newErrInvalid("must not specify multiple span processor type"),
266 },
267 {
268 name: "batch processor invalid exporter",
269 processor: SpanProcessor{
270 Batch: &BatchSpanProcessor{
271 Exporter: SpanExporter{},
272 },
273 },
274 wantErrT: newErrInvalid("no valid span exporter"),
275 },
276 {
277 name: "batch processor invalid batch size console exporter",
278 processor: SpanProcessor{
279 Batch: &BatchSpanProcessor{
280 MaxExportBatchSize: ptr(-1),
281 Exporter: SpanExporter{
282 Console: ConsoleExporter{},
283 },
284 },
285 },
286 wantErrT: newErrGreaterThanZero("max_export_batch_size"),
287 },
288 {
289 name: "batch processor invalid export timeout console exporter",
290 processor: SpanProcessor{
291 Batch: &BatchSpanProcessor{
292 ExportTimeout: ptr(-2),
293 Exporter: SpanExporter{
294 Console: ConsoleExporter{},
295 },
296 },
297 },
298 wantErrT: newErrGreaterOrEqualZero("export_timeout"),
299 },
300 {
301 name: "batch processor invalid queue size console exporter",
302 processor: SpanProcessor{
303 Batch: &BatchSpanProcessor{
304 MaxQueueSize: ptr(-3),
305 Exporter: SpanExporter{
306 Console: ConsoleExporter{},
307 },
308 },
309 },
310 wantErrT: newErrGreaterThanZero("max_queue_size"),
311 },
312 {
313 name: "batch processor invalid schedule delay console exporter",
314 processor: SpanProcessor{
315 Batch: &BatchSpanProcessor{
316 ScheduleDelay: ptr(-4),
317 Exporter: SpanExporter{
318 Console: ConsoleExporter{},
319 },
320 },
321 },
322 wantErrT: newErrGreaterOrEqualZero("schedule_delay"),
323 },
324 {
325 name: "batch processor with multiple exporters",
326 processor: SpanProcessor{
327 Batch: &BatchSpanProcessor{
328 Exporter: SpanExporter{
329 Console: ConsoleExporter{},
330 OTLPHttp: &OTLPHttpExporter{},
331 },
332 },
333 },
334 wantErrT: newErrInvalid("must not specify multiple exporters"),
335 },
336 {
337 name: "batch processor console exporter",
338 processor: SpanProcessor{
339 Batch: &BatchSpanProcessor{
340 MaxExportBatchSize: ptr(1),
341 ExportTimeout: ptr(0),
342 MaxQueueSize: ptr(1),
343 ScheduleDelay: ptr(0),
344 Exporter: SpanExporter{
345 Console: ConsoleExporter{},
346 },
347 },
348 },
349 wantProcessor: sdktrace.NewBatchSpanProcessor(consoleExporter),
350 },
351 {
352 name: "batch/otlp-grpc-exporter-no-endpoint",
353 processor: SpanProcessor{
354 Batch: &BatchSpanProcessor{
355 MaxExportBatchSize: ptr(1),
356 ExportTimeout: ptr(0),
357 MaxQueueSize: ptr(1),
358 ScheduleDelay: ptr(0),
359 Exporter: SpanExporter{
360 OTLPGrpc: &OTLPGrpcExporter{
361 Compression: ptr("gzip"),
362 Timeout: ptr(1000),
363 Headers: []NameStringValuePair{
364 {Name: "test", Value: ptr("test1")},
365 },
366 },
367 },
368 },
369 },
370 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpGRPCExporter),
371 },
372 {
373 name: "batch/otlp-grpc-exporter",
374 processor: SpanProcessor{
375 Batch: &BatchSpanProcessor{
376 MaxExportBatchSize: ptr(1),
377 ExportTimeout: ptr(0),
378 MaxQueueSize: ptr(1),
379 ScheduleDelay: ptr(0),
380 Exporter: SpanExporter{
381 OTLPGrpc: &OTLPGrpcExporter{
382 Endpoint: ptr("http://localhost:4317"),
383 Compression: ptr("gzip"),
384 Timeout: ptr(1000),
385 Headers: []NameStringValuePair{
386 {Name: "test", Value: ptr("test1")},
387 },
388 },
389 },
390 },
391 },
392 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpGRPCExporter),
393 },
394 {
395 name: "batch/otlp-grpc-exporter-socket-endpoint",
396 processor: SpanProcessor{
397 Batch: &BatchSpanProcessor{
398 MaxExportBatchSize: ptr(1),
399 ExportTimeout: ptr(0),
400 MaxQueueSize: ptr(1),
401 ScheduleDelay: ptr(0),
402 Exporter: SpanExporter{
403 OTLPGrpc: &OTLPGrpcExporter{
404 Endpoint: ptr("unix:collector.sock"),
405 Compression: ptr("gzip"),
406 Timeout: ptr(1000),
407 Headers: []NameStringValuePair{
408 {Name: "test", Value: ptr("test1")},
409 },
410 },
411 },
412 },
413 },
414 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpGRPCExporter),
415 },
416 {
417 name: "batch/otlp-grpc-good-ca-certificate",
418 processor: SpanProcessor{
419 Batch: &BatchSpanProcessor{
420 Exporter: SpanExporter{
421 OTLPGrpc: &OTLPGrpcExporter{
422 Endpoint: ptr("localhost:4317"),
423 Compression: ptr("gzip"),
424 Timeout: ptr(1000),
425 Tls: &GrpcTls{
426 CaFile: ptr(filepath.Join("testdata", "ca.crt")),
427 },
428 },
429 },
430 },
431 },
432 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpGRPCExporter),
433 },
434 {
435 name: "batch/otlp-grpc-bad-ca-certificate",
436 processor: SpanProcessor{
437 Batch: &BatchSpanProcessor{
438 Exporter: SpanExporter{
439 OTLPGrpc: &OTLPGrpcExporter{
440 Endpoint: ptr("localhost:4317"),
441 Compression: ptr("gzip"),
442 Timeout: ptr(1000),
443 Tls: &GrpcTls{
444 CaFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
445 },
446 },
447 },
448 },
449 },
450 wantErrT: newErrInvalid("tls configuration"),
451 },
452 {
453 name: "batch/otlp-grpc-bad-client-certificate",
454 processor: SpanProcessor{
455 Batch: &BatchSpanProcessor{
456 Exporter: SpanExporter{
457 OTLPGrpc: &OTLPGrpcExporter{
458 Endpoint: ptr("localhost:4317"),
459 Compression: ptr("gzip"),
460 Timeout: ptr(1000),
461 Tls: &GrpcTls{
462 KeyFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
463 CertFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
464 },
465 },
466 },
467 },
468 },
469 wantErrT: newErrInvalid("tls configuration"),
470 },
471 {
472 name: "batch/otlp-grpc-bad-headerslist",
473 processor: SpanProcessor{
474 Batch: &BatchSpanProcessor{
475 Exporter: SpanExporter{
476 OTLPGrpc: &OTLPGrpcExporter{
477 Endpoint: ptr("localhost:4317"),
478 Compression: ptr("gzip"),
479 Timeout: ptr(1000),
480 HeadersList: ptr("==="),
481 },
482 },
483 },
484 },
485 wantErrT: newErrInvalid("invalid headers_list"),
486 },
487 {
488 name: "batch/otlp-grpc-exporter-no-scheme",
489 processor: SpanProcessor{
490 Batch: &BatchSpanProcessor{
491 MaxExportBatchSize: ptr(1),
492 ExportTimeout: ptr(0),
493 MaxQueueSize: ptr(1),
494 ScheduleDelay: ptr(0),
495 Exporter: SpanExporter{
496 OTLPGrpc: &OTLPGrpcExporter{
497 Endpoint: ptr("localhost:4317"),
498 Compression: ptr("gzip"),
499 Timeout: ptr(1000),
500 Headers: []NameStringValuePair{
501 {Name: "test", Value: ptr("test1")},
502 },
503 },
504 },
505 },
506 },
507 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpGRPCExporter),
508 },
509 {
510 name: "batch/otlp-grpc-invalid-endpoint",
511 processor: SpanProcessor{
512 Batch: &BatchSpanProcessor{
513 MaxExportBatchSize: ptr(1),
514 ExportTimeout: ptr(0),
515 MaxQueueSize: ptr(1),
516 ScheduleDelay: ptr(0),
517 Exporter: SpanExporter{
518 OTLPGrpc: &OTLPGrpcExporter{
519 Endpoint: ptr(" "),
520 Compression: ptr("gzip"),
521 Timeout: ptr(1000),
522 Headers: []NameStringValuePair{
523 {Name: "test", Value: ptr("test1")},
524 },
525 },
526 },
527 },
528 },
529 wantErrT: newErrInvalid("endpoint parsing failed"),
530 },
531 {
532 name: "batch/otlp-grpc-invalid-compression",
533 processor: SpanProcessor{
534 Batch: &BatchSpanProcessor{
535 MaxExportBatchSize: ptr(1),
536 ExportTimeout: ptr(0),
537 MaxQueueSize: ptr(1),
538 ScheduleDelay: ptr(0),
539 Exporter: SpanExporter{
540 OTLPGrpc: &OTLPGrpcExporter{
541 Endpoint: ptr("localhost:4317"),
542 Compression: ptr("invalid"),
543 Timeout: ptr(1000),
544 Headers: []NameStringValuePair{
545 {Name: "test", Value: ptr("test1")},
546 },
547 },
548 },
549 },
550 },
551 wantErrT: newErrInvalid("unsupported compression \"invalid\""),
552 },
553 {
554 name: "batch/otlp-http-exporter",
555 processor: SpanProcessor{
556 Batch: &BatchSpanProcessor{
557 MaxExportBatchSize: ptr(1),
558 ExportTimeout: ptr(0),
559 MaxQueueSize: ptr(1),
560 ScheduleDelay: ptr(0),
561 Exporter: SpanExporter{
562 OTLPHttp: &OTLPHttpExporter{
563 Endpoint: ptr("http://localhost:4318"),
564 Compression: ptr("gzip"),
565 Timeout: ptr(1000),
566 Headers: []NameStringValuePair{
567 {Name: "test", Value: ptr("test1")},
568 },
569 },
570 },
571 },
572 },
573 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
574 },
575 {
576 name: "batch/otlp-http-good-ca-certificate",
577 processor: SpanProcessor{
578 Batch: &BatchSpanProcessor{
579 Exporter: SpanExporter{
580 OTLPHttp: &OTLPHttpExporter{
581 Endpoint: ptr("localhost:4317"),
582 Compression: ptr("gzip"),
583 Timeout: ptr(1000),
584 Tls: &HttpTls{
585 CaFile: ptr(filepath.Join("testdata", "ca.crt")),
586 },
587 },
588 },
589 },
590 },
591 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
592 },
593 {
594 name: "batch/otlp-http-bad-ca-certificate",
595 processor: SpanProcessor{
596 Batch: &BatchSpanProcessor{
597 Exporter: SpanExporter{
598 OTLPHttp: &OTLPHttpExporter{
599 Endpoint: ptr("localhost:4317"),
600 Compression: ptr("gzip"),
601 Timeout: ptr(1000),
602 Tls: &HttpTls{
603 CaFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
604 },
605 },
606 },
607 },
608 },
609 wantErrT: newErrInvalid("tls configuration"),
610 },
611 {
612 name: "batch/otlp-http-bad-client-certificate",
613 processor: SpanProcessor{
614 Batch: &BatchSpanProcessor{
615 Exporter: SpanExporter{
616 OTLPHttp: &OTLPHttpExporter{
617 Endpoint: ptr("localhost:4317"),
618 Compression: ptr("gzip"),
619 Timeout: ptr(1000),
620 Tls: &HttpTls{
621 KeyFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
622 CertFile: ptr(filepath.Join("testdata", "bad_cert.crt")),
623 },
624 },
625 },
626 },
627 },
628 wantErrT: newErrInvalid("tls configuration"),
629 },
630 {
631 name: "batch/otlp-http-bad-headerslist",
632 processor: SpanProcessor{
633 Batch: &BatchSpanProcessor{
634 Exporter: SpanExporter{
635 OTLPHttp: &OTLPHttpExporter{
636 Endpoint: ptr("localhost:4317"),
637 Compression: ptr("gzip"),
638 Timeout: ptr(1000),
639 HeadersList: ptr("==="),
640 },
641 },
642 },
643 },
644 wantErrT: newErrInvalid("invalid headers_list"),
645 },
646 {
647 name: "batch/otlp-http-exporter-with-path",
648 processor: SpanProcessor{
649 Batch: &BatchSpanProcessor{
650 MaxExportBatchSize: ptr(1),
651 ExportTimeout: ptr(0),
652 MaxQueueSize: ptr(1),
653 ScheduleDelay: ptr(0),
654 Exporter: SpanExporter{
655 OTLPHttp: &OTLPHttpExporter{
656 Endpoint: ptr("http://localhost:4318/path/123"),
657 Compression: ptr("none"),
658 Timeout: ptr(1000),
659 Headers: []NameStringValuePair{
660 {Name: "test", Value: ptr("test1")},
661 },
662 },
663 },
664 },
665 },
666 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
667 },
668 {
669 name: "batch/otlp-http-exporter-no-endpoint",
670 processor: SpanProcessor{
671 Batch: &BatchSpanProcessor{
672 MaxExportBatchSize: ptr(1),
673 ExportTimeout: ptr(0),
674 MaxQueueSize: ptr(1),
675 ScheduleDelay: ptr(0),
676 Exporter: SpanExporter{
677 OTLPHttp: &OTLPHttpExporter{
678 Compression: ptr("gzip"),
679 Timeout: ptr(1000),
680 Headers: []NameStringValuePair{
681 {Name: "test", Value: ptr("test1")},
682 },
683 },
684 },
685 },
686 },
687 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
688 },
689 {
690 name: "batch/otlp-http-exporter-no-scheme",
691 processor: SpanProcessor{
692 Batch: &BatchSpanProcessor{
693 MaxExportBatchSize: ptr(1),
694 ExportTimeout: ptr(0),
695 MaxQueueSize: ptr(1),
696 ScheduleDelay: ptr(0),
697 Exporter: SpanExporter{
698 OTLPHttp: &OTLPHttpExporter{
699 Endpoint: ptr("localhost:4318"),
700 Compression: ptr("gzip"),
701 Timeout: ptr(1000),
702 Headers: []NameStringValuePair{
703 {Name: "test", Value: ptr("test1")},
704 },
705 },
706 },
707 },
708 },
709 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
710 },
711 {
712 name: "batch/otlp-http-invalid-endpoint",
713 processor: SpanProcessor{
714 Batch: &BatchSpanProcessor{
715 MaxExportBatchSize: ptr(1),
716 ExportTimeout: ptr(0),
717 MaxQueueSize: ptr(1),
718 ScheduleDelay: ptr(0),
719 Exporter: SpanExporter{
720 OTLPHttp: &OTLPHttpExporter{
721 Endpoint: ptr(" "),
722 Compression: ptr("gzip"),
723 Timeout: ptr(1000),
724 Headers: []NameStringValuePair{
725 {Name: "test", Value: ptr("test1")},
726 },
727 },
728 },
729 },
730 },
731 wantErrT: newErrInvalid("endpoint parsing failed"),
732 },
733 {
734 name: "batch/otlp-http-none-compression",
735 processor: SpanProcessor{
736 Batch: &BatchSpanProcessor{
737 MaxExportBatchSize: ptr(1),
738 ExportTimeout: ptr(0),
739 MaxQueueSize: ptr(1),
740 ScheduleDelay: ptr(0),
741 Exporter: SpanExporter{
742 OTLPHttp: &OTLPHttpExporter{
743 Endpoint: ptr("localhost:4318"),
744 Compression: ptr("none"),
745 Timeout: ptr(1000),
746 Headers: []NameStringValuePair{
747 {Name: "test", Value: ptr("test1")},
748 },
749 },
750 },
751 },
752 },
753 wantProcessor: sdktrace.NewBatchSpanProcessor(otlpHTTPExporter),
754 },
755 {
756 name: "batch/otlp-http-invalid-compression",
757 processor: SpanProcessor{
758 Batch: &BatchSpanProcessor{
759 MaxExportBatchSize: ptr(1),
760 ExportTimeout: ptr(0),
761 MaxQueueSize: ptr(1),
762 ScheduleDelay: ptr(0),
763 Exporter: SpanExporter{
764 OTLPHttp: &OTLPHttpExporter{
765 Endpoint: ptr("localhost:4318"),
766 Compression: ptr("invalid"),
767 Timeout: ptr(1000),
768 Headers: []NameStringValuePair{
769 {Name: "test", Value: ptr("test1")},
770 },
771 },
772 },
773 },
774 },
775 wantErrT: newErrInvalid("unsupported compression \"invalid\""),
776 },
777 {
778 name: "simple/no-exporter",
779 processor: SpanProcessor{
780 Simple: &SimpleSpanProcessor{
781 Exporter: SpanExporter{},
782 },
783 },
784 wantErrT: newErrInvalid("no valid span exporter"),
785 },
786 {
787 name: "simple/console-exporter",
788 processor: SpanProcessor{
789 Simple: &SimpleSpanProcessor{
790 Exporter: SpanExporter{
791 Console: ConsoleExporter{},
792 },
793 },
794 },
795 wantProcessor: sdktrace.NewSimpleSpanProcessor(consoleExporter),
796 },
797 {
798 name: "simple/otlp_file",
799 processor: SpanProcessor{
800 Simple: &SimpleSpanProcessor{
801 Exporter: SpanExporter{},
802 },
803 },
804 wantErrT: newErrInvalid("otlp_file/development"),
805 },
806 {
807 name: "simple/multiple",
808 processor: SpanProcessor{
809 Simple: &SimpleSpanProcessor{
810 Exporter: SpanExporter{
811 Console: ConsoleExporter{},
812 OTLPGrpc: &OTLPGrpcExporter{},
813 },
814 },
815 },
816 wantErrT: newErrInvalid("must not specify multiple exporters"),
817 },
818 }
819 for _, tt := range testCases {
820 t.Run(tt.name, func(t *testing.T) {
821 got, err := spanProcessor(t.Context(), tt.processor)
822 require.ErrorIs(t, err, tt.wantErrT)
823 if tt.wantProcessor == nil {
824 require.Nil(t, got)
825 } else {
826 require.Equal(t, reflect.TypeOf(tt.wantProcessor), reflect.TypeOf(got))
827 var fieldName string
828 switch reflect.TypeOf(tt.wantProcessor).String() {
829 case "*trace.simpleSpanProcessor":
830 fieldName = "exporter"
831 default:
832 fieldName = "e"
833 }
834 wantExporterType := reflect.Indirect(reflect.ValueOf(tt.wantProcessor)).FieldByName(fieldName).Elem().Type()
835 gotExporterType := reflect.Indirect(reflect.ValueOf(got)).FieldByName(fieldName).Elem().Type()
836 require.Equal(t, wantExporterType.String(), gotExporterType.String())
837 }
838 })
839 }
840 }
841
842 func TestSampler(t *testing.T) {
843 for _, tt := range []struct {
844 name string
845 sampler *Sampler
846 wantSampler sdktrace.Sampler
847 wantError error
848 }{
849 {
850 name: "no sampler configuration, return default",
851 sampler: nil,
852 wantSampler: sdktrace.ParentBased(sdktrace.AlwaysSample()),
853 },
854 {
855 name: "invalid sampler configuration, return error",
856 sampler: &Sampler{},
857 wantSampler: nil,
858 wantError: errInvalidSamplerConfiguration,
859 },
860 {
861 name: "sampler configuration always on",
862 sampler: &Sampler{
863 AlwaysOn: AlwaysOnSampler{},
864 },
865 wantSampler: sdktrace.AlwaysSample(),
866 },
867 {
868 name: "sampler configuration always off",
869 sampler: &Sampler{
870 AlwaysOff: AlwaysOffSampler{},
871 },
872 wantSampler: sdktrace.NeverSample(),
873 },
874 {
875 name: "sampler configuration trace ID ratio",
876 sampler: &Sampler{
877 TraceIDRatioBased: &TraceIDRatioBasedSampler{
878 Ratio: ptr(0.54),
879 },
880 },
881 wantSampler: sdktrace.TraceIDRatioBased(0.54),
882 },
883 {
884 name: "sampler configuration trace ID ratio no ratio",
885 sampler: &Sampler{
886 TraceIDRatioBased: &TraceIDRatioBasedSampler{},
887 },
888 wantSampler: sdktrace.TraceIDRatioBased(1),
889 },
890 {
891 name: "sampler configuration parent based no options",
892 sampler: &Sampler{
893 ParentBased: &ParentBasedSampler{},
894 },
895 wantSampler: sdktrace.ParentBased(sdktrace.AlwaysSample()),
896 },
897 {
898 name: "sampler configuration parent based many options",
899 sampler: &Sampler{
900 ParentBased: &ParentBasedSampler{
901 Root: &Sampler{
902 AlwaysOff: AlwaysOffSampler{},
903 },
904 RemoteParentNotSampled: &Sampler{
905 AlwaysOn: AlwaysOnSampler{},
906 },
907 RemoteParentSampled: &Sampler{
908 TraceIDRatioBased: &TraceIDRatioBasedSampler{
909 Ratio: ptr(0.009),
910 },
911 },
912 LocalParentNotSampled: &Sampler{
913 AlwaysOff: AlwaysOffSampler{},
914 },
915 LocalParentSampled: &Sampler{
916 TraceIDRatioBased: &TraceIDRatioBasedSampler{
917 Ratio: ptr(0.05),
918 },
919 },
920 },
921 },
922 wantSampler: sdktrace.ParentBased(
923 sdktrace.NeverSample(),
924 sdktrace.WithLocalParentNotSampled(sdktrace.NeverSample()),
925 sdktrace.WithLocalParentSampled(sdktrace.TraceIDRatioBased(0.05)),
926 sdktrace.WithRemoteParentNotSampled(sdktrace.AlwaysSample()),
927 sdktrace.WithRemoteParentSampled(sdktrace.TraceIDRatioBased(0.009)),
928 ),
929 },
930 {
931 name: "sampler configuration with many errors",
932 sampler: &Sampler{
933 ParentBased: &ParentBasedSampler{
934 Root: &Sampler{},
935 RemoteParentNotSampled: &Sampler{},
936 RemoteParentSampled: &Sampler{},
937 LocalParentNotSampled: &Sampler{},
938 LocalParentSampled: &Sampler{},
939 },
940 },
941 wantError: errors.Join(
942 errInvalidSamplerConfiguration,
943 errInvalidSamplerConfiguration,
944 errInvalidSamplerConfiguration,
945 errInvalidSamplerConfiguration,
946 errInvalidSamplerConfiguration,
947 ),
948 },
949 } {
950 t.Run(tt.name, func(t *testing.T) {
951 got, err := sampler(tt.sampler)
952 if tt.wantError != nil {
953 require.Error(t, err)
954 require.EqualError(t, err, tt.wantError.Error())
955 } else {
956 require.NoError(t, err)
957 }
958
959 require.Equal(t, tt.wantSampler, got)
960 })
961 }
962 }
963
964 func Test_otlpGRPCTraceExporter(t *testing.T) {
965 if runtime.GOOS == "windows" || runtime.GOOS == "darwin" {
966 // TODO (#8115): Fix the flakiness on Windows and MacOS.
967 t.Skip("Test is flaky on Windows and MacOS.")
968 }
969 type args struct {
970 ctx context.Context
971 otlpConfig *OTLPGrpcExporter
972 }
973 tests := []struct {
974 name string
975 args args
976 grpcServerOpts func() ([]grpc.ServerOption, error)
977 }{
978 {
979 name: "no TLS config",
980 args: args{
981 ctx: t.Context(),
982 otlpConfig: &OTLPGrpcExporter{
983 Compression: ptr("gzip"),
984 Timeout: ptr(5000),
985 Tls: &GrpcTls{
986 Insecure: ptr(true),
987 },
988 Headers: []NameStringValuePair{
989 {Name: "test", Value: ptr("test1")},
990 },
991 },
992 },
993 grpcServerOpts: func() ([]grpc.ServerOption, error) {
994 return []grpc.ServerOption{}, nil
995 },
996 },
997 {
998 name: "with TLS config",
999 args: args{
1000 ctx: t.Context(),
1001 otlpConfig: &OTLPGrpcExporter{
1002 Compression: ptr("gzip"),
1003 Timeout: ptr(5000),
1004 Tls: &GrpcTls{
1005 CaFile: ptr("testdata/server-certs/server.crt"),
1006 },
1007 Headers: []NameStringValuePair{
1008 {Name: "test", Value: ptr("test1")},
1009 },
1010 },
1011 },
1012 grpcServerOpts: func() ([]grpc.ServerOption, error) {
1013 opts := []grpc.ServerOption{}
1014 tlsCreds, err := credentials.NewServerTLSFromFile("testdata/server-certs/server.crt", "testdata/server-certs/server.key")
1015 if err != nil {
1016 return nil, err
1017 }
1018 opts = append(opts, grpc.Creds(tlsCreds))
1019 return opts, nil
1020 },
1021 },
1022 {
1023 name: "with TLS config and client key",
1024 args: args{
1025 ctx: t.Context(),
1026 otlpConfig: &OTLPGrpcExporter{
1027 Compression: ptr("gzip"),
1028 Timeout: ptr(5000),
1029 Tls: &GrpcTls{
1030 CaFile: ptr("testdata/server-certs/server.crt"),
1031 KeyFile: ptr("testdata/client-certs/client.key"),
1032 CertFile: ptr("testdata/client-certs/client.crt"),
1033 },
1034 Headers: []NameStringValuePair{
1035 {Name: "test", Value: ptr("test1")},
1036 },
1037 },
1038 },
1039 grpcServerOpts: func() ([]grpc.ServerOption, error) {
1040 opts := []grpc.ServerOption{}
1041 cert, err := tls.LoadX509KeyPair("testdata/server-certs/server.crt", "testdata/server-certs/server.key")
1042 if err != nil {
1043 return nil, err
1044 }
1045 caCert, err := os.ReadFile("testdata/ca.crt")
1046 if err != nil {
1047 return nil, err
1048 }
1049 caCertPool := x509.NewCertPool()
1050 caCertPool.AppendCertsFromPEM(caCert)
1051 tlsCreds := credentials.NewTLS(&tls.Config{
1052 Certificates: []tls.Certificate{cert},
1053 ClientCAs: caCertPool,
1054 ClientAuth: tls.RequireAndVerifyClientCert,
1055 })
1056 opts = append(opts, grpc.Creds(tlsCreds))
1057 return opts, nil
1058 },
1059 },
1060 }
1061 for _, tt := range tests {
1062 t.Run(tt.name, func(t *testing.T) {
1063 n, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp4", "localhost:0")
1064 require.NoError(t, err)
1065
1066 // We need to manually construct the endpoint using the port on which the server is listening.
1067 //
1068 // n.Addr() always returns 127.0.0.1 instead of localhost.
1069 // But our certificate is created with CN as 'localhost', not '127.0.0.1'.
1070 // So we have to manually form the endpoint as "localhost:<port>".
1071 _, port, err := net.SplitHostPort(n.Addr().String())
1072 require.NoError(t, err)
1073 tt.args.otlpConfig.Endpoint = ptr("localhost:" + port)
1074
1075 serverOpts, err := tt.grpcServerOpts()
1076 require.NoError(t, err)
1077
1078 startGRPCTraceCollector(t, n, serverOpts)
1079
1080 exporter, err := otlpGRPCSpanExporter(tt.args.ctx, tt.args.otlpConfig)
1081 require.NoError(t, err)
1082
1083 input := tracetest.SpanStubs{
1084 {
1085 Name: "test-span",
1086 },
1087 }
1088
1089 assert.EventuallyWithT(t, func(collect *assert.CollectT) {
1090 assert.NoError(collect, exporter.ExportSpans(context.Background(), input.Snapshots())) //nolint:usetesting // required to avoid getting a canceled context.
1091 }, 10*time.Second, 1*time.Second)
1092 })
1093 }
1094 }
1095
1096 // grpcTraceCollector is an OTLP gRPC server that collects all requests it receives.
1097 type grpcTraceCollector struct {
1098 v1.UnimplementedTraceServiceServer
1099 }
1100
1101 var _ v1.TraceServiceServer = (*grpcTraceCollector)(nil)
1102
1103 // startGRPCTraceCollector returns a *grpcTraceCollector that is listening at the provided
1104 // endpoint.
1105 //
1106 // If endpoint is an empty string, the returned collector will be listening on
1107 // the localhost interface at an OS chosen port.
1108 func startGRPCTraceCollector(t *testing.T, listener net.Listener, serverOptions []grpc.ServerOption) {
1109 srv := grpc.NewServer(serverOptions...)
1110 c := &grpcTraceCollector{}
1111
1112 v1.RegisterTraceServiceServer(srv, c)
1113
1114 errCh := make(chan error, 1)
1115 go func() { errCh <- srv.Serve(listener) }()
1116
1117 t.Cleanup(func() {
1118 srv.GracefulStop()
1119 if err := <-errCh; err != nil && !errors.Is(err, grpc.ErrServerStopped) {
1120 assert.NoError(t, err)
1121 }
1122 })
1123 }
1124
1125 // Export handles the export req.
1126 func (*grpcTraceCollector) Export(
1127 _ context.Context,
1128 _ *v1.ExportTraceServiceRequest,
1129 ) (*v1.ExportTraceServiceResponse, error) {
1130 return &v1.ExportTraceServiceResponse{}, nil
1131 }