Debian Codegraph @

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