Debian Codegraph @

otelconf/x/metric.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package x // import "go.opentelemetry.io/contrib/otelconf/x"
5
6 import (
7 "context"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "math"
12 "net"
13 "net/http"
14 "net/url"
15 "os"
16 "strconv"
17 "time"
18
19 "github.com/prometheus/client_golang/prometheus"
20 "github.com/prometheus/client_golang/prometheus/promhttp"
21 "github.com/prometheus/otlptranslator"
22 "go.opentelemetry.io/otel"
23 "go.opentelemetry.io/otel/attribute"
24 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc"
25 "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
26 otelprom "go.opentelemetry.io/otel/exporters/prometheus"
27 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
28 "go.opentelemetry.io/otel/metric"
29 "go.opentelemetry.io/otel/metric/noop"
30 "go.opentelemetry.io/otel/sdk/instrumentation"
31 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
32 "go.opentelemetry.io/otel/sdk/metric/metricdata"
33 "go.opentelemetry.io/otel/sdk/resource"
34 "google.golang.org/grpc/credentials"
35
36 "go.opentelemetry.io/contrib/otelconf/internal/tls"
37 )
38
39 var zeroScope instrumentation.Scope
40
41 const instrumentKindUndefined = sdkmetric.InstrumentKind(0)
42
43 func meterProvider(cfg configOptions, res *resource.Resource) (metric.MeterProvider, shutdownFunc, error) {
44 if cfg.opentelemetryConfig.MeterProvider == nil {
45 return noop.NewMeterProvider(), noopShutdown, nil
46 }
47 opts := append(cfg.meterProviderOptions, sdkmetric.WithResource(res))
48
49 var errs []error
50 for _, reader := range cfg.opentelemetryConfig.MeterProvider.Readers {
51 r, err := metricReader(cfg.ctx, reader)
52 if err == nil {
53 opts = append(opts, sdkmetric.WithReader(r))
54 } else {
55 errs = append(errs, err)
56 }
57 }
58 for _, vw := range cfg.opentelemetryConfig.MeterProvider.Views {
59 v, err := view(vw)
60 if err == nil {
61 opts = append(opts, sdkmetric.WithView(v))
62 } else {
63 errs = append(errs, err)
64 }
65 }
66
67 if len(errs) > 0 {
68 return noop.NewMeterProvider(), noopShutdown, errors.Join(errs...)
69 }
70
71 mp := sdkmetric.NewMeterProvider(opts...)
72 return mp, mp.Shutdown, nil
73 }
74
75 func metricReader(ctx context.Context, r MetricReader) (sdkmetric.Reader, error) {
76 if r.Periodic != nil && r.Pull != nil {
77 return nil, newErrInvalid("must not specify multiple metric reader type")
78 }
79
80 if r.Periodic != nil {
81 var opts []sdkmetric.PeriodicReaderOption
82 if r.Periodic.Interval != nil {
83 opts = append(opts, sdkmetric.WithInterval(time.Duration(*r.Periodic.Interval)*time.Millisecond))
84 }
85
86 if r.Periodic.Timeout != nil {
87 opts = append(opts, sdkmetric.WithTimeout(time.Duration(*r.Periodic.Timeout)*time.Millisecond))
88 }
89 return periodicExporter(ctx, r.Periodic.Exporter, opts...)
90 }
91
92 if r.Pull != nil {
93 return pullReader(ctx, r.Pull.Exporter)
94 }
95 return nil, newErrInvalid("no valid metric reader")
96 }
97
98 func pullReader(ctx context.Context, exporter PullMetricExporter) (sdkmetric.Reader, error) {
99 if exporter.PrometheusDevelopment != nil {
100 return prometheusReader(ctx, exporter.PrometheusDevelopment)
101 }
102 return nil, newErrInvalid("no valid metric exporter")
103 }
104
105 func periodicExporter(ctx context.Context, exporter PushMetricExporter, opts ...sdkmetric.PeriodicReaderOption) (sdkmetric.Reader, error) {
106 exportersConfigured := 0
107 var exportFunc func() (sdkmetric.Reader, error)
108
109 if exporter.Console != nil {
110 exportersConfigured++
111 enc := json.NewEncoder(os.Stdout)
112 enc.SetIndent("", " ")
113
114 exp, err := stdoutmetric.New(
115 stdoutmetric.WithEncoder(enc),
116 )
117 if err != nil {
118 return nil, err
119 }
120 exportFunc = func() (sdkmetric.Reader, error) {
121 return sdkmetric.NewPeriodicReader(exp, opts...), nil
122 }
123 }
124 if exporter.OTLPHttp != nil {
125 exportersConfigured++
126 exp, err := otlpHTTPMetricExporter(ctx, exporter.OTLPHttp)
127 if err != nil {
128 return nil, err
129 }
130 exportFunc = func() (sdkmetric.Reader, error) {
131 return sdkmetric.NewPeriodicReader(exp, opts...), nil
132 }
133 }
134 if exporter.OTLPGrpc != nil {
135 exportersConfigured++
136 exp, err := otlpGRPCMetricExporter(ctx, exporter.OTLPGrpc)
137 if err != nil {
138 return nil, err
139 }
140 exportFunc = func() (sdkmetric.Reader, error) {
141 return sdkmetric.NewPeriodicReader(exp, opts...), nil
142 }
143 }
144 if exporter.OTLPFileDevelopment != nil {
145 // TODO: implement file exporter https://github.com/open-telemetry/opentelemetry-go/issues/5408
146 return nil, newErrInvalid("otlp_file/development")
147 }
148
149 if exportersConfigured > 1 {
150 return nil, newErrInvalid("must not specify multiple exporters")
151 }
152
153 if exportFunc != nil {
154 return exportFunc()
155 }
156
157 return nil, newErrInvalid("no valid metric exporter")
158 }
159
160 func otlpHTTPMetricExporter(ctx context.Context, otlpConfig *OTLPHttpMetricExporter) (sdkmetric.Exporter, error) {
161 opts := []otlpmetrichttp.Option{}
162
163 if otlpConfig.Endpoint != nil {
164 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
165 if err != nil {
166 return nil, errors.Join(newErrInvalid("endpoint parsing failed"), err)
167 }
168 opts = append(opts, otlpmetrichttp.WithEndpoint(u.Host))
169
170 if u.Scheme == "http" {
171 opts = append(opts, otlpmetrichttp.WithInsecure())
172 }
173 if u.Path != "" {
174 opts = append(opts, otlpmetrichttp.WithURLPath(u.Path))
175 }
176 }
177 if otlpConfig.Compression != nil {
178 switch *otlpConfig.Compression {
179 case compressionGzip:
180 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression))
181 case compressionNone:
182 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.NoCompression))
183 default:
184 return nil, newErrInvalid(fmt.Sprintf("unsupported compression %q", *otlpConfig.Compression))
185 }
186 }
187 if otlpConfig.Timeout != nil {
188 opts = append(opts, otlpmetrichttp.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
189 }
190 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
191 if err != nil {
192 return nil, err
193 }
194 if len(headersConfig) > 0 {
195 opts = append(opts, otlpmetrichttp.WithHeaders(headersConfig))
196 }
197 if otlpConfig.TemporalityPreference != nil {
198 switch *otlpConfig.TemporalityPreference {
199 case "delta":
200 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(deltaTemporality))
201 case "cumulative":
202 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(cumulativeTemporality))
203 case "low_memory":
204 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(lowMemory))
205 default:
206 return nil, newErrInvalid(fmt.Sprintf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference))
207 }
208 }
209 if otlpConfig.Tls != nil {
210 tlsConfig, err := tls.CreateConfig(otlpConfig.Tls.CaFile, otlpConfig.Tls.CertFile, otlpConfig.Tls.KeyFile)
211 if err != nil {
212 return nil, errors.Join(newErrInvalid("tls configuration"), err)
213 }
214 opts = append(opts, otlpmetrichttp.WithTLSClientConfig(tlsConfig))
215 }
216
217 return otlpmetrichttp.New(ctx, opts...)
218 }
219
220 func otlpGRPCMetricExporter(ctx context.Context, otlpConfig *OTLPGrpcMetricExporter) (sdkmetric.Exporter, error) {
221 var opts []otlpmetricgrpc.Option
222
223 if otlpConfig.Endpoint != nil {
224 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
225 if err != nil {
226 return nil, errors.Join(newErrInvalid("endpoint parsing failed"), err)
227 }
228 // ParseRequestURI leaves the Host field empty when no
229 // scheme is specified (i.e. localhost:4317). This check is
230 // here to support the case where a user may not specify a
231 // scheme. The code does its best effort here by using
232 // otlpConfig.Endpoint as-is in that case
233 if u.Host != "" {
234 opts = append(opts, otlpmetricgrpc.WithEndpoint(u.Host))
235 } else {
236 opts = append(opts, otlpmetricgrpc.WithEndpoint(*otlpConfig.Endpoint))
237 }
238 if u.Scheme == "http" || (u.Scheme != "https" && otlpConfig.Tls != nil && otlpConfig.Tls.Insecure != nil && *otlpConfig.Tls.Insecure) {
239 opts = append(opts, otlpmetricgrpc.WithInsecure())
240 }
241 }
242
243 if otlpConfig.Compression != nil {
244 switch *otlpConfig.Compression {
245 case compressionGzip:
246 opts = append(opts, otlpmetricgrpc.WithCompressor(*otlpConfig.Compression))
247 case compressionNone:
248 // none requires no options
249 default:
250 return nil, newErrInvalid(fmt.Sprintf("unsupported compression %q", *otlpConfig.Compression))
251 }
252 }
253 if otlpConfig.Timeout != nil && *otlpConfig.Timeout > 0 {
254 opts = append(opts, otlpmetricgrpc.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
255 }
256 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
257 if err != nil {
258 return nil, err
259 }
260 if len(headersConfig) > 0 {
261 opts = append(opts, otlpmetricgrpc.WithHeaders(headersConfig))
262 }
263 if otlpConfig.TemporalityPreference != nil {
264 switch *otlpConfig.TemporalityPreference {
265 case "delta":
266 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(deltaTemporality))
267 case "cumulative":
268 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(cumulativeTemporality))
269 case "low_memory":
270 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(lowMemory))
271 default:
272 return nil, newErrInvalid(fmt.Sprintf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference))
273 }
274 }
275
276 if otlpConfig.Tls != nil && (otlpConfig.Tls.CaFile != nil || otlpConfig.Tls.CertFile != nil || otlpConfig.Tls.KeyFile != nil) {
277 tlsConfig, err := tls.CreateConfig(otlpConfig.Tls.CaFile, otlpConfig.Tls.CertFile, otlpConfig.Tls.KeyFile)
278 if err != nil {
279 return nil, errors.Join(newErrInvalid("tls configuration"), err)
280 }
281 opts = append(opts, otlpmetricgrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig)))
282 }
283
284 return otlpmetricgrpc.New(ctx, opts...)
285 }
286
287 func cumulativeTemporality(sdkmetric.InstrumentKind) metricdata.Temporality {
288 return metricdata.CumulativeTemporality
289 }
290
291 func deltaTemporality(ik sdkmetric.InstrumentKind) metricdata.Temporality {
292 switch ik {
293 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram, sdkmetric.InstrumentKindObservableCounter:
294 return metricdata.DeltaTemporality
295 default:
296 return metricdata.CumulativeTemporality
297 }
298 }
299
300 func lowMemory(ik sdkmetric.InstrumentKind) metricdata.Temporality {
301 switch ik {
302 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram:
303 return metricdata.DeltaTemporality
304 default:
305 return metricdata.CumulativeTemporality
306 }
307 }
308
309 // newIncludeExcludeFilter returns a Filter that includes attributes
310 // in the include list and excludes attributes in the excludes list.
311 // It returns an error if an attribute is in both lists
312 //
313 // If IncludeExclude is empty an include-all filter is returned.
314 func newIncludeExcludeFilter(lists *IncludeExclude) (attribute.Filter, error) {
315 if lists == nil {
316 return func(attribute.KeyValue) bool { return true }, nil
317 }
318
319 included := make(map[attribute.Key]struct{})
320 for _, k := range lists.Included {
321 included[attribute.Key(k)] = struct{}{}
322 }
323 excluded := make(map[attribute.Key]struct{})
324 for _, k := range lists.Excluded {
325 if _, ok := included[attribute.Key(k)]; ok {
326 return nil, fmt.Errorf("attribute cannot be in both include and exclude list: %s", k)
327 }
328 excluded[attribute.Key(k)] = struct{}{}
329 }
330 return func(kv attribute.KeyValue) bool {
331 // check if a value is excluded first
332 if _, ok := excluded[kv.Key]; ok {
333 return false
334 }
335
336 if len(included) == 0 {
337 return true
338 }
339
340 _, ok := included[kv.Key]
341 return ok
342 }, nil
343 }
344
345 func prometheusReader(ctx context.Context, prometheusConfig *ExperimentalPrometheusMetricExporter) (sdkmetric.Reader, error) {
346 if prometheusConfig.Host == nil {
347 return nil, newErrInvalid("host must be specified")
348 }
349 if prometheusConfig.Port == nil {
350 return nil, newErrInvalid("port must be specified")
351 }
352
353 opts, err := prometheusReaderOpts(prometheusConfig)
354 if err != nil {
355 return nil, err
356 }
357
358 reg := prometheus.NewRegistry()
359 opts = append(opts, otelprom.WithRegisterer(reg))
360
361 reader, err := otelprom.New(opts...)
362 if err != nil {
363 return nil, fmt.Errorf("error creating otel prometheus exporter: %w", err)
364 }
365
366 mux := http.NewServeMux()
367 mux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
368 server := http.Server{
369 // Timeouts are necessary to make a server resilient to attacks.
370 // We use values from this example: https://blog.cloudflare.com/exposing-go-on-the-internet/#:~:text=There%20are%20three%20main%20timeouts
371 ReadTimeout: 5 * time.Second,
372 WriteTimeout: 10 * time.Second,
373 IdleTimeout: 120 * time.Second,
374 Handler: mux,
375 }
376
377 // Remove surrounding "[]" from the host definition to allow users to define the host as "[::1]" or "::1".
378 host := *prometheusConfig.Host
379 if len(host) > 2 && host[0] == '[' && host[len(host)-1] == ']' {
380 host = host[1 : len(host)-1]
381 }
382
383 addr := net.JoinHostPort(host, strconv.Itoa(*prometheusConfig.Port))
384 lis, err := (&net.ListenConfig{}).Listen(ctx, "tcp", addr)
385 if err != nil {
386 return nil, errors.Join(
387 fmt.Errorf("binding address %s for Prometheus exporter: %w", addr, err),
388 reader.Shutdown(ctx),
389 )
390 }
391
392 // Only for testing reasons, add the address to the http Server, will not be used.
393 server.Addr = lis.Addr().String()
394
395 go func() {
396 if err := server.Serve(lis); err != nil && !errors.Is(err, http.ErrServerClosed) {
397 otel.Handle(fmt.Errorf("the Prometheus HTTP server exited unexpectedly: %w", err))
398 }
399 }()
400
401 return readerWithServer{reader, &server}, nil
402 }
403
404 func validTranslationStrategy(strategy ExperimentalPrometheusTranslationStrategy) bool {
405 return strategy == ExperimentalPrometheusTranslationStrategyNoTranslation ||
406 strategy == ExperimentalPrometheusTranslationStrategyNoUtf8EscapingWithSuffixes ||
407 strategy == ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithSuffixes ||
408 strategy == ExperimentalPrometheusTranslationStrategyUnderscoreEscapingWithoutSuffixes
409 }
410
411 func prometheusReaderOpts(prometheusConfig *ExperimentalPrometheusMetricExporter) ([]otelprom.Option, error) {
412 var opts []otelprom.Option
413 if prometheusConfig.WithoutScopeInfo != nil && *prometheusConfig.WithoutScopeInfo {
414 opts = append(opts, otelprom.WithoutScopeInfo())
415 }
416 if prometheusConfig.TranslationStrategy != nil {
417 if !validTranslationStrategy(*prometheusConfig.TranslationStrategy) {
418 return nil, newErrInvalid("translation strategy invalid")
419 }
420 opts = append(opts, otelprom.WithTranslationStrategy(otlptranslator.TranslationStrategyOption(*prometheusConfig.TranslationStrategy)))
421 }
422 if prometheusConfig.WithResourceConstantLabels != nil {
423 f, err := newIncludeExcludeFilter(prometheusConfig.WithResourceConstantLabels)
424 if err != nil {
425 return nil, err
426 }
427 opts = append(opts, otelprom.WithResourceAsConstantLabels(f))
428 }
429
430 return opts, nil
431 }
432
433 type readerWithServer struct {
434 sdkmetric.Reader
435 server *http.Server
436 }
437
438 func (rws readerWithServer) Shutdown(ctx context.Context) error {
439 return errors.Join(
440 rws.Reader.Shutdown(ctx),
441 rws.server.Shutdown(ctx),
442 )
443 }
444
445 func view(v View) (sdkmetric.View, error) {
446 inst, err := instrument(v.Selector)
447 if err != nil {
448 return nil, err
449 }
450
451 s, err := stream(v.Stream)
452 if err != nil {
453 return nil, err
454 }
455 return sdkmetric.NewView(inst, s), nil
456 }
457
458 func instrument(vs ViewSelector) (sdkmetric.Instrument, error) {
459 kind, err := instrumentKind(vs.InstrumentType)
460 if err != nil {
461 return sdkmetric.Instrument{}, fmt.Errorf("view_selector: %w", err)
462 }
463 inst := sdkmetric.Instrument{
464 Name: strOrEmpty(vs.InstrumentName),
465 Unit: strOrEmpty(vs.Unit),
466 Kind: kind,
467 Scope: instrumentation.Scope{
468 Name: strOrEmpty(vs.MeterName),
469 Version: strOrEmpty(vs.MeterVersion),
470 SchemaURL: strOrEmpty(vs.MeterSchemaUrl),
471 },
472 }
473
474 if instrumentIsEmpty(inst) {
475 return sdkmetric.Instrument{}, errors.New("view_selector: empty selector not supporter")
476 }
477 return inst, nil
478 }
479
480 func stream(vs ViewStream) (sdkmetric.Stream, error) {
481 f, err := newIncludeExcludeFilter(vs.AttributeKeys)
482 if err != nil {
483 return sdkmetric.Stream{}, err
484 }
485 return sdkmetric.Stream{
486 Name: strOrEmpty(vs.Name),
487 Description: strOrEmpty(vs.Description),
488 Aggregation: aggregation(vs.Aggregation),
489 AttributeFilter: f,
490 }, nil
491 }
492
493 func aggregation(aggr *Aggregation) sdkmetric.Aggregation {
494 if aggr == nil {
495 return nil
496 }
497
498 if aggr.Base2ExponentialBucketHistogram != nil {
499 return sdkmetric.AggregationBase2ExponentialHistogram{
500 MaxSize: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxSize),
501 MaxScale: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxScale),
502 // Need to negate because config has the positive action RecordMinMax.
503 NoMinMax: !boolOrFalse(aggr.Base2ExponentialBucketHistogram.RecordMinMax),
504 }
505 }
506 if aggr.Default != nil {
507 // TODO: Understand what to set here.
508 return nil
509 }
510 if aggr.Drop != nil {
511 return sdkmetric.AggregationDrop{}
512 }
513 if aggr.ExplicitBucketHistogram != nil {
514 return sdkmetric.AggregationExplicitBucketHistogram{
515 Boundaries: aggr.ExplicitBucketHistogram.Boundaries,
516 // Need to negate because config has the positive action RecordMinMax.
517 NoMinMax: !boolOrFalse(aggr.ExplicitBucketHistogram.RecordMinMax),
518 }
519 }
520 if aggr.LastValue != nil {
521 return sdkmetric.AggregationLastValue{}
522 }
523 if aggr.Sum != nil {
524 return sdkmetric.AggregationSum{}
525 }
526 return nil
527 }
528
529 func instrumentKind(vsit *InstrumentType) (sdkmetric.InstrumentKind, error) {
530 if vsit == nil {
531 // Equivalent to instrumentKindUndefined.
532 return instrumentKindUndefined, nil
533 }
534
535 switch *vsit {
536 case InstrumentTypeCounter:
537 return sdkmetric.InstrumentKindCounter, nil
538 case InstrumentTypeUpDownCounter:
539 return sdkmetric.InstrumentKindUpDownCounter, nil
540 case InstrumentTypeHistogram:
541 return sdkmetric.InstrumentKindHistogram, nil
542 case InstrumentTypeObservableCounter:
543 return sdkmetric.InstrumentKindObservableCounter, nil
544 case InstrumentTypeObservableUpDownCounter:
545 return sdkmetric.InstrumentKindObservableUpDownCounter, nil
546 case InstrumentTypeObservableGauge:
547 return sdkmetric.InstrumentKindObservableGauge, nil
548 }
549
550 return instrumentKindUndefined, errors.New("instrument_type: invalid value")
551 }
552
553 func instrumentIsEmpty(i sdkmetric.Instrument) bool {
554 return i.Name == "" &&
555 i.Description == "" &&
556 i.Kind == instrumentKindUndefined &&
557 i.Unit == "" &&
558 i.Scope == zeroScope
559 }
560
561 func boolOrFalse(pBool *bool) bool {
562 if pBool == nil {
563 return false
564 }
565 return *pBool
566 }
567
568 func int32OrZero(pInt *int) int32 {
569 if pInt == nil {
570 return 0
571 }
572 i := *pInt
573 if i > math.MaxInt32 {
574 return math.MaxInt32
575 }
576 if i < math.MinInt32 {
577 return math.MinInt32
578 }
579 return int32(i)
580 }
581
582 func strOrEmpty(pStr *string) string {
583 if pStr == nil {
584 return ""
585 }
586 return *pStr
587 }