Debian Codegraph @

otelconf/x/metric_test.go

raw symbols SCIP
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 "fmt"
13 "net"
14 "net/http"
15 "net/http/httptest"
16 "os"
17 "path/filepath"
18 "reflect"
19 "runtime"
20 "strings"
21 "testing"
22 "time"
23
24 "github.com/stretchr/testify/assert"
25 "github.com/stretchr/testify/require"
26 "go.opentelemetry.io/otel/attribute"
27 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
28 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
29 otelprom "go.opentelemetry.io/otel/exporters/prometheus"
30 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
31 "go.opentelemetry.io/otel/metric"
32 "go.opentelemetry.io/otel/metric/noop"
33 "go.opentelemetry.io/otel/sdk/instrumentation"
34 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
35 "go.opentelemetry.io/otel/sdk/metric/metricdata"
36 "go.opentelemetry.io/otel/sdk/resource"
37 v1 "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
38 "google.golang.org/grpc"
39 "google.golang.org/grpc/credentials"
40 )
41
42 func TestMeterProvider(t *testing.T) {
43 tests := []struct {
44 name string
45 cfg configOptions
46 wantProvider metric.MeterProvider
47 wantErr error
48 }{
49 {
50 name: "no-meter-provider-configured",
51 wantProvider: noop.NewMeterProvider(),
52 },
53 {
54 name: "error-in-config",
55 cfg: configOptions{
56 opentelemetryConfig: OpenTelemetryConfiguration{
57 MeterProvider: &MeterProvider{
58 Readers: []MetricReader{
59 {
60 Periodic: &PeriodicMetricReader{},
61 Pull: &PullMetricReader{},
62 },
63 },
64 },
65 },
66 },
67 wantProvider: noop.NewMeterProvider(),
68 wantErr: newErrInvalid("must not specify multiple metric reader type"),
69 },
70 {
71 name: "multiple-errors-in-config",
72 cfg: configOptions{
73 opentelemetryConfig: OpenTelemetryConfiguration{
74 MeterProvider: &MeterProvider{
75 Readers: []MetricReader{
76 {
77 Periodic: &PeriodicMetricReader{},
78 Pull: &PullMetricReader{},
79 },
80 {
81 Periodic: &PeriodicMetricReader{
82 Exporter: PushMetricExporter{
83 Console: &ConsoleMetricExporter{},
84 OTLPGrpc: &OTLPGrpcMetricExporter{},
85 },
86 },
87 },
88 },
89 },
90 },
91 },
92 wantProvider: noop.NewMeterProvider(),
93 wantErr: newErrInvalid("must not specify multiple metric reader type"),
94 },
95 }
96 for _, tt := range tests {
97 t.Run(tt.name, func(t *testing.T) {
98 mp, shutdown, err := meterProvider(tt.cfg, resource.Default())
99 require.Equal(t, tt.wantProvider, mp)
100 assert.ErrorIs(t, err, tt.wantErr)
101 require.NoError(t, shutdown(t.Context()))
102 })
103 }
104 }
105
106 func TestMeterProviderOptions(t *testing.T) {
107 var calls int
108 srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
109 calls++
110 }))
111 defer srv.Close()
112
113 cfg := OpenTelemetryConfiguration{
114 MeterProvider: &MeterProvider{
115 Readers: []MetricReader{{
116 Periodic: &PeriodicMetricReader{
117 Exporter: PushMetricExporter{
118 OTLPHttp: &OTLPHttpMetricExporter{
119 Endpoint: ptr(srv.URL),
120 },
121 },
122 },
123 }},
124 },
125 }
126
127 var buf bytes.Buffer
128 stdoutmetricExporter, err := stdoutmetric.New(stdoutmetric.WithWriter(&buf))
129 require.NoError(t, err)
130
131 res := resource.NewSchemaless(attribute.String("foo", "bar"))
132 sdk, err := NewSDK(
133 WithOpenTelemetryConfiguration(cfg),
134 WithMeterProviderOptions(sdkmetric.WithReader(sdkmetric.NewPeriodicReader(stdoutmetricExporter))),
135 WithMeterProviderOptions(sdkmetric.WithResource(res)),
136 )
137 require.NoError(t, err)
138 defer func() {
139 assert.NoError(t, sdk.Shutdown(t.Context()))
140 // The exporter, which we passed in as an extra option to NewSDK,
141 // should be wired up to the provider in addition to the
142 // configuration-based OTLP exporter.
143 assert.NotZero(t, buf)
144 assert.Equal(t, 1, calls) // flushed on shutdown
145
146 // Options provided by WithMeterProviderOptions may be overridden
147 // by configuration, e.g. the resource is always defined via
148 // configuration.
149 assert.NotContains(t, buf.String(), "foo")
150 }()
151
152 counter, _ := sdk.MeterProvider().Meter("test").Int64Counter("counter")
153 counter.Add(t.Context(), 1)
154 }
155
156 func TestReader(t *testing.T) {
157 consoleExporter, err := stdoutmetric.New(
158 stdoutmetric.WithPrettyPrint(),
159 )
160 require.NoError(t, err)
161 ctx := t.Context()
162 otlpGRPCExporter, err := otlpmetricgrpc.New(ctx)
163 require.NoError(t, err)
164 otlpHTTPExporter, err := otlpmetrichttp.New(ctx)
165 require.NoError(t, err)
166 promExporter, err := otelprom.New()
167 require.NoError(t, err)
168 testCases := []struct {
169 name string
170 reader MetricReader
171 args any
172 wantErrT error
173 wantReader sdkmetric.Reader
174 }{
175 {
176 name: "no reader",
177 wantErrT: newErrInvalid("no valid metric reader"),
178 },
179 {
180 name: "pull/no-exporter",
181 reader: MetricReader{
182 Pull: &PullMetricReader{},
183 },
184 wantErrT: newErrInvalid("no valid metric exporter"),
185 },
186 {
187 name: "pull/prometheus-no-host",
188 reader: MetricReader{
189 Pull: &PullMetricReader{
190 Exporter: PullMetricExporter{
191 PrometheusDevelopment: &ExperimentalPrometheusMetricExporter{},
192 },
193 },
194 },
195 wantErrT: newErrInvalid("host must be specified"),
196 },
197 {
198 name: "pull/prometheus-no-port",
199 reader: MetricReader{
200 Pull: &PullMetricReader{
201 Exporter: PullMetricExporter{
202 PrometheusDevelopment: &ExperimentalPrometheusMetricExporter{
203 Host: ptr("localhost"),
204 },
205 },
206 },
207 },
208 wantErrT: newErrInvalid("port must be specified"),
209 },
210 {
211 name: "pull/prometheus",
212 reader: MetricReader{
213 Pull: &PullMetricReader{
214 Exporter: PullMetricExporter{
215 PrometheusDevelopment: &ExperimentalPrometheusMetricExporter{
216 Host: ptr("localhost"),
217 Port: ptr(0),
218 WithoutScopeInfo: ptr(true),
219 TranslationStrategy: ptr(ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithoutSuffixes),
220 WithResourceConstantLabels: &IncludeExclude{
221 Included: []string{"include"},
222 Excluded: []string{"exclude"},
223 },
224 },
225 },
226 },
227 },
228 wantReader: readerWithServer{promExporter, nil},
229 },
230 {
231 name: "pull/prometheus/invalid strategy",
232 reader: MetricReader{
233 Pull: &PullMetricReader{
234 Exporter: PullMetricExporter{
235 PrometheusDevelopment: &ExperimentalPrometheusMetricExporter{
236 Host: ptr("localhost"),
237 Port: ptr(0),
238 WithoutScopeInfo: ptr(true),
239 TranslationStrategy: ptr(ExperimentalPrometheusTranslationStrategy("invalid-strategy")),
240 WithResourceConstantLabels: &IncludeExclude{
241 Included: []string{"include"},
242 Excluded: []string{"exclude"},
243 },
244 },
245 },
246 },
247 },
248 wantErrT: newErrInvalid("translation strategy invalid"),
249 },
250 {
251 name: "periodic/otlp-grpc-exporter",
252 reader: MetricReader{
253 Periodic: &PeriodicMetricReader{
254 Exporter: PushMetricExporter{
255 OTLPGrpc: &OTLPGrpcMetricExporter{
256 Endpoint: ptr("http://localhost:4318"),
257 Compression: ptr("gzip"),
258 Timeout: ptr(1000),
259 Headers: []NameStringValuePair{
260 {Name: "test", Value: ptr("test1")},
261 },
262 },
263 },
264 },
265 },
266 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
267 },
268 {
269 name: "periodic/otlp-grpc-exporter-with-path",
270 reader: MetricReader{
271 Periodic: &PeriodicMetricReader{
272 Exporter: PushMetricExporter{
273 OTLPGrpc: &OTLPGrpcMetricExporter{
274 Endpoint: ptr("http://localhost:4318/path/123"),
275 Compression: ptr("gzip"),
276 Timeout: ptr(1000),
277 Headers: []NameStringValuePair{
278 {Name: "test", Value: ptr("test1")},
279 },
280 },
281 },
282 },
283 },
284 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
285 },
286 {
287 name: "periodic/otlp-grpc-good-ca-certificate",
288 reader: MetricReader{
289 Periodic: &PeriodicMetricReader{
290 Exporter: PushMetricExporter{
291 OTLPGrpc: &OTLPGrpcMetricExporter{
292 Endpoint: ptr("https://localhost:4317"),
293 Compression: ptr("gzip"),
294 Timeout: ptr(1000),
295 Tls: &GrpcTls{
296 CaFile: ptr(filepath.Join("..", "testdata", "ca.crt")),
297 },
298 },
299 },
300 },
301 },
302 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
303 },
304 {
305 name: "periodic/otlp-grpc-bad-ca-certificate",
306 reader: MetricReader{
307 Periodic: &PeriodicMetricReader{
308 Exporter: PushMetricExporter{
309 OTLPGrpc: &OTLPGrpcMetricExporter{
310 Endpoint: ptr("https://localhost:4317"),
311 Compression: ptr("gzip"),
312 Timeout: ptr(1000),
313 Tls: &GrpcTls{
314 CaFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
315 },
316 },
317 },
318 },
319 },
320 wantErrT: newErrInvalid("tls configuration"),
321 },
322 {
323 name: "periodic/otlp-grpc-bad-client-certificate",
324 reader: MetricReader{
325 Periodic: &PeriodicMetricReader{
326 Exporter: PushMetricExporter{
327 OTLPGrpc: &OTLPGrpcMetricExporter{
328 Endpoint: ptr("localhost:4317"),
329 Compression: ptr("gzip"),
330 Timeout: ptr(1000),
331 Tls: &GrpcTls{
332 KeyFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
333 CertFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
334 },
335 },
336 },
337 },
338 },
339 wantErrT: newErrInvalid("tls configuration"),
340 },
341 {
342 name: "periodic/otlp-grpc-bad-headerslist",
343 reader: MetricReader{
344 Periodic: &PeriodicMetricReader{
345 Exporter: PushMetricExporter{
346 OTLPGrpc: &OTLPGrpcMetricExporter{
347 Endpoint: ptr("localhost:4317"),
348 Compression: ptr("gzip"),
349 Timeout: ptr(1000),
350 HeadersList: ptr("==="),
351 },
352 },
353 },
354 },
355 wantErrT: newErrInvalid("invalid headers_list"),
356 },
357 {
358 name: "periodic/otlp-grpc-exporter-no-endpoint",
359 reader: MetricReader{
360 Periodic: &PeriodicMetricReader{
361 Exporter: PushMetricExporter{
362 OTLPGrpc: &OTLPGrpcMetricExporter{
363 Compression: ptr("gzip"),
364 Timeout: ptr(1000),
365 Headers: []NameStringValuePair{
366 {Name: "test", Value: ptr("test1")},
367 },
368 },
369 },
370 },
371 },
372 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
373 },
374 {
375 name: "periodic/otlp-grpc-exporter-socket-endpoint",
376 reader: MetricReader{
377 Periodic: &PeriodicMetricReader{
378 Exporter: PushMetricExporter{
379 OTLPGrpc: &OTLPGrpcMetricExporter{
380 Endpoint: ptr("unix:collector.sock"),
381 Compression: ptr("gzip"),
382 Timeout: ptr(1000),
383 Headers: []NameStringValuePair{
384 {Name: "test", Value: ptr("test1")},
385 },
386 },
387 },
388 },
389 },
390 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
391 },
392 {
393 name: "periodic/otlp-grpc-exporter-no-scheme",
394 reader: MetricReader{
395 Periodic: &PeriodicMetricReader{
396 Exporter: PushMetricExporter{
397 OTLPGrpc: &OTLPGrpcMetricExporter{
398 Endpoint: ptr("localhost:4318"),
399 Compression: ptr("gzip"),
400 Timeout: ptr(1000),
401 Headers: []NameStringValuePair{
402 {Name: "test", Value: ptr("test1")},
403 },
404 },
405 },
406 },
407 },
408 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
409 },
410 {
411 name: "periodic/otlp-grpc-invalid-endpoint",
412 reader: MetricReader{
413 Periodic: &PeriodicMetricReader{
414 Exporter: PushMetricExporter{
415 OTLPGrpc: &OTLPGrpcMetricExporter{
416 Endpoint: ptr(" "),
417 Compression: ptr("gzip"),
418 Timeout: ptr(1000),
419 Headers: []NameStringValuePair{
420 {Name: "test", Value: ptr("test1")},
421 },
422 },
423 },
424 },
425 },
426 wantErrT: newErrInvalid("endpoint parsing failed"),
427 },
428 {
429 name: "periodic/otlp-grpc-none-compression",
430 reader: MetricReader{
431 Periodic: &PeriodicMetricReader{
432 Exporter: PushMetricExporter{
433 OTLPGrpc: &OTLPGrpcMetricExporter{
434 Endpoint: ptr("localhost:4318"),
435 Compression: ptr("none"),
436 Timeout: ptr(1000),
437 Headers: []NameStringValuePair{
438 {Name: "test", Value: ptr("test1")},
439 },
440 },
441 },
442 },
443 },
444 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
445 },
446 {
447 name: "periodic/otlp-grpc-delta-temporality",
448 reader: MetricReader{
449 Periodic: &PeriodicMetricReader{
450 Exporter: PushMetricExporter{
451 OTLPGrpc: &OTLPGrpcMetricExporter{
452 Endpoint: ptr("localhost:4318"),
453 Compression: ptr("none"),
454 Timeout: ptr(1000),
455 Headers: []NameStringValuePair{
456 {Name: "test", Value: ptr("test1")},
457 },
458 TemporalityPreference: ptr(ExporterTemporalityPreferenceDelta),
459 },
460 },
461 },
462 },
463 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
464 },
465 {
466 name: "periodic/otlp-grpc-cumulative-temporality",
467 reader: MetricReader{
468 Periodic: &PeriodicMetricReader{
469 Exporter: PushMetricExporter{
470 OTLPGrpc: &OTLPGrpcMetricExporter{
471 Endpoint: ptr("localhost:4318"),
472 Compression: ptr("none"),
473 Timeout: ptr(1000),
474 Headers: []NameStringValuePair{
475 {Name: "test", Value: ptr("test1")},
476 },
477 TemporalityPreference: ptr(ExporterTemporalityPreferenceCumulative),
478 },
479 },
480 },
481 },
482 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
483 },
484 {
485 name: "periodic/otlp-grpc-lowmemory-temporality",
486 reader: MetricReader{
487 Periodic: &PeriodicMetricReader{
488 Exporter: PushMetricExporter{
489 OTLPGrpc: &OTLPGrpcMetricExporter{
490 Endpoint: ptr("localhost:4318"),
491 Compression: ptr("none"),
492 Timeout: ptr(1000),
493 Headers: []NameStringValuePair{
494 {Name: "test", Value: ptr("test1")},
495 },
496 TemporalityPreference: ptr(ExporterTemporalityPreferenceLowMemory),
497 },
498 },
499 },
500 },
501 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
502 },
503 {
504 name: "periodic/otlp-grpc-invalid-temporality",
505 reader: MetricReader{
506 Periodic: &PeriodicMetricReader{
507 Exporter: PushMetricExporter{
508 OTLPGrpc: &OTLPGrpcMetricExporter{
509 Endpoint: ptr("localhost:4318"),
510 Compression: ptr("none"),
511 Timeout: ptr(1000),
512 Headers: []NameStringValuePair{
513 {Name: "test", Value: ptr("test1")},
514 },
515 TemporalityPreference: (*ExporterTemporalityPreference)(ptr("invalid")),
516 },
517 },
518 },
519 },
520 wantErrT: newErrInvalid("unsupported temporality preference \"invalid\""),
521 },
522 {
523 name: "periodic/otlp-grpc-invalid-compression",
524 reader: MetricReader{
525 Periodic: &PeriodicMetricReader{
526 Exporter: PushMetricExporter{
527 OTLPGrpc: &OTLPGrpcMetricExporter{
528 Endpoint: ptr("localhost:4318"),
529 Compression: ptr("invalid"),
530 Timeout: ptr(1000),
531 Headers: []NameStringValuePair{
532 {Name: "test", Value: ptr("test1")},
533 },
534 },
535 },
536 },
537 },
538 wantErrT: newErrInvalid("unsupported compression \"invalid\""),
539 },
540 {
541 name: "periodic/otlp-http-exporter",
542 reader: MetricReader{
543 Periodic: &PeriodicMetricReader{
544 Exporter: PushMetricExporter{
545 OTLPHttp: &OTLPHttpMetricExporter{
546 Endpoint: ptr("http://localhost:4318"),
547 Compression: ptr("gzip"),
548 Timeout: ptr(1000),
549 Headers: []NameStringValuePair{
550 {Name: "test", Value: ptr("test1")},
551 },
552 },
553 },
554 },
555 },
556 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
557 },
558 {
559 name: "periodic/otlp-http-good-ca-certificate",
560 reader: MetricReader{
561 Periodic: &PeriodicMetricReader{
562 Exporter: PushMetricExporter{
563 OTLPHttp: &OTLPHttpMetricExporter{
564 Endpoint: ptr("https://localhost:4317"),
565 Compression: ptr("gzip"),
566 Timeout: ptr(1000),
567 Tls: &HttpTls{
568 CaFile: ptr(filepath.Join("..", "testdata", "ca.crt")),
569 },
570 },
571 },
572 },
573 },
574 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
575 },
576 {
577 name: "periodic/otlp-http-bad-ca-certificate",
578 reader: MetricReader{
579 Periodic: &PeriodicMetricReader{
580 Exporter: PushMetricExporter{
581 OTLPHttp: &OTLPHttpMetricExporter{
582 Endpoint: ptr("https://localhost:4317"),
583 Compression: ptr("gzip"),
584 Timeout: ptr(1000),
585 Tls: &HttpTls{
586 CaFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
587 },
588 },
589 },
590 },
591 },
592 wantErrT: newErrInvalid("tls configuration"),
593 },
594 {
595 name: "periodic/otlp-http-bad-client-certificate",
596 reader: MetricReader{
597 Periodic: &PeriodicMetricReader{
598 Exporter: PushMetricExporter{
599 OTLPHttp: &OTLPHttpMetricExporter{
600 Endpoint: ptr("localhost:4317"),
601 Compression: ptr("gzip"),
602 Timeout: ptr(1000),
603 Tls: &HttpTls{
604 KeyFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
605 CertFile: ptr(filepath.Join("..", "testdata", "bad_cert.crt")),
606 },
607 },
608 },
609 },
610 },
611 wantErrT: newErrInvalid("tls configuration"),
612 },
613 {
614 name: "periodic/otlp-http-bad-headerslist",
615 reader: MetricReader{
616 Periodic: &PeriodicMetricReader{
617 Exporter: PushMetricExporter{
618 OTLPHttp: &OTLPHttpMetricExporter{
619 Endpoint: ptr("localhost:4317"),
620 Compression: ptr("gzip"),
621 Timeout: ptr(1000),
622 HeadersList: ptr("==="),
623 },
624 },
625 },
626 },
627 wantErrT: newErrInvalid("invalid headers_list"),
628 },
629 {
630 name: "periodic/otlp-http-exporter-with-path",
631 reader: MetricReader{
632 Periodic: &PeriodicMetricReader{
633 Exporter: PushMetricExporter{
634 OTLPHttp: &OTLPHttpMetricExporter{
635 Endpoint: ptr("http://localhost:4318/path/123"),
636 Compression: ptr("gzip"),
637 Timeout: ptr(1000),
638 Headers: []NameStringValuePair{
639 {Name: "test", Value: ptr("test1")},
640 },
641 },
642 },
643 },
644 },
645 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
646 },
647 {
648 name: "periodic/otlp-http-exporter-no-endpoint",
649 reader: MetricReader{
650 Periodic: &PeriodicMetricReader{
651 Exporter: PushMetricExporter{
652 OTLPHttp: &OTLPHttpMetricExporter{
653 Compression: ptr("gzip"),
654 Timeout: ptr(1000),
655 Headers: []NameStringValuePair{
656 {Name: "test", Value: ptr("test1")},
657 },
658 },
659 },
660 },
661 },
662 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
663 },
664 {
665 name: "periodic/otlp-http-exporter-no-scheme",
666 reader: MetricReader{
667 Periodic: &PeriodicMetricReader{
668 Exporter: PushMetricExporter{
669 OTLPHttp: &OTLPHttpMetricExporter{
670 Endpoint: ptr("localhost:4318"),
671 Compression: ptr("gzip"),
672 Timeout: ptr(1000),
673 Headers: []NameStringValuePair{
674 {Name: "test", Value: ptr("test1")},
675 },
676 },
677 },
678 },
679 },
680 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
681 },
682 {
683 name: "periodic/otlp-http-invalid-endpoint",
684 reader: MetricReader{
685 Periodic: &PeriodicMetricReader{
686 Exporter: PushMetricExporter{
687 OTLPHttp: &OTLPHttpMetricExporter{
688 Endpoint: ptr(" "),
689 Compression: ptr("gzip"),
690 Timeout: ptr(1000),
691 Headers: []NameStringValuePair{
692 {Name: "test", Value: ptr("test1")},
693 },
694 },
695 },
696 },
697 },
698 wantErrT: newErrInvalid("endpoint parsing failed"),
699 },
700 {
701 name: "periodic/otlp-http-none-compression",
702 reader: MetricReader{
703 Periodic: &PeriodicMetricReader{
704 Exporter: PushMetricExporter{
705 OTLPHttp: &OTLPHttpMetricExporter{
706 Endpoint: ptr("localhost:4318"),
707 Compression: ptr("none"),
708 Timeout: ptr(1000),
709 Headers: []NameStringValuePair{
710 {Name: "test", Value: ptr("test1")},
711 },
712 },
713 },
714 },
715 },
716 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
717 },
718 {
719 name: "periodic/otlp-http-cumulative-temporality",
720 reader: MetricReader{
721 Periodic: &PeriodicMetricReader{
722 Exporter: PushMetricExporter{
723 OTLPHttp: &OTLPHttpMetricExporter{
724 Endpoint: ptr("localhost:4318"),
725 Compression: ptr("none"),
726 Timeout: ptr(1000),
727 Headers: []NameStringValuePair{
728 {Name: "test", Value: ptr("test1")},
729 },
730 TemporalityPreference: ptr(ExporterTemporalityPreferenceCumulative),
731 },
732 },
733 },
734 },
735 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
736 },
737 {
738 name: "periodic/otlp-http-lowmemory-temporality",
739 reader: MetricReader{
740 Periodic: &PeriodicMetricReader{
741 Exporter: PushMetricExporter{
742 OTLPHttp: &OTLPHttpMetricExporter{
743 Endpoint: ptr("localhost:4318"),
744 Compression: ptr("none"),
745 Timeout: ptr(1000),
746 Headers: []NameStringValuePair{
747 {Name: "test", Value: ptr("test1")},
748 },
749 TemporalityPreference: ptr(ExporterTemporalityPreferenceLowMemory),
750 },
751 },
752 },
753 },
754 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
755 },
756 {
757 name: "periodic/otlp-http-delta-temporality",
758 reader: MetricReader{
759 Periodic: &PeriodicMetricReader{
760 Exporter: PushMetricExporter{
761 OTLPHttp: &OTLPHttpMetricExporter{
762 Endpoint: ptr("localhost:4318"),
763 Compression: ptr("none"),
764 Timeout: ptr(1000),
765 Headers: []NameStringValuePair{
766 {Name: "test", Value: ptr("test1")},
767 },
768 TemporalityPreference: ptr(ExporterTemporalityPreferenceDelta),
769 },
770 },
771 },
772 },
773 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
774 },
775 {
776 name: "periodic/otlp-http-invalid-temporality",
777 reader: MetricReader{
778 Periodic: &PeriodicMetricReader{
779 Exporter: PushMetricExporter{
780 OTLPHttp: &OTLPHttpMetricExporter{
781 Endpoint: ptr("localhost:4318"),
782 Compression: ptr("none"),
783 Timeout: ptr(1000),
784 Headers: []NameStringValuePair{
785 {Name: "test", Value: ptr("test1")},
786 },
787 TemporalityPreference: (*ExporterTemporalityPreference)(ptr("invalid")),
788 },
789 },
790 },
791 },
792 wantErrT: newErrInvalid("unsupported temporality preference \"invalid\""),
793 },
794 {
795 name: "periodic/otlp-http-invalid-compression",
796 reader: MetricReader{
797 Periodic: &PeriodicMetricReader{
798 Exporter: PushMetricExporter{
799 OTLPHttp: &OTLPHttpMetricExporter{
800 Endpoint: ptr("localhost:4318"),
801 Compression: ptr("invalid"),
802 Timeout: ptr(1000),
803 Headers: []NameStringValuePair{
804 {Name: "test", Value: ptr("test1")},
805 },
806 },
807 },
808 },
809 },
810 wantErrT: newErrInvalid("unsupported compression \"invalid\""),
811 },
812 {
813 name: "periodic/no-exporter",
814 reader: MetricReader{
815 Periodic: &PeriodicMetricReader{
816 Exporter: PushMetricExporter{},
817 },
818 },
819 wantErrT: newErrInvalid("no valid metric exporter"),
820 },
821 {
822 name: "periodic/console-exporter",
823 reader: MetricReader{
824 Periodic: &PeriodicMetricReader{
825 Exporter: PushMetricExporter{
826 Console: &ConsoleMetricExporter{},
827 },
828 },
829 },
830 wantReader: sdkmetric.NewPeriodicReader(consoleExporter),
831 },
832 {
833 name: "periodic/console-exporter-with-extra-options",
834 reader: MetricReader{
835 Periodic: &PeriodicMetricReader{
836 Interval: ptr(30_000),
837 Timeout: ptr(5_000),
838 Exporter: PushMetricExporter{
839 Console: &ConsoleMetricExporter{},
840 },
841 },
842 },
843 wantReader: sdkmetric.NewPeriodicReader(
844 consoleExporter,
845 sdkmetric.WithInterval(30_000*time.Millisecond),
846 sdkmetric.WithTimeout(5_000*time.Millisecond),
847 ),
848 },
849 {
850 name: "periodic/otlp_file",
851 reader: MetricReader{
852 Periodic: &PeriodicMetricReader{
853 Exporter: PushMetricExporter{
854 OTLPFileDevelopment: &ExperimentalOTLPFileMetricExporter{},
855 },
856 },
857 },
858 wantErrT: newErrInvalid("otlp_file/development"),
859 },
860 }
861 for _, tt := range testCases {
862 t.Run(tt.name, func(t *testing.T) {
863 got, err := metricReader(t.Context(), tt.reader)
864 require.ErrorIs(t, err, tt.wantErrT)
865 if tt.wantReader == nil {
866 require.Nil(t, got)
867 } else {
868 require.Equal(t, reflect.TypeOf(tt.wantReader), reflect.TypeOf(got))
869 var fieldName string
870 switch reflect.TypeOf(tt.wantReader).String() {
871 case "*metric.PeriodicReader":
872 fieldName = "exporter"
873 case "x.readerWithServer":
874 fieldName = "Reader"
875 default:
876 fieldName = "e"
877 }
878 wantExporterType := reflect.Indirect(reflect.ValueOf(tt.wantReader)).FieldByName(fieldName).Elem().Type()
879 gotExporterType := reflect.Indirect(reflect.ValueOf(got)).FieldByName(fieldName).Elem().Type()
880 require.Equal(t, wantExporterType.String(), gotExporterType.String())
881 require.NoError(t, got.Shutdown(t.Context()))
882 }
883 })
884 }
885 }
886
887 func TestView(t *testing.T) {
888 testCases := []struct {
889 name string
890 view View
891 args any
892 wantErr string
893 matchInstrument *sdkmetric.Instrument
894 wantStream sdkmetric.Stream
895 wantResult bool
896 }{
897 {
898 name: "selector/invalid_type",
899 view: View{
900 Selector: ViewSelector{
901 InstrumentType: (*InstrumentType)(ptr("invalid_type")),
902 },
903 },
904 wantErr: "view_selector: instrument_type: invalid value",
905 },
906 {
907 name: "selector/invalid_type",
908 view: View{
909 Selector: ViewSelector{},
910 },
911 wantErr: "view_selector: empty selector not supporter",
912 },
913 {
914 name: "all selectors match",
915 view: View{
916 Selector: ViewSelector{
917 InstrumentName: ptr("test_name"),
918 InstrumentType: ptr(InstrumentTypeCounter),
919 Unit: ptr("test_unit"),
920 MeterName: ptr("test_meter_name"),
921 MeterVersion: ptr("test_meter_version"),
922 MeterSchemaUrl: ptr("test_schema_url"),
923 },
924 },
925 matchInstrument: &sdkmetric.Instrument{
926 Name: "test_name",
927 Unit: "test_unit",
928 Kind: sdkmetric.InstrumentKindCounter,
929 Scope: instrumentation.Scope{
930 Name: "test_meter_name",
931 Version: "test_meter_version",
932 SchemaURL: "test_schema_url",
933 },
934 },
935 wantStream: sdkmetric.Stream{Name: "test_name", Unit: "test_unit"},
936 wantResult: true,
937 },
938 {
939 name: "all selectors no match name",
940 view: View{
941 Selector: ViewSelector{
942 InstrumentName: ptr("test_name"),
943 InstrumentType: ptr(InstrumentTypeCounter),
944 Unit: ptr("test_unit"),
945 MeterName: ptr("test_meter_name"),
946 MeterVersion: ptr("test_meter_version"),
947 MeterSchemaUrl: ptr("test_schema_url"),
948 },
949 },
950 matchInstrument: &sdkmetric.Instrument{
951 Name: "not_match",
952 Unit: "test_unit",
953 Kind: sdkmetric.InstrumentKindCounter,
954 Scope: instrumentation.Scope{
955 Name: "test_meter_name",
956 Version: "test_meter_version",
957 SchemaURL: "test_schema_url",
958 },
959 },
960 wantStream: sdkmetric.Stream{},
961 wantResult: false,
962 },
963 {
964 name: "all selectors no match unit",
965 view: View{
966 Selector: ViewSelector{
967 InstrumentName: ptr("test_name"),
968 InstrumentType: ptr(InstrumentTypeCounter),
969 Unit: ptr("test_unit"),
970 MeterName: ptr("test_meter_name"),
971 MeterVersion: ptr("test_meter_version"),
972 MeterSchemaUrl: ptr("test_schema_url"),
973 },
974 },
975 matchInstrument: &sdkmetric.Instrument{
976 Name: "test_name",
977 Unit: "not_match",
978 Kind: sdkmetric.InstrumentKindCounter,
979 Scope: instrumentation.Scope{
980 Name: "test_meter_name",
981 Version: "test_meter_version",
982 SchemaURL: "test_schema_url",
983 },
984 },
985 wantStream: sdkmetric.Stream{},
986 wantResult: false,
987 },
988 {
989 name: "all selectors no match kind",
990 view: View{
991 Selector: ViewSelector{
992 InstrumentName: ptr("test_name"),
993 InstrumentType: (*InstrumentType)(ptr("histogram")),
994 Unit: ptr("test_unit"),
995 MeterName: ptr("test_meter_name"),
996 MeterVersion: ptr("test_meter_version"),
997 MeterSchemaUrl: ptr("test_schema_url"),
998 },
999 },
1000 matchInstrument: &sdkmetric.Instrument{
1001 Name: "test_name",
1002 Unit: "test_unit",
1003 Kind: sdkmetric.InstrumentKindCounter,
1004 Scope: instrumentation.Scope{
1005 Name: "test_meter_name",
1006 Version: "test_meter_version",
1007 SchemaURL: "test_schema_url",
1008 },
1009 },
1010 wantStream: sdkmetric.Stream{},
1011 wantResult: false,
1012 },
1013 {
1014 name: "all selectors no match meter name",
1015 view: View{
1016 Selector: ViewSelector{
1017 InstrumentName: ptr("test_name"),
1018 InstrumentType: ptr(InstrumentTypeCounter),
1019 Unit: ptr("test_unit"),
1020 MeterName: ptr("test_meter_name"),
1021 MeterVersion: ptr("test_meter_version"),
1022 MeterSchemaUrl: ptr("test_schema_url"),
1023 },
1024 },
1025 matchInstrument: &sdkmetric.Instrument{
1026 Name: "test_name",
1027 Unit: "test_unit",
1028 Kind: sdkmetric.InstrumentKindCounter,
1029 Scope: instrumentation.Scope{
1030 Name: "not_match",
1031 Version: "test_meter_version",
1032 SchemaURL: "test_schema_url",
1033 },
1034 },
1035 wantStream: sdkmetric.Stream{},
1036 wantResult: false,
1037 },
1038 {
1039 name: "all selectors no match meter version",
1040 view: View{
1041 Selector: ViewSelector{
1042 InstrumentName: ptr("test_name"),
1043 InstrumentType: ptr(InstrumentTypeCounter),
1044 Unit: ptr("test_unit"),
1045 MeterName: ptr("test_meter_name"),
1046 MeterVersion: ptr("test_meter_version"),
1047 MeterSchemaUrl: ptr("test_schema_url"),
1048 },
1049 },
1050 matchInstrument: &sdkmetric.Instrument{
1051 Name: "test_name",
1052 Unit: "test_unit",
1053 Kind: sdkmetric.InstrumentKindCounter,
1054 Scope: instrumentation.Scope{
1055 Name: "test_meter_name",
1056 Version: "not_match",
1057 SchemaURL: "test_schema_url",
1058 },
1059 },
1060 wantStream: sdkmetric.Stream{},
1061 wantResult: false,
1062 },
1063 {
1064 name: "all selectors no match meter schema url",
1065 view: View{
1066 Selector: ViewSelector{
1067 InstrumentName: ptr("test_name"),
1068 InstrumentType: ptr(InstrumentTypeCounter),
1069 Unit: ptr("test_unit"),
1070 MeterName: ptr("test_meter_name"),
1071 MeterVersion: ptr("test_meter_version"),
1072 MeterSchemaUrl: ptr("test_schema_url"),
1073 },
1074 },
1075 matchInstrument: &sdkmetric.Instrument{
1076 Name: "test_name",
1077 Unit: "test_unit",
1078 Kind: sdkmetric.InstrumentKindCounter,
1079 Scope: instrumentation.Scope{
1080 Name: "test_meter_name",
1081 Version: "test_meter_version",
1082 SchemaURL: "not_match",
1083 },
1084 },
1085 wantStream: sdkmetric.Stream{},
1086 wantResult: false,
1087 },
1088 {
1089 name: "with stream",
1090 view: View{
1091 Selector: ViewSelector{
1092 InstrumentName: ptr("test_name"),
1093 Unit: ptr("test_unit"),
1094 },
1095 Stream: ViewStream{
1096 Name: ptr("new_name"),
1097 Description: ptr("new_description"),
1098 AttributeKeys: ptr(IncludeExclude{Included: []string{"foo", "bar"}}),
1099 Aggregation: &Aggregation{Sum: make(SumAggregation)},
1100 },
1101 },
1102 matchInstrument: &sdkmetric.Instrument{
1103 Name: "test_name",
1104 Description: "test_description",
1105 Unit: "test_unit",
1106 },
1107 wantStream: sdkmetric.Stream{
1108 Name: "new_name",
1109 Description: "new_description",
1110 Unit: "test_unit",
1111 Aggregation: sdkmetric.AggregationSum{},
1112 },
1113 wantResult: true,
1114 },
1115 }
1116 for _, tt := range testCases {
1117 t.Run(tt.name, func(t *testing.T) {
1118 got, err := view(tt.view)
1119 if tt.wantErr != "" {
1120 require.EqualError(t, err, tt.wantErr)
1121 require.Nil(t, got)
1122 } else {
1123 require.NoError(t, err)
1124 gotStream, gotResult := got(*tt.matchInstrument)
1125 // Remove filter, since it cannot be compared
1126 gotStream.AttributeFilter = nil
1127 require.Equal(t, tt.wantStream, gotStream)
1128 require.Equal(t, tt.wantResult, gotResult)
1129 }
1130 })
1131 }
1132 }
1133
1134 func TestInstrumentType(t *testing.T) {
1135 testCases := []struct {
1136 name string
1137 instType *InstrumentType
1138 wantErr error
1139 wantKind sdkmetric.InstrumentKind
1140 }{
1141 {
1142 name: "nil",
1143 wantKind: sdkmetric.InstrumentKind(0),
1144 },
1145 {
1146 name: "counter",
1147 instType: ptr(InstrumentTypeCounter),
1148 wantKind: sdkmetric.InstrumentKindCounter,
1149 },
1150 {
1151 name: "up_down_counter",
1152 instType: ptr(InstrumentTypeUpDownCounter),
1153 wantKind: sdkmetric.InstrumentKindUpDownCounter,
1154 },
1155 {
1156 name: "histogram",
1157 instType: ptr(InstrumentTypeHistogram),
1158 wantKind: sdkmetric.InstrumentKindHistogram,
1159 },
1160 {
1161 name: "observable_counter",
1162 instType: ptr(InstrumentTypeObservableCounter),
1163 wantKind: sdkmetric.InstrumentKindObservableCounter,
1164 },
1165 {
1166 name: "observable_up_down_counter",
1167 instType: ptr(InstrumentTypeObservableUpDownCounter),
1168 wantKind: sdkmetric.InstrumentKindObservableUpDownCounter,
1169 },
1170 {
1171 name: "observable_gauge",
1172 instType: ptr(InstrumentTypeObservableGauge),
1173 wantKind: sdkmetric.InstrumentKindObservableGauge,
1174 },
1175 {
1176 name: "invalid",
1177 instType: (*InstrumentType)(ptr("invalid")),
1178 wantErr: errors.New("instrument_type: invalid value"),
1179 },
1180 }
1181 for _, tt := range testCases {
1182 t.Run(tt.name, func(t *testing.T) {
1183 got, err := instrumentKind(tt.instType)
1184 if tt.wantErr != nil {
1185 require.Equal(t, tt.wantErr, err)
1186 require.Zero(t, got)
1187 } else {
1188 require.NoError(t, err)
1189 require.Equal(t, tt.wantKind, got)
1190 }
1191 })
1192 }
1193 }
1194
1195 func TestAggregation(t *testing.T) {
1196 testCases := []struct {
1197 name string
1198 aggregation *Aggregation
1199 wantAggregation sdkmetric.Aggregation
1200 }{
1201 {
1202 name: "nil",
1203 wantAggregation: nil,
1204 },
1205 {
1206 name: "empty",
1207 aggregation: &Aggregation{},
1208 wantAggregation: nil,
1209 },
1210 {
1211 name: "Base2ExponentialBucketHistogram empty",
1212 aggregation: &Aggregation{
1213 Base2ExponentialBucketHistogram: &Base2ExponentialBucketHistogramAggregation{},
1214 },
1215 wantAggregation: sdkmetric.AggregationBase2ExponentialHistogram{
1216 MaxSize: 0,
1217 MaxScale: 0,
1218 NoMinMax: true,
1219 },
1220 },
1221 {
1222 name: "Base2ExponentialBucketHistogram",
1223 aggregation: &Aggregation{
1224 Base2ExponentialBucketHistogram: &Base2ExponentialBucketHistogramAggregation{
1225 MaxSize: ptr(2),
1226 MaxScale: ptr(3),
1227 RecordMinMax: ptr(true),
1228 },
1229 },
1230 wantAggregation: sdkmetric.AggregationBase2ExponentialHistogram{
1231 MaxSize: 2,
1232 MaxScale: 3,
1233 NoMinMax: false,
1234 },
1235 },
1236 {
1237 name: "Default",
1238 aggregation: &Aggregation{
1239 Default: make(DefaultAggregation),
1240 },
1241 wantAggregation: nil,
1242 },
1243 {
1244 name: "Drop",
1245 aggregation: &Aggregation{
1246 Drop: make(DropAggregation),
1247 },
1248 wantAggregation: sdkmetric.AggregationDrop{},
1249 },
1250 {
1251 name: "ExplicitBucketHistogram empty",
1252 aggregation: &Aggregation{
1253 ExplicitBucketHistogram: &ExplicitBucketHistogramAggregation{},
1254 },
1255 wantAggregation: sdkmetric.AggregationExplicitBucketHistogram{
1256 Boundaries: nil,
1257 NoMinMax: true,
1258 },
1259 },
1260 {
1261 name: "ExplicitBucketHistogram",
1262 aggregation: &Aggregation{
1263 ExplicitBucketHistogram: &ExplicitBucketHistogramAggregation{
1264 Boundaries: []float64{1, 2, 3},
1265 RecordMinMax: ptr(true),
1266 },
1267 },
1268 wantAggregation: sdkmetric.AggregationExplicitBucketHistogram{
1269 Boundaries: []float64{1, 2, 3},
1270 NoMinMax: false,
1271 },
1272 },
1273 {
1274 name: "LastValue",
1275 aggregation: &Aggregation{
1276 LastValue: make(LastValueAggregation),
1277 },
1278 wantAggregation: sdkmetric.AggregationLastValue{},
1279 },
1280 {
1281 name: "Sum",
1282 aggregation: &Aggregation{
1283 Sum: make(SumAggregation),
1284 },
1285 wantAggregation: sdkmetric.AggregationSum{},
1286 },
1287 }
1288 for _, tt := range testCases {
1289 t.Run(tt.name, func(t *testing.T) {
1290 got := aggregation(tt.aggregation)
1291 require.Equal(t, tt.wantAggregation, got)
1292 })
1293 }
1294 }
1295
1296 func TestNewIncludeExcludeFilter(t *testing.T) {
1297 testCases := []struct {
1298 name string
1299 attributeKeys *IncludeExclude
1300 wantPass []string
1301 wantFail []string
1302 }{
1303 {
1304 name: "empty",
1305 attributeKeys: nil,
1306 wantPass: []string{"foo", "bar"},
1307 wantFail: nil,
1308 },
1309 {
1310 name: "filter-with-include",
1311 attributeKeys: ptr(IncludeExclude{
1312 Included: []string{"foo"},
1313 }),
1314 wantPass: []string{"foo"},
1315 wantFail: []string{"bar"},
1316 },
1317 {
1318 name: "filter-with-exclude",
1319 attributeKeys: ptr(IncludeExclude{
1320 Excluded: []string{"foo"},
1321 }),
1322 wantPass: []string{"bar"},
1323 wantFail: []string{"foo"},
1324 },
1325 {
1326 name: "filter-with-include-and-exclude",
1327 attributeKeys: ptr(IncludeExclude{
1328 Included: []string{"bar"},
1329 Excluded: []string{"foo"},
1330 }),
1331 wantPass: []string{"bar"},
1332 wantFail: []string{"foo"},
1333 },
1334 }
1335 for _, tt := range testCases {
1336 t.Run(tt.name, func(t *testing.T) {
1337 got, err := newIncludeExcludeFilter(tt.attributeKeys)
1338 require.NoError(t, err)
1339 for _, pass := range tt.wantPass {
1340 require.True(t, got(attribute.KeyValue{Key: attribute.Key(pass), Value: attribute.StringValue("")}))
1341 }
1342 for _, fail := range tt.wantFail {
1343 require.False(t, got(attribute.KeyValue{Key: attribute.Key(fail), Value: attribute.StringValue("")}))
1344 }
1345 })
1346 }
1347 }
1348
1349 func TestNewIncludeExcludeFilterError(t *testing.T) {
1350 _, err := newIncludeExcludeFilter(ptr(IncludeExclude{
1351 Included: []string{"foo"},
1352 Excluded: []string{"foo"},
1353 }))
1354 require.Equal(t, fmt.Errorf("attribute cannot be in both include and exclude list: foo"), err)
1355 }
1356
1357 func TestPrometheusReaderOpts(t *testing.T) {
1358 testCases := []struct {
1359 name string
1360 cfg ExperimentalPrometheusMetricExporter
1361 wantOptions int
1362 }{
1363 {
1364 name: "no options",
1365 cfg: ExperimentalPrometheusMetricExporter{},
1366 wantOptions: 0,
1367 },
1368 {
1369 name: "all set",
1370 cfg: ExperimentalPrometheusMetricExporter{
1371 WithoutScopeInfo: ptr(true),
1372 TranslationStrategy: ptr(ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithoutSuffixes),
1373 WithResourceConstantLabels: &IncludeExclude{},
1374 },
1375 wantOptions: 3,
1376 },
1377 {
1378 name: "all set false",
1379 cfg: ExperimentalPrometheusMetricExporter{
1380 WithoutScopeInfo: ptr(false),
1381 TranslationStrategy: ptr(ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithSuffixes),
1382 WithResourceConstantLabels: &IncludeExclude{},
1383 },
1384 wantOptions: 2,
1385 },
1386 }
1387 for _, tt := range testCases {
1388 t.Run(tt.name, func(t *testing.T) {
1389 opts, err := prometheusReaderOpts(&tt.cfg)
1390 require.NoError(t, err)
1391 require.Len(t, opts, tt.wantOptions)
1392 })
1393 }
1394 }
1395
1396 func TestPrometheusIPv6(t *testing.T) {
1397 tests := []struct {
1398 name string
1399 host string
1400 }{
1401 {
1402 name: "IPv6",
1403 host: "::1",
1404 },
1405 {
1406 name: "[IPv6]",
1407 host: "[::1]",
1408 },
1409 }
1410 for _, tt := range tests {
1411 t.Run(tt.name, func(t *testing.T) {
1412 port := 0
1413 cfg := ExperimentalPrometheusMetricExporter{
1414 Host: &tt.host,
1415 Port: &port,
1416 WithoutScopeInfo: ptr(true),
1417 TranslationStrategy: ptr(ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithSuffixes),
1418 WithResourceConstantLabels: &IncludeExclude{},
1419 }
1420
1421 rs, err := prometheusReader(t.Context(), &cfg)
1422 t.Cleanup(func() {
1423 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
1424 require.NoError(t, rs.Shutdown(context.Background()))
1425 })
1426 require.NoError(t, err)
1427
1428 hServ := rs.(readerWithServer).server
1429 assert.True(t, strings.HasPrefix(hServ.Addr, "[::1]:"))
1430
1431 req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+hServ.Addr+"/metrics", http.NoBody)
1432 require.NoError(t, err)
1433
1434 resp, err := http.DefaultClient.Do(req)
1435 t.Cleanup(func() {
1436 require.NoError(t, resp.Body.Close())
1437 })
1438 require.NoError(t, err)
1439 assert.Equal(t, http.StatusOK, resp.StatusCode)
1440 })
1441 }
1442 }
1443
1444 func Test_otlpGRPCMetricExporter(t *testing.T) {
1445 if runtime.GOOS == "windows" {
1446 // TODO (#7446): Fix the flakiness on Windows.
1447 t.Skip("Test is flaky on Windows.")
1448 }
1449 type args struct {
1450 ctx context.Context
1451 otlpConfig *OTLPGrpcMetricExporter
1452 }
1453 tests := []struct {
1454 name string
1455 args args
1456 grpcServerOpts func() ([]grpc.ServerOption, error)
1457 }{
1458 {
1459 name: "no TLS config",
1460 args: args{
1461 ctx: t.Context(),
1462 otlpConfig: &OTLPGrpcMetricExporter{
1463 Compression: ptr("gzip"),
1464 Timeout: ptr(5000),
1465 Tls: &GrpcTls{
1466 Insecure: ptr(true),
1467 },
1468 Headers: []NameStringValuePair{
1469 {Name: "test", Value: ptr("test1")},
1470 },
1471 },
1472 },
1473 grpcServerOpts: func() ([]grpc.ServerOption, error) {
1474 return []grpc.ServerOption{}, nil
1475 },
1476 },
1477 {
1478 name: "with TLS config",
1479 args: args{
1480 ctx: t.Context(),
1481 otlpConfig: &OTLPGrpcMetricExporter{
1482 Compression: ptr("gzip"),
1483 Timeout: ptr(5000),
1484 Tls: &GrpcTls{
1485 CaFile: ptr("../testdata/server-certs/server.crt"),
1486 },
1487 Headers: []NameStringValuePair{
1488 {Name: "test", Value: ptr("test1")},
1489 },
1490 },
1491 },
1492 grpcServerOpts: func() ([]grpc.ServerOption, error) {
1493 opts := []grpc.ServerOption{}
1494 tlsCreds, err := credentials.NewServerTLSFromFile("../testdata/server-certs/server.crt", "../testdata/server-certs/server.key")
1495 if err != nil {
1496 return nil, err
1497 }
1498 opts = append(opts, grpc.Creds(tlsCreds))
1499 return opts, nil
1500 },
1501 },
1502 {
1503 name: "with TLS config and client key",
1504 args: args{
1505 ctx: t.Context(),
1506 otlpConfig: &OTLPGrpcMetricExporter{
1507 Compression: ptr("gzip"),
1508 Timeout: ptr(5000),
1509 Tls: &GrpcTls{
1510 CaFile: ptr("../testdata/server-certs/server.crt"),
1511 KeyFile: ptr("../testdata/client-certs/client.key"),
1512 CertFile: ptr("../testdata/client-certs/client.crt"),
1513 },
1514 Headers: []NameStringValuePair{
1515 {Name: "test", Value: ptr("test1")},
1516 },
1517 },
1518 },
1519 grpcServerOpts: func() ([]grpc.ServerOption, error) {
1520 opts := []grpc.ServerOption{}
1521 cert, err := tls.LoadX509KeyPair("../testdata/server-certs/server.crt", "../testdata/server-certs/server.key")
1522 if err != nil {
1523 return nil, err
1524 }
1525 caCert, err := os.ReadFile("../testdata/ca.crt")
1526 if err != nil {
1527 return nil, err
1528 }
1529 caCertPool := x509.NewCertPool()
1530 caCertPool.AppendCertsFromPEM(caCert)
1531 tlsCreds := credentials.NewTLS(&tls.Config{
1532 Certificates: []tls.Certificate{cert},
1533 ClientCAs: caCertPool,
1534 ClientAuth: tls.RequireAndVerifyClientCert,
1535 })
1536 opts = append(opts, grpc.Creds(tlsCreds))
1537 return opts, nil
1538 },
1539 },
1540 }
1541 for _, tt := range tests {
1542 t.Run(tt.name, func(t *testing.T) {
1543 n, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp4", "localhost:0")
1544 require.NoError(t, err)
1545
1546 // We need to manually construct the endpoint using the port on which the server is listening.
1547 //
1548 // n.Addr() always returns 127.0.0.1 instead of localhost.
1549 // But our certificate is created with CN as 'localhost', not '127.0.0.1'.
1550 // So we have to manually form the endpoint as "localhost:<port>".
1551 _, port, err := net.SplitHostPort(n.Addr().String())
1552 require.NoError(t, err)
1553 tt.args.otlpConfig.Endpoint = ptr("localhost:" + port)
1554
1555 serverOpts, err := tt.grpcServerOpts()
1556 require.NoError(t, err)
1557
1558 startGRPCMetricCollector(t, n, serverOpts)
1559
1560 exporter, err := otlpGRPCMetricExporter(tt.args.ctx, tt.args.otlpConfig)
1561 require.NoError(t, err)
1562
1563 res, err := resource.New(t.Context())
1564 require.NoError(t, err)
1565
1566 assert.EventuallyWithT(t, func(collect *assert.CollectT) {
1567 assert.NoError(collect, exporter.Export(context.Background(), &metricdata.ResourceMetrics{ //nolint:usetesting // required to avoid getting a canceled context.
1568 Resource: res,
1569 ScopeMetrics: []metricdata.ScopeMetrics{
1570 {
1571 Metrics: []metricdata.Metrics{
1572 {
1573 Name: "test-metric",
1574 Data: metricdata.Gauge[int64]{
1575 DataPoints: []metricdata.DataPoint[int64]{
1576 {
1577 Value: 1,
1578 },
1579 },
1580 },
1581 },
1582 },
1583 },
1584 },
1585 }))
1586 }, 10*time.Second, 1*time.Second)
1587 })
1588 }
1589 }
1590
1591 // grpcMetricCollector is an OTLP gRPC server that collects all requests it receives.
1592 type grpcMetricCollector struct {
1593 v1.UnimplementedMetricsServiceServer
1594 }
1595
1596 var _ v1.MetricsServiceServer = (*grpcMetricCollector)(nil)
1597
1598 // startGRPCMetricCollector returns a *grpcMetricCollector that is listening at the provided
1599 // endpoint.
1600 //
1601 // If endpoint is an empty string, the returned collector will be listening on
1602 // the localhost interface at an OS chosen port.
1603 func startGRPCMetricCollector(t *testing.T, listener net.Listener, serverOptions []grpc.ServerOption) {
1604 srv := grpc.NewServer(serverOptions...)
1605 c := &grpcMetricCollector{}
1606
1607 v1.RegisterMetricsServiceServer(srv, c)
1608
1609 errCh := make(chan error, 1)
1610 go func() { errCh <- srv.Serve(listener) }()
1611
1612 t.Cleanup(func() {
1613 srv.GracefulStop()
1614 if err := <-errCh; err != nil && !errors.Is(err, grpc.ErrServerStopped) {
1615 assert.NoError(t, err)
1616 }
1617 })
1618 }
1619
1620 // Export handles the export req.
1621 func (*grpcMetricCollector) Export(
1622 _ context.Context,
1623 _ *v1.ExportMetricsServiceRequest,
1624 ) (*v1.ExportMetricsServiceResponse, error) {
1625 return &v1.ExportMetricsServiceResponse{}, nil
1626 }