Debian Codegraph @

otelconf/v0.3.0/metric.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelconf // import "go.opentelemetry.io/contrib/otelconf/v0.3.0"
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, errors.New("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, errors.New("no valid metric reader")
96 }
97
98 func pullReader(ctx context.Context, exporter PullMetricExporter) (sdkmetric.Reader, error) {
99 if exporter.Prometheus != nil {
100 return prometheusReader(ctx, exporter.Prometheus)
101 }
102 return nil, errors.New("no valid metric exporter")
103 }
104
105 func periodicExporter(ctx context.Context, exporter PushMetricExporter, opts ...sdkmetric.PeriodicReaderOption) (sdkmetric.Reader, error) {
106 if exporter.Console != nil && exporter.OTLP != nil {
107 return nil, errors.New("must not specify multiple exporters")
108 }
109 if exporter.Console != nil {
110 enc := json.NewEncoder(os.Stdout)
111 enc.SetIndent("", " ")
112
113 exp, err := stdoutmetric.New(
114 stdoutmetric.WithEncoder(enc),
115 )
116 if err != nil {
117 return nil, err
118 }
119 return sdkmetric.NewPeriodicReader(exp, opts...), nil
120 }
121 if exporter.OTLP != nil && exporter.OTLP.Protocol != nil {
122 var err error
123 var exp sdkmetric.Exporter
124 switch *exporter.OTLP.Protocol {
125 case protocolProtobufHTTP:
126 exp, err = otlpHTTPMetricExporter(ctx, exporter.OTLP)
127 case protocolProtobufGRPC:
128 exp, err = otlpGRPCMetricExporter(ctx, exporter.OTLP)
129 default:
130 return nil, fmt.Errorf("unsupported protocol %q", *exporter.OTLP.Protocol)
131 }
132 if err != nil {
133 return nil, err
134 }
135 return sdkmetric.NewPeriodicReader(exp, opts...), nil
136 }
137 return nil, errors.New("no valid metric exporter")
138 }
139
140 func otlpHTTPMetricExporter(ctx context.Context, otlpConfig *OTLPMetric) (sdkmetric.Exporter, error) {
141 opts := []otlpmetrichttp.Option{}
142
143 if otlpConfig.Endpoint != nil {
144 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
145 if err != nil {
146 return nil, err
147 }
148 opts = append(opts, otlpmetrichttp.WithEndpoint(u.Host))
149
150 if u.Scheme == "http" {
151 opts = append(opts, otlpmetrichttp.WithInsecure())
152 } else {
153 tlsConfig, err := tls.CreateConfig(otlpConfig.Certificate, otlpConfig.ClientCertificate, otlpConfig.ClientKey)
154 if err != nil {
155 return nil, err
156 }
157 opts = append(opts, otlpmetrichttp.WithTLSClientConfig(tlsConfig))
158 }
159 if u.Path != "" {
160 opts = append(opts, otlpmetrichttp.WithURLPath(u.Path))
161 }
162 }
163 if otlpConfig.Compression != nil {
164 switch *otlpConfig.Compression {
165 case compressionGzip:
166 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression))
167 case compressionNone:
168 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.NoCompression))
169 default:
170 return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
171 }
172 }
173 if otlpConfig.Timeout != nil {
174 opts = append(opts, otlpmetrichttp.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
175 }
176 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
177 if err != nil {
178 return nil, err
179 }
180 if len(headersConfig) > 0 {
181 opts = append(opts, otlpmetrichttp.WithHeaders(headersConfig))
182 }
183 if otlpConfig.TemporalityPreference != nil {
184 switch *otlpConfig.TemporalityPreference {
185 case "delta":
186 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(deltaTemporality))
187 case "cumulative":
188 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(cumulativeTemporality))
189 case "lowmemory":
190 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(lowMemory))
191 default:
192 return nil, fmt.Errorf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference)
193 }
194 }
195
196 return otlpmetrichttp.New(ctx, opts...)
197 }
198
199 func otlpGRPCMetricExporter(ctx context.Context, otlpConfig *OTLPMetric) (sdkmetric.Exporter, error) {
200 var opts []otlpmetricgrpc.Option
201
202 if otlpConfig.Endpoint != nil {
203 u, err := url.ParseRequestURI(*otlpConfig.Endpoint)
204 if err != nil {
205 return nil, err
206 }
207 // ParseRequestURI leaves the Host field empty when no
208 // scheme is specified (i.e. localhost:4317). This check is
209 // here to support the case where a user may not specify a
210 // scheme. The code does its best effort here by using
211 // otlpConfig.Endpoint as-is in that case
212 if u.Host != "" {
213 opts = append(opts, otlpmetricgrpc.WithEndpoint(u.Host))
214 } else {
215 opts = append(opts, otlpmetricgrpc.WithEndpoint(*otlpConfig.Endpoint))
216 }
217 if u.Scheme == "http" || (u.Scheme != "https" && otlpConfig.Insecure != nil && *otlpConfig.Insecure) {
218 opts = append(opts, otlpmetricgrpc.WithInsecure())
219 }
220 }
221
222 if otlpConfig.Compression != nil {
223 switch *otlpConfig.Compression {
224 case compressionGzip:
225 opts = append(opts, otlpmetricgrpc.WithCompressor(*otlpConfig.Compression))
226 case compressionNone:
227 // none requires no options
228 default:
229 return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
230 }
231 }
232 if otlpConfig.Timeout != nil && *otlpConfig.Timeout > 0 {
233 opts = append(opts, otlpmetricgrpc.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
234 }
235 headersConfig, err := createHeadersConfig(otlpConfig.Headers, otlpConfig.HeadersList)
236 if err != nil {
237 return nil, err
238 }
239 if len(headersConfig) > 0 {
240 opts = append(opts, otlpmetricgrpc.WithHeaders(headersConfig))
241 }
242 if otlpConfig.TemporalityPreference != nil {
243 switch *otlpConfig.TemporalityPreference {
244 case "delta":
245 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(deltaTemporality))
246 case "cumulative":
247 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(cumulativeTemporality))
248 case "lowmemory":
249 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(lowMemory))
250 default:
251 return nil, fmt.Errorf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference)
252 }
253 }
254
255 if otlpConfig.Certificate != nil || otlpConfig.ClientCertificate != nil || otlpConfig.ClientKey != nil {
256 tlsConfig, err := tls.CreateConfig(otlpConfig.Certificate, otlpConfig.ClientCertificate, otlpConfig.ClientKey)
257 if err != nil {
258 return nil, err
259 }
260 opts = append(opts, otlpmetricgrpc.WithTLSCredentials(credentials.NewTLS(tlsConfig)))
261 }
262
263 return otlpmetricgrpc.New(ctx, opts...)
264 }
265
266 func cumulativeTemporality(sdkmetric.InstrumentKind) metricdata.Temporality {
267 return metricdata.CumulativeTemporality
268 }
269
270 func deltaTemporality(ik sdkmetric.InstrumentKind) metricdata.Temporality {
271 switch ik {
272 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram, sdkmetric.InstrumentKindObservableCounter:
273 return metricdata.DeltaTemporality
274 default:
275 return metricdata.CumulativeTemporality
276 }
277 }
278
279 func lowMemory(ik sdkmetric.InstrumentKind) metricdata.Temporality {
280 switch ik {
281 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram:
282 return metricdata.DeltaTemporality
283 default:
284 return metricdata.CumulativeTemporality
285 }
286 }
287
288 // newIncludeExcludeFilter returns a Filter that includes attributes
289 // in the include list and excludes attributes in the excludes list.
290 // It returns an error if an attribute is in both lists
291 //
292 // If IncludeExclude is empty a include-all filter is returned.
293 func newIncludeExcludeFilter(lists *IncludeExclude) (attribute.Filter, error) {
294 if lists == nil {
295 return func(attribute.KeyValue) bool { return true }, nil
296 }
297
298 included := make(map[attribute.Key]struct{})
299 for _, k := range lists.Included {
300 included[attribute.Key(k)] = struct{}{}
301 }
302 excluded := make(map[attribute.Key]struct{})
303 for _, k := range lists.Excluded {
304 if _, ok := included[attribute.Key(k)]; ok {
305 return nil, fmt.Errorf("attribute cannot be in both include and exclude list: %s", k)
306 }
307 excluded[attribute.Key(k)] = struct{}{}
308 }
309 return func(kv attribute.KeyValue) bool {
310 // check if a value is excluded first
311 if _, ok := excluded[kv.Key]; ok {
312 return false
313 }
314
315 if len(included) == 0 {
316 return true
317 }
318
319 _, ok := included[kv.Key]
320 return ok
321 }, nil
322 }
323
324 func prometheusReader(ctx context.Context, prometheusConfig *Prometheus) (sdkmetric.Reader, error) {
325 if prometheusConfig.Host == nil {
326 return nil, errors.New("host must be specified")
327 }
328 if prometheusConfig.Port == nil {
329 return nil, errors.New("port must be specified")
330 }
331
332 opts, err := prometheusReaderOpts(prometheusConfig)
333 if err != nil {
334 return nil, err
335 }
336
337 reg := prometheus.NewRegistry()
338 opts = append(opts, otelprom.WithRegisterer(reg))
339
340 reader, err := otelprom.New(opts...)
341 if err != nil {
342 return nil, fmt.Errorf("error creating otel prometheus exporter: %w", err)
343 }
344
345 mux := http.NewServeMux()
346 mux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
347 server := http.Server{
348 // Timeouts are necessary to make a server resilient to attacks.
349 // We use values from this example: https://blog.cloudflare.com/exposing-go-on-the-internet/#:~:text=There%20are%20three%20main%20timeouts
350 ReadTimeout: 5 * time.Second,
351 WriteTimeout: 10 * time.Second,
352 IdleTimeout: 120 * time.Second,
353 Handler: mux,
354 }
355
356 // Remove surrounding "[]" from the host definition to allow users to define the host as "[::1]" or "::1".
357 host := *prometheusConfig.Host
358 if len(host) > 2 && host[0] == '[' && host[len(host)-1] == ']' {
359 host = host[1 : len(host)-1]
360 }
361
362 addr := net.JoinHostPort(host, strconv.Itoa(*prometheusConfig.Port))
363 lis, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", addr)
364 if err != nil {
365 return nil, errors.Join(
366 fmt.Errorf("binding address %s for Prometheus exporter: %w", addr, err),
367 reader.Shutdown(ctx),
368 )
369 }
370
371 // Only for testing reasons, add the address to the http Server, will not be used.
372 server.Addr = lis.Addr().String()
373
374 go func() {
375 if err := server.Serve(lis); err != nil && !errors.Is(err, http.ErrServerClosed) {
376 otel.Handle(fmt.Errorf("the Prometheus HTTP server exited unexpectedly: %w", err))
377 }
378 }()
379
380 return readerWithServer{reader, &server}, nil
381 }
382
383 func prometheusReaderOpts(prometheusConfig *Prometheus) ([]otelprom.Option, error) {
384 var opts []otelprom.Option
385 if prometheusConfig.WithoutScopeInfo != nil && *prometheusConfig.WithoutScopeInfo {
386 opts = append(opts, otelprom.WithoutScopeInfo())
387 }
388
389 if prometheusConfig.WithoutTypeSuffix != nil && *prometheusConfig.WithoutTypeSuffix && prometheusConfig.WithoutUnits != nil && *prometheusConfig.WithoutUnits {
390 // NoTranslation preserves OTel dot-style label names (e.g. service.name)
391 // and suppresses metric name suffixes. The exporter's newConfig will
392 // automatically set withoutCounterSuffixes and withoutUnits when
393 // ShouldAddSuffixes() is false.
394 opts = append(opts, otelprom.WithTranslationStrategy(otlptranslator.NoTranslation))
395 } else {
396 opts = append(opts, otelprom.WithTranslationStrategy(otlptranslator.NoUTF8EscapingWithSuffixes))
397 }
398
399 if prometheusConfig.WithResourceConstantLabels != nil {
400 f, err := newIncludeExcludeFilter(prometheusConfig.WithResourceConstantLabels)
401 if err != nil {
402 return nil, err
403 }
404 opts = append(opts, otelprom.WithResourceAsConstantLabels(f))
405 }
406
407 return opts, nil
408 }
409
410 type readerWithServer struct {
411 sdkmetric.Reader
412 server *http.Server
413 }
414
415 func (rws readerWithServer) Shutdown(ctx context.Context) error {
416 return errors.Join(
417 rws.Reader.Shutdown(ctx),
418 rws.server.Shutdown(ctx),
419 )
420 }
421
422 func view(v View) (sdkmetric.View, error) {
423 if v.Selector == nil {
424 return nil, errors.New("view: no selector provided")
425 }
426
427 inst, err := instrument(*v.Selector)
428 if err != nil {
429 return nil, err
430 }
431
432 s, err := stream(v.Stream)
433 if err != nil {
434 return nil, err
435 }
436 return sdkmetric.NewView(inst, s), nil
437 }
438
439 func instrument(vs ViewSelector) (sdkmetric.Instrument, error) {
440 kind, err := instrumentKind(vs.InstrumentType)
441 if err != nil {
442 return sdkmetric.Instrument{}, fmt.Errorf("view_selector: %w", err)
443 }
444 inst := sdkmetric.Instrument{
445 Name: strOrEmpty(vs.InstrumentName),
446 Unit: strOrEmpty(vs.Unit),
447 Kind: kind,
448 Scope: instrumentation.Scope{
449 Name: strOrEmpty(vs.MeterName),
450 Version: strOrEmpty(vs.MeterVersion),
451 SchemaURL: strOrEmpty(vs.MeterSchemaUrl),
452 },
453 }
454
455 if instrumentIsEmpty(inst) {
456 return sdkmetric.Instrument{}, errors.New("view_selector: empty selector not supporter")
457 }
458 return inst, nil
459 }
460
461 func stream(vs *ViewStream) (sdkmetric.Stream, error) {
462 if vs == nil {
463 return sdkmetric.Stream{}, nil
464 }
465
466 f, err := newIncludeExcludeFilter(vs.AttributeKeys)
467 if err != nil {
468 return sdkmetric.Stream{}, err
469 }
470 return sdkmetric.Stream{
471 Name: strOrEmpty(vs.Name),
472 Description: strOrEmpty(vs.Description),
473 Aggregation: aggregation(vs.Aggregation),
474 AttributeFilter: f,
475 }, nil
476 }
477
478 func aggregation(aggr *ViewStreamAggregation) sdkmetric.Aggregation {
479 if aggr == nil {
480 return nil
481 }
482
483 if aggr.Base2ExponentialBucketHistogram != nil {
484 return sdkmetric.AggregationBase2ExponentialHistogram{
485 MaxSize: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxSize),
486 MaxScale: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxScale),
487 // Need to negate because config has the positive action RecordMinMax.
488 NoMinMax: !boolOrFalse(aggr.Base2ExponentialBucketHistogram.RecordMinMax),
489 }
490 }
491 if aggr.Default != nil {
492 // TODO: Understand what to set here.
493 return nil
494 }
495 if aggr.Drop != nil {
496 return sdkmetric.AggregationDrop{}
497 }
498 if aggr.ExplicitBucketHistogram != nil {
499 return sdkmetric.AggregationExplicitBucketHistogram{
500 Boundaries: aggr.ExplicitBucketHistogram.Boundaries,
501 // Need to negate because config has the positive action RecordMinMax.
502 NoMinMax: !boolOrFalse(aggr.ExplicitBucketHistogram.RecordMinMax),
503 }
504 }
505 if aggr.LastValue != nil {
506 return sdkmetric.AggregationLastValue{}
507 }
508 if aggr.Sum != nil {
509 return sdkmetric.AggregationSum{}
510 }
511 return nil
512 }
513
514 func instrumentKind(vsit *ViewSelectorInstrumentType) (sdkmetric.InstrumentKind, error) {
515 if vsit == nil {
516 // Equivalent to instrumentKindUndefined.
517 return instrumentKindUndefined, nil
518 }
519
520 switch *vsit {
521 case ViewSelectorInstrumentTypeCounter:
522 return sdkmetric.InstrumentKindCounter, nil
523 case ViewSelectorInstrumentTypeUpDownCounter:
524 return sdkmetric.InstrumentKindUpDownCounter, nil
525 case ViewSelectorInstrumentTypeHistogram:
526 return sdkmetric.InstrumentKindHistogram, nil
527 case ViewSelectorInstrumentTypeObservableCounter:
528 return sdkmetric.InstrumentKindObservableCounter, nil
529 case ViewSelectorInstrumentTypeObservableUpDownCounter:
530 return sdkmetric.InstrumentKindObservableUpDownCounter, nil
531 case ViewSelectorInstrumentTypeObservableGauge:
532 return sdkmetric.InstrumentKindObservableGauge, nil
533 }
534
535 return instrumentKindUndefined, errors.New("instrument_type: invalid value")
536 }
537
538 func instrumentIsEmpty(i sdkmetric.Instrument) bool {
539 return i.Name == "" &&
540 i.Description == "" &&
541 i.Kind == instrumentKindUndefined &&
542 i.Unit == "" &&
543 i.Scope == zeroScope
544 }
545
546 func boolOrFalse(pBool *bool) bool {
547 if pBool == nil {
548 return false
549 }
550 return *pBool
551 }
552
553 func int32OrZero(pInt *int) int32 {
554 if pInt == nil {
555 return 0
556 }
557 i := *pInt
558 if i > math.MaxInt32 {
559 return math.MaxInt32
560 }
561 if i < math.MinInt32 {
562 return math.MinInt32
563 }
564 return int32(i)
565 }
566
567 func strOrEmpty(pStr *string) string {
568 if pStr == nil {
569 return ""
570 }
571 return *pStr
572 }