Debian Codegraph @

otelconf/x/trace_test.go

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