Debian Codegraph @

otelconf/v0.2.0/metric_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelconf
5
6 import (
7 "bytes"
8 "context"
9 "errors"
10 "net/http"
11 "net/url"
12 "reflect"
13 "strings"
14 "testing"
15 "time"
16
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19 "go.opentelemetry.io/otel/attribute"
20 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
21 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
22 otelprom "go.opentelemetry.io/otel/exporters/prometheus"
23 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
24 "go.opentelemetry.io/otel/metric"
25 "go.opentelemetry.io/otel/metric/noop"
26 "go.opentelemetry.io/otel/sdk/instrumentation"
27 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
28 "go.opentelemetry.io/otel/sdk/resource"
29 )
30
31 func TestMeterProvider(t *testing.T) {
32 tests := []struct {
33 name string
34 cfg configOptions
35 wantProvider metric.MeterProvider
36 wantErr error
37 }{
38 {
39 name: "no-meter-provider-configured",
40 wantProvider: noop.NewMeterProvider(),
41 },
42 {
43 name: "error-in-config",
44 cfg: configOptions{
45 opentelemetryConfig: OpenTelemetryConfiguration{
46 MeterProvider: &MeterProvider{
47 Readers: []MetricReader{
48 {
49 Periodic: &PeriodicMetricReader{},
50 Pull: &PullMetricReader{},
51 },
52 },
53 },
54 },
55 },
56 wantProvider: noop.NewMeterProvider(),
57 wantErr: errors.Join(errors.New("must not specify multiple metric reader type")),
58 },
59 {
60 name: "multiple-errors-in-config",
61 cfg: configOptions{
62 opentelemetryConfig: OpenTelemetryConfiguration{
63 MeterProvider: &MeterProvider{
64 Readers: []MetricReader{
65 {
66 Periodic: &PeriodicMetricReader{},
67 Pull: &PullMetricReader{},
68 },
69 {
70 Periodic: &PeriodicMetricReader{
71 Exporter: MetricExporter{
72 Console: Console{},
73 OTLP: &OTLPMetric{},
74 },
75 },
76 },
77 },
78 },
79 },
80 },
81 wantProvider: noop.NewMeterProvider(),
82 wantErr: errors.Join(errors.New("must not specify multiple metric reader type"), errors.New("must not specify multiple exporters")),
83 },
84 }
85 for _, tt := range tests {
86 mp, shutdown, err := meterProvider(tt.cfg, resource.Default())
87 require.Equal(t, tt.wantProvider, mp)
88 assert.Equal(t, tt.wantErr, err)
89 require.NoError(t, shutdown(t.Context()))
90 }
91 }
92
93 func TestReader(t *testing.T) {
94 consoleExporter, err := stdoutmetric.New(
95 stdoutmetric.WithPrettyPrint(),
96 )
97 require.NoError(t, err)
98 ctx := t.Context()
99 otlpGRPCExporter, err := otlpmetricgrpc.New(ctx)
100 require.NoError(t, err)
101 otlpHTTPExporter, err := otlpmetrichttp.New(ctx)
102 require.NoError(t, err)
103 promExporter, err := otelprom.New()
104 require.NoError(t, err)
105 testCases := []struct {
106 name string
107 reader MetricReader
108 args any
109 wantErr error
110 wantReader sdkmetric.Reader
111 }{
112 {
113 name: "no reader",
114 wantErr: errors.New("no valid metric reader"),
115 },
116 {
117 name: "pull/no-exporter",
118 reader: MetricReader{
119 Pull: &PullMetricReader{},
120 },
121 wantErr: errors.New("no valid metric exporter"),
122 },
123 {
124 name: "pull/prometheus-no-host",
125 reader: MetricReader{
126 Pull: &PullMetricReader{
127 Exporter: MetricExporter{
128 Prometheus: &Prometheus{},
129 },
130 },
131 },
132 wantErr: errors.New("host must be specified"),
133 },
134 {
135 name: "pull/prometheus-no-port",
136 reader: MetricReader{
137 Pull: &PullMetricReader{
138 Exporter: MetricExporter{
139 Prometheus: &Prometheus{
140 Host: ptr("localhost"),
141 },
142 },
143 },
144 },
145 wantErr: errors.New("port must be specified"),
146 },
147 {
148 name: "pull/prometheus",
149 reader: MetricReader{
150 Pull: &PullMetricReader{
151 Exporter: MetricExporter{
152 Prometheus: &Prometheus{
153 Host: ptr("localhost"),
154 Port: ptr(0),
155 WithoutScopeInfo: ptr(true),
156 WithoutUnits: ptr(true),
157 WithoutTypeSuffix: ptr(true),
158 WithResourceConstantLabels: &IncludeExclude{
159 Included: []string{"include"},
160 Excluded: []string{"exclude"},
161 },
162 },
163 },
164 },
165 },
166 wantReader: readerWithServer{promExporter, nil},
167 },
168 {
169 name: "periodic/otlp-exporter-invalid-protocol",
170 reader: MetricReader{
171 Periodic: &PeriodicMetricReader{
172 Exporter: MetricExporter{
173 OTLP: &OTLPMetric{
174 Protocol: "http/invalid",
175 },
176 },
177 },
178 },
179 wantErr: errors.New("unsupported protocol \"http/invalid\""),
180 },
181 {
182 name: "periodic/otlp-grpc-exporter",
183 reader: MetricReader{
184 Periodic: &PeriodicMetricReader{
185 Exporter: MetricExporter{
186 OTLP: &OTLPMetric{
187 Protocol: "grpc/protobuf",
188 Endpoint: "http://localhost:4318",
189 Compression: ptr("gzip"),
190 Timeout: ptr(1000),
191 Headers: map[string]string{
192 "test": "test1",
193 },
194 },
195 },
196 },
197 },
198 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
199 },
200 {
201 name: "periodic/otlp-grpc-exporter-with-path",
202 reader: MetricReader{
203 Periodic: &PeriodicMetricReader{
204 Exporter: MetricExporter{
205 OTLP: &OTLPMetric{
206 Protocol: "grpc/protobuf",
207 Endpoint: "http://localhost:4318/path/123",
208 Compression: ptr("gzip"),
209 Timeout: ptr(1000),
210 Headers: map[string]string{
211 "test": "test1",
212 },
213 },
214 },
215 },
216 },
217 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
218 },
219 {
220 name: "periodic/otlp-grpc-exporter-no-endpoint",
221 reader: MetricReader{
222 Periodic: &PeriodicMetricReader{
223 Exporter: MetricExporter{
224 OTLP: &OTLPMetric{
225 Protocol: "grpc/protobuf",
226 Compression: ptr("gzip"),
227 Timeout: ptr(1000),
228 Headers: map[string]string{
229 "test": "test1",
230 },
231 },
232 },
233 },
234 },
235 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
236 },
237 {
238 name: "periodic/otlp-grpc-exporter-no-scheme",
239 reader: MetricReader{
240 Periodic: &PeriodicMetricReader{
241 Exporter: MetricExporter{
242 OTLP: &OTLPMetric{
243 Protocol: "grpc/protobuf",
244 Endpoint: "localhost:4318",
245 Compression: ptr("gzip"),
246 Timeout: ptr(1000),
247 Headers: map[string]string{
248 "test": "test1",
249 },
250 },
251 },
252 },
253 },
254 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
255 },
256 {
257 name: "periodic/otlp-grpc-invalid-endpoint",
258 reader: MetricReader{
259 Periodic: &PeriodicMetricReader{
260 Exporter: MetricExporter{
261 OTLP: &OTLPMetric{
262 Protocol: "grpc/protobuf",
263 Endpoint: " ",
264 Compression: ptr("gzip"),
265 Timeout: ptr(1000),
266 Headers: map[string]string{
267 "test": "test1",
268 },
269 },
270 },
271 },
272 },
273 wantErr: &url.Error{Op: "parse", URL: " ", Err: errors.New("invalid URI for request")},
274 },
275 {
276 name: "periodic/otlp-grpc-none-compression",
277 reader: MetricReader{
278 Periodic: &PeriodicMetricReader{
279 Exporter: MetricExporter{
280 OTLP: &OTLPMetric{
281 Protocol: "grpc/protobuf",
282 Endpoint: "localhost:4318",
283 Compression: ptr("none"),
284 Timeout: ptr(1000),
285 Headers: map[string]string{
286 "test": "test1",
287 },
288 },
289 },
290 },
291 },
292 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
293 },
294 {
295 name: "periodic/otlp-grpc-delta-temporality",
296 reader: MetricReader{
297 Periodic: &PeriodicMetricReader{
298 Exporter: MetricExporter{
299 OTLP: &OTLPMetric{
300 Protocol: "grpc/protobuf",
301 Endpoint: "localhost:4318",
302 Compression: ptr("none"),
303 Timeout: ptr(1000),
304 Headers: map[string]string{
305 "test": "test1",
306 },
307 TemporalityPreference: ptr("delta"),
308 },
309 },
310 },
311 },
312 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
313 },
314 {
315 name: "periodic/otlp-grpc-cumulative-temporality",
316 reader: MetricReader{
317 Periodic: &PeriodicMetricReader{
318 Exporter: MetricExporter{
319 OTLP: &OTLPMetric{
320 Protocol: "grpc/protobuf",
321 Endpoint: "localhost:4318",
322 Compression: ptr("none"),
323 Timeout: ptr(1000),
324 Headers: map[string]string{
325 "test": "test1",
326 },
327 TemporalityPreference: ptr("cumulative"),
328 },
329 },
330 },
331 },
332 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
333 },
334 {
335 name: "periodic/otlp-grpc-lowmemory-temporality",
336 reader: MetricReader{
337 Periodic: &PeriodicMetricReader{
338 Exporter: MetricExporter{
339 OTLP: &OTLPMetric{
340 Protocol: "grpc/protobuf",
341 Endpoint: "localhost:4318",
342 Compression: ptr("none"),
343 Timeout: ptr(1000),
344 Headers: map[string]string{
345 "test": "test1",
346 },
347 TemporalityPreference: ptr("lowmemory"),
348 },
349 },
350 },
351 },
352 wantReader: sdkmetric.NewPeriodicReader(otlpGRPCExporter),
353 },
354 {
355 name: "periodic/otlp-grpc-invalid-temporality",
356 reader: MetricReader{
357 Periodic: &PeriodicMetricReader{
358 Exporter: MetricExporter{
359 OTLP: &OTLPMetric{
360 Protocol: "grpc/protobuf",
361 Endpoint: "localhost:4318",
362 Compression: ptr("none"),
363 Timeout: ptr(1000),
364 Headers: map[string]string{
365 "test": "test1",
366 },
367 TemporalityPreference: ptr("invalid"),
368 },
369 },
370 },
371 },
372 wantErr: errors.New("unsupported temporality preference \"invalid\""),
373 },
374 {
375 name: "periodic/otlp-grpc-invalid-compression",
376 reader: MetricReader{
377 Periodic: &PeriodicMetricReader{
378 Exporter: MetricExporter{
379 OTLP: &OTLPMetric{
380 Protocol: "grpc/protobuf",
381 Endpoint: "localhost:4318",
382 Compression: ptr("invalid"),
383 Timeout: ptr(1000),
384 Headers: map[string]string{
385 "test": "test1",
386 },
387 },
388 },
389 },
390 },
391 wantErr: errors.New("unsupported compression \"invalid\""),
392 },
393 {
394 name: "periodic/otlp-http-exporter",
395 reader: MetricReader{
396 Periodic: &PeriodicMetricReader{
397 Exporter: MetricExporter{
398 OTLP: &OTLPMetric{
399 Protocol: "http/protobuf",
400 Endpoint: "http://localhost:4318",
401 Compression: ptr("gzip"),
402 Timeout: ptr(1000),
403 Headers: map[string]string{
404 "test": "test1",
405 },
406 },
407 },
408 },
409 },
410 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
411 },
412 {
413 name: "periodic/otlp-http-exporter-with-path",
414 reader: MetricReader{
415 Periodic: &PeriodicMetricReader{
416 Exporter: MetricExporter{
417 OTLP: &OTLPMetric{
418 Protocol: "http/protobuf",
419 Endpoint: "http://localhost:4318/path/123",
420 Compression: ptr("gzip"),
421 Timeout: ptr(1000),
422 Headers: map[string]string{
423 "test": "test1",
424 },
425 },
426 },
427 },
428 },
429 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
430 },
431 {
432 name: "periodic/otlp-http-exporter-no-endpoint",
433 reader: MetricReader{
434 Periodic: &PeriodicMetricReader{
435 Exporter: MetricExporter{
436 OTLP: &OTLPMetric{
437 Protocol: "http/protobuf",
438 Compression: ptr("gzip"),
439 Timeout: ptr(1000),
440 Headers: map[string]string{
441 "test": "test1",
442 },
443 },
444 },
445 },
446 },
447 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
448 },
449 {
450 name: "periodic/otlp-http-exporter-no-scheme",
451 reader: MetricReader{
452 Periodic: &PeriodicMetricReader{
453 Exporter: MetricExporter{
454 OTLP: &OTLPMetric{
455 Protocol: "http/protobuf",
456 Endpoint: "localhost:4318",
457 Compression: ptr("gzip"),
458 Timeout: ptr(1000),
459 Headers: map[string]string{
460 "test": "test1",
461 },
462 },
463 },
464 },
465 },
466 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
467 },
468 {
469 name: "periodic/otlp-http-invalid-endpoint",
470 reader: MetricReader{
471 Periodic: &PeriodicMetricReader{
472 Exporter: MetricExporter{
473 OTLP: &OTLPMetric{
474 Protocol: "http/protobuf",
475 Endpoint: " ",
476 Compression: ptr("gzip"),
477 Timeout: ptr(1000),
478 Headers: map[string]string{
479 "test": "test1",
480 },
481 },
482 },
483 },
484 },
485 wantErr: &url.Error{Op: "parse", URL: " ", Err: errors.New("invalid URI for request")},
486 },
487 {
488 name: "periodic/otlp-http-none-compression",
489 reader: MetricReader{
490 Periodic: &PeriodicMetricReader{
491 Exporter: MetricExporter{
492 OTLP: &OTLPMetric{
493 Protocol: "http/protobuf",
494 Endpoint: "localhost:4318",
495 Compression: ptr("none"),
496 Timeout: ptr(1000),
497 Headers: map[string]string{
498 "test": "test1",
499 },
500 },
501 },
502 },
503 },
504 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
505 },
506 {
507 name: "periodic/otlp-http-cumulative-temporality",
508 reader: MetricReader{
509 Periodic: &PeriodicMetricReader{
510 Exporter: MetricExporter{
511 OTLP: &OTLPMetric{
512 Protocol: "http/protobuf",
513 Endpoint: "localhost:4318",
514 Compression: ptr("none"),
515 Timeout: ptr(1000),
516 Headers: map[string]string{
517 "test": "test1",
518 },
519 TemporalityPreference: ptr("cumulative"),
520 },
521 },
522 },
523 },
524 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
525 },
526 {
527 name: "periodic/otlp-http-lowmemory-temporality",
528 reader: MetricReader{
529 Periodic: &PeriodicMetricReader{
530 Exporter: MetricExporter{
531 OTLP: &OTLPMetric{
532 Protocol: "http/protobuf",
533 Endpoint: "localhost:4318",
534 Compression: ptr("none"),
535 Timeout: ptr(1000),
536 Headers: map[string]string{
537 "test": "test1",
538 },
539 TemporalityPreference: ptr("lowmemory"),
540 },
541 },
542 },
543 },
544 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
545 },
546 {
547 name: "periodic/otlp-http-delta-temporality",
548 reader: MetricReader{
549 Periodic: &PeriodicMetricReader{
550 Exporter: MetricExporter{
551 OTLP: &OTLPMetric{
552 Protocol: "http/protobuf",
553 Endpoint: "localhost:4318",
554 Compression: ptr("none"),
555 Timeout: ptr(1000),
556 Headers: map[string]string{
557 "test": "test1",
558 },
559 TemporalityPreference: ptr("delta"),
560 },
561 },
562 },
563 },
564 wantReader: sdkmetric.NewPeriodicReader(otlpHTTPExporter),
565 },
566 {
567 name: "periodic/otlp-http-invalid-temporality",
568 reader: MetricReader{
569 Periodic: &PeriodicMetricReader{
570 Exporter: MetricExporter{
571 OTLP: &OTLPMetric{
572 Protocol: "http/protobuf",
573 Endpoint: "localhost:4318",
574 Compression: ptr("none"),
575 Timeout: ptr(1000),
576 Headers: map[string]string{
577 "test": "test1",
578 },
579 TemporalityPreference: ptr("invalid"),
580 },
581 },
582 },
583 },
584 wantErr: errors.New("unsupported temporality preference \"invalid\""),
585 },
586 {
587 name: "periodic/otlp-http-invalid-compression",
588 reader: MetricReader{
589 Periodic: &PeriodicMetricReader{
590 Exporter: MetricExporter{
591 OTLP: &OTLPMetric{
592 Protocol: "http/protobuf",
593 Endpoint: "localhost:4318",
594 Compression: ptr("invalid"),
595 Timeout: ptr(1000),
596 Headers: map[string]string{
597 "test": "test1",
598 },
599 },
600 },
601 },
602 },
603 wantErr: errors.New("unsupported compression \"invalid\""),
604 },
605 {
606 name: "periodic/no-exporter",
607 reader: MetricReader{
608 Periodic: &PeriodicMetricReader{
609 Exporter: MetricExporter{},
610 },
611 },
612 wantErr: errors.New("no valid metric exporter"),
613 },
614 {
615 name: "periodic/console-exporter",
616 reader: MetricReader{
617 Periodic: &PeriodicMetricReader{
618 Exporter: MetricExporter{
619 Console: Console{},
620 },
621 },
622 },
623 wantReader: sdkmetric.NewPeriodicReader(consoleExporter),
624 },
625 {
626 name: "periodic/console-exporter-with-extra-options",
627 reader: MetricReader{
628 Periodic: &PeriodicMetricReader{
629 Interval: ptr(30_000),
630 Timeout: ptr(5_000),
631 Exporter: MetricExporter{
632 Console: Console{},
633 },
634 },
635 },
636 wantReader: sdkmetric.NewPeriodicReader(
637 consoleExporter,
638 sdkmetric.WithInterval(30_000*time.Millisecond),
639 sdkmetric.WithTimeout(5_000*time.Millisecond),
640 ),
641 },
642 }
643 for _, tt := range testCases {
644 t.Run(tt.name, func(t *testing.T) {
645 got, err := metricReader(t.Context(), tt.reader)
646 require.Equal(t, tt.wantErr, err)
647 if tt.wantReader == nil {
648 require.Nil(t, got)
649 } else {
650 require.Equal(t, reflect.TypeOf(tt.wantReader), reflect.TypeOf(got))
651 var fieldName string
652 switch reflect.TypeOf(tt.wantReader).String() {
653 case "*metric.PeriodicReader":
654 fieldName = "exporter"
655 case "otelconf.readerWithServer":
656 fieldName = "Reader"
657 default:
658 fieldName = "e"
659 }
660 wantExporterType := reflect.Indirect(reflect.ValueOf(tt.wantReader)).FieldByName(fieldName).Elem().Type()
661 gotExporterType := reflect.Indirect(reflect.ValueOf(got)).FieldByName(fieldName).Elem().Type()
662 require.Equal(t, wantExporterType.String(), gotExporterType.String())
663 require.NoError(t, got.Shutdown(t.Context()))
664 }
665 })
666 }
667 }
668
669 func TestView(t *testing.T) {
670 testCases := []struct {
671 name string
672 view View
673 args any
674 wantErr string
675 matchInstrument *sdkmetric.Instrument
676 wantStream sdkmetric.Stream
677 wantResult bool
678 }{
679 {
680 name: "no selector",
681 wantErr: "view: no selector provided",
682 },
683 {
684 name: "selector/invalid_type",
685 view: View{
686 Selector: &ViewSelector{
687 InstrumentType: (*ViewSelectorInstrumentType)(ptr("invalid_type")),
688 },
689 },
690 wantErr: "view_selector: instrument_type: invalid value",
691 },
692 {
693 name: "selector/invalid_type",
694 view: View{
695 Selector: &ViewSelector{},
696 },
697 wantErr: "view_selector: empty selector not supporter",
698 },
699 {
700 name: "all selectors match",
701 view: View{
702 Selector: &ViewSelector{
703 InstrumentName: ptr("test_name"),
704 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
705 Unit: ptr("test_unit"),
706 MeterName: ptr("test_meter_name"),
707 MeterVersion: ptr("test_meter_version"),
708 MeterSchemaUrl: ptr("test_schema_url"),
709 },
710 },
711 matchInstrument: &sdkmetric.Instrument{
712 Name: "test_name",
713 Unit: "test_unit",
714 Kind: sdkmetric.InstrumentKindCounter,
715 Scope: instrumentation.Scope{
716 Name: "test_meter_name",
717 Version: "test_meter_version",
718 SchemaURL: "test_schema_url",
719 },
720 },
721 wantStream: sdkmetric.Stream{Name: "test_name", Unit: "test_unit"},
722 wantResult: true,
723 },
724 {
725 name: "all selectors no match name",
726 view: View{
727 Selector: &ViewSelector{
728 InstrumentName: ptr("test_name"),
729 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
730 Unit: ptr("test_unit"),
731 MeterName: ptr("test_meter_name"),
732 MeterVersion: ptr("test_meter_version"),
733 MeterSchemaUrl: ptr("test_schema_url"),
734 },
735 },
736 matchInstrument: &sdkmetric.Instrument{
737 Name: "not_match",
738 Unit: "test_unit",
739 Kind: sdkmetric.InstrumentKindCounter,
740 Scope: instrumentation.Scope{
741 Name: "test_meter_name",
742 Version: "test_meter_version",
743 SchemaURL: "test_schema_url",
744 },
745 },
746 wantStream: sdkmetric.Stream{},
747 wantResult: false,
748 },
749 {
750 name: "all selectors no match unit",
751 view: View{
752 Selector: &ViewSelector{
753 InstrumentName: ptr("test_name"),
754 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
755 Unit: ptr("test_unit"),
756 MeterName: ptr("test_meter_name"),
757 MeterVersion: ptr("test_meter_version"),
758 MeterSchemaUrl: ptr("test_schema_url"),
759 },
760 },
761 matchInstrument: &sdkmetric.Instrument{
762 Name: "test_name",
763 Unit: "not_match",
764 Kind: sdkmetric.InstrumentKindCounter,
765 Scope: instrumentation.Scope{
766 Name: "test_meter_name",
767 Version: "test_meter_version",
768 SchemaURL: "test_schema_url",
769 },
770 },
771 wantStream: sdkmetric.Stream{},
772 wantResult: false,
773 },
774 {
775 name: "all selectors no match kind",
776 view: View{
777 Selector: &ViewSelector{
778 InstrumentName: ptr("test_name"),
779 InstrumentType: (*ViewSelectorInstrumentType)(ptr("histogram")),
780 Unit: ptr("test_unit"),
781 MeterName: ptr("test_meter_name"),
782 MeterVersion: ptr("test_meter_version"),
783 MeterSchemaUrl: ptr("test_schema_url"),
784 },
785 },
786 matchInstrument: &sdkmetric.Instrument{
787 Name: "test_name",
788 Unit: "test_unit",
789 Kind: sdkmetric.InstrumentKindCounter,
790 Scope: instrumentation.Scope{
791 Name: "test_meter_name",
792 Version: "test_meter_version",
793 SchemaURL: "test_schema_url",
794 },
795 },
796 wantStream: sdkmetric.Stream{},
797 wantResult: false,
798 },
799 {
800 name: "all selectors no match meter name",
801 view: View{
802 Selector: &ViewSelector{
803 InstrumentName: ptr("test_name"),
804 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
805 Unit: ptr("test_unit"),
806 MeterName: ptr("test_meter_name"),
807 MeterVersion: ptr("test_meter_version"),
808 MeterSchemaUrl: ptr("test_schema_url"),
809 },
810 },
811 matchInstrument: &sdkmetric.Instrument{
812 Name: "test_name",
813 Unit: "test_unit",
814 Kind: sdkmetric.InstrumentKindCounter,
815 Scope: instrumentation.Scope{
816 Name: "not_match",
817 Version: "test_meter_version",
818 SchemaURL: "test_schema_url",
819 },
820 },
821 wantStream: sdkmetric.Stream{},
822 wantResult: false,
823 },
824 {
825 name: "all selectors no match meter version",
826 view: View{
827 Selector: &ViewSelector{
828 InstrumentName: ptr("test_name"),
829 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
830 Unit: ptr("test_unit"),
831 MeterName: ptr("test_meter_name"),
832 MeterVersion: ptr("test_meter_version"),
833 MeterSchemaUrl: ptr("test_schema_url"),
834 },
835 },
836 matchInstrument: &sdkmetric.Instrument{
837 Name: "test_name",
838 Unit: "test_unit",
839 Kind: sdkmetric.InstrumentKindCounter,
840 Scope: instrumentation.Scope{
841 Name: "test_meter_name",
842 Version: "not_match",
843 SchemaURL: "test_schema_url",
844 },
845 },
846 wantStream: sdkmetric.Stream{},
847 wantResult: false,
848 },
849 {
850 name: "all selectors no match meter schema url",
851 view: View{
852 Selector: &ViewSelector{
853 InstrumentName: ptr("test_name"),
854 InstrumentType: (*ViewSelectorInstrumentType)(ptr("counter")),
855 Unit: ptr("test_unit"),
856 MeterName: ptr("test_meter_name"),
857 MeterVersion: ptr("test_meter_version"),
858 MeterSchemaUrl: ptr("test_schema_url"),
859 },
860 },
861 matchInstrument: &sdkmetric.Instrument{
862 Name: "test_name",
863 Unit: "test_unit",
864 Kind: sdkmetric.InstrumentKindCounter,
865 Scope: instrumentation.Scope{
866 Name: "test_meter_name",
867 Version: "test_meter_version",
868 SchemaURL: "not_match",
869 },
870 },
871 wantStream: sdkmetric.Stream{},
872 wantResult: false,
873 },
874 {
875 name: "with stream",
876 view: View{
877 Selector: &ViewSelector{
878 InstrumentName: ptr("test_name"),
879 Unit: ptr("test_unit"),
880 },
881 Stream: &ViewStream{
882 Name: ptr("new_name"),
883 Description: ptr("new_description"),
884 AttributeKeys: []string{"foo", "bar"},
885 Aggregation: &ViewStreamAggregation{Sum: make(ViewStreamAggregationSum)},
886 },
887 },
888 matchInstrument: &sdkmetric.Instrument{
889 Name: "test_name",
890 Description: "test_description",
891 Unit: "test_unit",
892 },
893 wantStream: sdkmetric.Stream{
894 Name: "new_name",
895 Description: "new_description",
896 Unit: "test_unit",
897 Aggregation: sdkmetric.AggregationSum{},
898 },
899 wantResult: true,
900 },
901 }
902 for _, tt := range testCases {
903 t.Run(tt.name, func(t *testing.T) {
904 got, err := view(tt.view)
905 if tt.wantErr != "" {
906 require.EqualError(t, err, tt.wantErr)
907 require.Nil(t, got)
908 } else {
909 require.NoError(t, err)
910 gotStream, gotResult := got(*tt.matchInstrument)
911 // Remove filter, since it cannot be compared
912 gotStream.AttributeFilter = nil
913 require.Equal(t, tt.wantStream, gotStream)
914 require.Equal(t, tt.wantResult, gotResult)
915 }
916 })
917 }
918 }
919
920 func TestInstrumentType(t *testing.T) {
921 testCases := []struct {
922 name string
923 instType *ViewSelectorInstrumentType
924 wantErr error
925 wantKind sdkmetric.InstrumentKind
926 }{
927 {
928 name: "nil",
929 wantKind: sdkmetric.InstrumentKind(0),
930 },
931 {
932 name: "counter",
933 instType: (*ViewSelectorInstrumentType)(ptr("counter")),
934 wantKind: sdkmetric.InstrumentKindCounter,
935 },
936 {
937 name: "up_down_counter",
938 instType: (*ViewSelectorInstrumentType)(ptr("up_down_counter")),
939 wantKind: sdkmetric.InstrumentKindUpDownCounter,
940 },
941 {
942 name: "histogram",
943 instType: (*ViewSelectorInstrumentType)(ptr("histogram")),
944 wantKind: sdkmetric.InstrumentKindHistogram,
945 },
946 {
947 name: "observable_counter",
948 instType: (*ViewSelectorInstrumentType)(ptr("observable_counter")),
949 wantKind: sdkmetric.InstrumentKindObservableCounter,
950 },
951 {
952 name: "observable_up_down_counter",
953 instType: (*ViewSelectorInstrumentType)(ptr("observable_up_down_counter")),
954 wantKind: sdkmetric.InstrumentKindObservableUpDownCounter,
955 },
956 {
957 name: "observable_gauge",
958 instType: (*ViewSelectorInstrumentType)(ptr("observable_gauge")),
959 wantKind: sdkmetric.InstrumentKindObservableGauge,
960 },
961 {
962 name: "invalid",
963 instType: (*ViewSelectorInstrumentType)(ptr("invalid")),
964 wantErr: errors.New("instrument_type: invalid value"),
965 },
966 }
967 for _, tt := range testCases {
968 t.Run(tt.name, func(t *testing.T) {
969 got, err := instrumentKind(tt.instType)
970 if tt.wantErr != nil {
971 require.Equal(t, tt.wantErr, err)
972 require.Zero(t, got)
973 } else {
974 require.NoError(t, err)
975 require.Equal(t, tt.wantKind, got)
976 }
977 })
978 }
979 }
980
981 func TestAggregation(t *testing.T) {
982 testCases := []struct {
983 name string
984 aggregation *ViewStreamAggregation
985 wantAggregation sdkmetric.Aggregation
986 }{
987 {
988 name: "nil",
989 wantAggregation: nil,
990 },
991 {
992 name: "empty",
993 aggregation: &ViewStreamAggregation{},
994 wantAggregation: nil,
995 },
996 {
997 name: "Base2ExponentialBucketHistogram empty",
998 aggregation: &ViewStreamAggregation{
999 Base2ExponentialBucketHistogram: &ViewStreamAggregationBase2ExponentialBucketHistogram{},
1000 },
1001 wantAggregation: sdkmetric.AggregationBase2ExponentialHistogram{
1002 MaxSize: 0,
1003 MaxScale: 0,
1004 NoMinMax: true,
1005 },
1006 },
1007 {
1008 name: "Base2ExponentialBucketHistogram",
1009 aggregation: &ViewStreamAggregation{
1010 Base2ExponentialBucketHistogram: &ViewStreamAggregationBase2ExponentialBucketHistogram{
1011 MaxSize: ptr(2),
1012 MaxScale: ptr(3),
1013 RecordMinMax: ptr(true),
1014 },
1015 },
1016 wantAggregation: sdkmetric.AggregationBase2ExponentialHistogram{
1017 MaxSize: 2,
1018 MaxScale: 3,
1019 NoMinMax: false,
1020 },
1021 },
1022 {
1023 name: "Default",
1024 aggregation: &ViewStreamAggregation{
1025 Default: make(ViewStreamAggregationDefault),
1026 },
1027 wantAggregation: nil,
1028 },
1029 {
1030 name: "Drop",
1031 aggregation: &ViewStreamAggregation{
1032 Drop: make(ViewStreamAggregationDrop),
1033 },
1034 wantAggregation: sdkmetric.AggregationDrop{},
1035 },
1036 {
1037 name: "ExplicitBucketHistogram empty",
1038 aggregation: &ViewStreamAggregation{
1039 ExplicitBucketHistogram: &ViewStreamAggregationExplicitBucketHistogram{},
1040 },
1041 wantAggregation: sdkmetric.AggregationExplicitBucketHistogram{
1042 Boundaries: nil,
1043 NoMinMax: true,
1044 },
1045 },
1046 {
1047 name: "ExplicitBucketHistogram",
1048 aggregation: &ViewStreamAggregation{
1049 ExplicitBucketHistogram: &ViewStreamAggregationExplicitBucketHistogram{
1050 Boundaries: []float64{1, 2, 3},
1051 RecordMinMax: ptr(true),
1052 },
1053 },
1054 wantAggregation: sdkmetric.AggregationExplicitBucketHistogram{
1055 Boundaries: []float64{1, 2, 3},
1056 NoMinMax: false,
1057 },
1058 },
1059 {
1060 name: "LastValue",
1061 aggregation: &ViewStreamAggregation{
1062 LastValue: make(ViewStreamAggregationLastValue),
1063 },
1064 wantAggregation: sdkmetric.AggregationLastValue{},
1065 },
1066 {
1067 name: "Sum",
1068 aggregation: &ViewStreamAggregation{
1069 Sum: make(ViewStreamAggregationSum),
1070 },
1071 wantAggregation: sdkmetric.AggregationSum{},
1072 },
1073 }
1074 for _, tt := range testCases {
1075 t.Run(tt.name, func(t *testing.T) {
1076 got := aggregation(tt.aggregation)
1077 require.Equal(t, tt.wantAggregation, got)
1078 })
1079 }
1080 }
1081
1082 func TestAttributeFilter(t *testing.T) {
1083 testCases := []struct {
1084 name string
1085 attributeKeys []string
1086 wantPass []string
1087 wantFail []string
1088 }{
1089 {
1090 name: "empty",
1091 attributeKeys: []string{},
1092 wantPass: nil,
1093 wantFail: []string{"foo", "bar"},
1094 },
1095 {
1096 name: "filter",
1097 attributeKeys: []string{"foo"},
1098 wantPass: []string{"foo"},
1099 wantFail: []string{"bar"},
1100 },
1101 }
1102 for _, tt := range testCases {
1103 t.Run(tt.name, func(t *testing.T) {
1104 got := attributeFilter(tt.attributeKeys)
1105 for _, pass := range tt.wantPass {
1106 require.True(t, got(attribute.KeyValue{Key: attribute.Key(pass), Value: attribute.StringValue("")}))
1107 }
1108 for _, fail := range tt.wantFail {
1109 require.False(t, got(attribute.KeyValue{Key: attribute.Key(fail), Value: attribute.StringValue("")}))
1110 }
1111 })
1112 }
1113 }
1114
1115 func TestPrometheusIPv6(t *testing.T) {
1116 tests := []struct {
1117 name string
1118 host string
1119 }{
1120 {
1121 name: "IPv6",
1122 host: "::1",
1123 },
1124 {
1125 name: "[IPv6]",
1126 host: "[::1]",
1127 },
1128 }
1129 for _, tt := range tests {
1130 t.Run(tt.name, func(t *testing.T) {
1131 port := 0
1132 cfg := Prometheus{
1133 Host: &tt.host,
1134 Port: &port,
1135 WithoutScopeInfo: ptr(true),
1136 WithoutTypeSuffix: ptr(true),
1137 WithoutUnits: ptr(true),
1138 WithResourceConstantLabels: &IncludeExclude{},
1139 }
1140
1141 rs, err := prometheusReader(t.Context(), &cfg)
1142 t.Cleanup(func() {
1143 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
1144 require.NoError(t, rs.Shutdown(context.Background()))
1145 })
1146 require.NoError(t, err)
1147
1148 hServ := rs.(readerWithServer).server
1149 assert.True(t, strings.HasPrefix(hServ.Addr, "[::1]:"))
1150
1151 req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+hServ.Addr+"/metrics", http.NoBody)
1152 require.NoError(t, err)
1153
1154 resp, err := http.DefaultClient.Do(req)
1155 t.Cleanup(func() {
1156 require.NoError(t, resp.Body.Close())
1157 })
1158 require.NoError(t, err)
1159 assert.Equal(t, http.StatusOK, resp.StatusCode)
1160 })
1161 }
1162 }
1163
1164 func TestPrometheusReaderErrorCases(t *testing.T) {
1165 tests := []struct {
1166 name string
1167 config *Prometheus
1168 errMsg string
1169 }{
1170 {
1171 name: "missing host",
1172 config: &Prometheus{Port: ptr(8080)},
1173 errMsg: "host must be specified",
1174 },
1175 {
1176 name: "missing port",
1177 config: &Prometheus{Host: ptr("localhost")},
1178 errMsg: "port must be specified",
1179 },
1180 {
1181 name: "invalid port",
1182 config: &Prometheus{
1183 Host: ptr("localhost"),
1184 Port: ptr(99999), // invalid port
1185 WithoutScopeInfo: ptr(true),
1186 WithoutTypeSuffix: ptr(true),
1187 WithoutUnits: ptr(true),
1188 WithResourceConstantLabels: &IncludeExclude{},
1189 },
1190 errMsg: "binding address",
1191 },
1192 }
1193
1194 for _, tt := range tests {
1195 t.Run(tt.name, func(t *testing.T) {
1196 reader, err := prometheusReader(t.Context(), tt.config)
1197 assert.ErrorContains(t, err, tt.errMsg)
1198 assert.Nil(t, reader)
1199 })
1200 }
1201 }
1202
1203 func TestPrometheusReaderConfigurationOptions(t *testing.T) {
1204 host := "localhost"
1205 port := 0
1206 cfg := &Prometheus{
1207 Host: &host,
1208 Port: &port,
1209 WithoutScopeInfo: ptr(true),
1210 WithoutTypeSuffix: ptr(true),
1211 WithoutUnits: ptr(true),
1212 WithResourceConstantLabels: &IncludeExclude{
1213 Included: []string{"service.name"},
1214 Excluded: []string{"host.name"},
1215 },
1216 }
1217
1218 reader, err := prometheusReader(t.Context(), cfg)
1219 require.NoError(t, err)
1220 require.NotNil(t, reader)
1221
1222 t.Cleanup(func() {
1223 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
1224 require.NoError(t, reader.Shutdown(context.Background()))
1225 })
1226
1227 rws, ok := reader.(readerWithServer)
1228 require.True(t, ok, "reader is not a readerWithServer")
1229 server := rws.server
1230
1231 addr := server.Addr
1232 // localhost resolves to 127.0.0.1, so we expect the resolved IP
1233 assert.Contains(t, addr, "127.0.0.1")
1234
1235 req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+addr+"/metrics", http.NoBody)
1236 require.NoError(t, err)
1237
1238 resp, err := http.DefaultClient.Do(req)
1239 require.NoError(t, err)
1240 defer resp.Body.Close()
1241
1242 assert.Equal(t, http.StatusOK, resp.StatusCode)
1243 }
1244
1245 // TestPrometheusReaderDotStyleLabels verifies that OTel dot-style resource
1246 // attribute names (e.g. service.name) are preserved in target_info when both
1247 // without_type_suffix and without_units are set which is default config for OTel Collector.
1248 func TestPrometheusReaderDotStyleLabels(t *testing.T) {
1249 host := "localhost"
1250 port := 0
1251 reader, err := prometheusReader(t.Context(), &Prometheus{
1252 Host: &host,
1253 Port: &port,
1254 WithoutTypeSuffix: ptr(true),
1255 WithoutUnits: ptr(true),
1256 })
1257 require.NoError(t, err)
1258
1259 res := resource.NewWithAttributes("", attribute.String("service.name", "test-svc"))
1260 mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader), sdkmetric.WithResource(res))
1261 t.Cleanup(func() {
1262 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
1263 require.NoError(t, mp.Shutdown(context.Background()))
1264 })
1265 c, err := mp.Meter("test").Int64Counter("test.counter")
1266 require.NoError(t, err)
1267 c.Add(t.Context(), 1)
1268
1269 addr := reader.(readerWithServer).server.Addr
1270 req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://"+addr+"/metrics", http.NoBody)
1271 require.NoError(t, err)
1272 req.Header.Set("Accept", "application/openmetrics-text; version=1.0.0; escaping=allow-utf-8")
1273 resp, err := http.DefaultClient.Do(req)
1274 require.NoError(t, err)
1275 defer resp.Body.Close()
1276
1277 var buf bytes.Buffer
1278 _, err = buf.ReadFrom(resp.Body)
1279 require.NoError(t, err)
1280 body := buf.String()
1281
1282 assert.Contains(t, body, `target_info{"service.name"="test-svc"}`)
1283 assert.NotContains(t, body, "service_name")
1284 }
1285
1286 func TestPrometheusReaderHostParsing(t *testing.T) {
1287 tests := []struct {
1288 name string
1289 host string
1290 wantAddr string
1291 }{
1292 {
1293 name: "regular host",
1294 host: "localhost",
1295 wantAddr: "127.0.0.1", // localhost resolves to this IP
1296 },
1297 {
1298 name: "IPv4",
1299 host: "127.0.0.1",
1300 wantAddr: "127.0.0.1",
1301 },
1302 {
1303 name: "IPv6 with brackets",
1304 host: "[::1]",
1305 wantAddr: "::1",
1306 },
1307 {
1308 name: "IPv6 without brackets",
1309 host: "::1",
1310 wantAddr: "::1",
1311 },
1312 }
1313
1314 for _, tt := range tests {
1315 t.Run(tt.name, func(t *testing.T) {
1316 port := 0
1317 cfg := Prometheus{
1318 Host: &tt.host,
1319 Port: &port,
1320 WithoutScopeInfo: ptr(true),
1321 WithoutTypeSuffix: ptr(true),
1322 WithoutUnits: ptr(true),
1323 WithResourceConstantLabels: &IncludeExclude{},
1324 }
1325
1326 reader, err := prometheusReader(t.Context(), &cfg)
1327 require.NoError(t, err)
1328 require.NotNil(t, reader)
1329
1330 t.Cleanup(func() {
1331 //nolint:usetesting // required to avoid getting a canceled context at cleanup.
1332 require.NoError(t, reader.Shutdown(context.Background()))
1333 })
1334
1335 rws, ok := reader.(readerWithServer)
1336 require.True(t, ok, "reader is not a readerWithServer")
1337 server := rws.server
1338
1339 assert.Contains(t, server.Addr, tt.wantAddr)
1340 })
1341 }
1342 }