Debian Codegraph @

otelconf/v0.2.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.2.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 )
35
36 var zeroScope instrumentation.Scope
37
38 const instrumentKindUndefined = sdkmetric.InstrumentKind(0)
39
40 func meterProvider(cfg configOptions, res *resource.Resource) (metric.MeterProvider, shutdownFunc, error) {
41 if cfg.opentelemetryConfig.MeterProvider == nil {
42 return noop.NewMeterProvider(), noopShutdown, nil
43 }
44 opts := []sdkmetric.Option{
45 sdkmetric.WithResource(res),
46 }
47
48 var errs []error
49 for _, reader := range cfg.opentelemetryConfig.MeterProvider.Readers {
50 r, err := metricReader(cfg.ctx, reader)
51 if err == nil {
52 opts = append(opts, sdkmetric.WithReader(r))
53 } else {
54 errs = append(errs, err)
55 }
56 }
57 for _, vw := range cfg.opentelemetryConfig.MeterProvider.Views {
58 v, err := view(vw)
59 if err == nil {
60 opts = append(opts, sdkmetric.WithView(v))
61 } else {
62 errs = append(errs, err)
63 }
64 }
65
66 if len(errs) > 0 {
67 return noop.NewMeterProvider(), noopShutdown, errors.Join(errs...)
68 }
69
70 mp := sdkmetric.NewMeterProvider(opts...)
71 return mp, mp.Shutdown, nil
72 }
73
74 func metricReader(ctx context.Context, r MetricReader) (sdkmetric.Reader, error) {
75 if r.Periodic != nil && r.Pull != nil {
76 return nil, errors.New("must not specify multiple metric reader type")
77 }
78
79 if r.Periodic != nil {
80 var opts []sdkmetric.PeriodicReaderOption
81 if r.Periodic.Interval != nil {
82 opts = append(opts, sdkmetric.WithInterval(time.Duration(*r.Periodic.Interval)*time.Millisecond))
83 }
84
85 if r.Periodic.Timeout != nil {
86 opts = append(opts, sdkmetric.WithTimeout(time.Duration(*r.Periodic.Timeout)*time.Millisecond))
87 }
88 return periodicExporter(ctx, r.Periodic.Exporter, opts...)
89 }
90
91 if r.Pull != nil {
92 return pullReader(ctx, r.Pull.Exporter)
93 }
94 return nil, errors.New("no valid metric reader")
95 }
96
97 func pullReader(ctx context.Context, exporter MetricExporter) (sdkmetric.Reader, error) {
98 if exporter.Prometheus != nil {
99 return prometheusReader(ctx, exporter.Prometheus)
100 }
101 return nil, errors.New("no valid metric exporter")
102 }
103
104 func periodicExporter(ctx context.Context, exporter MetricExporter, opts ...sdkmetric.PeriodicReaderOption) (sdkmetric.Reader, error) {
105 if exporter.Console != nil && exporter.OTLP != nil {
106 return nil, errors.New("must not specify multiple exporters")
107 }
108 if exporter.Console != nil {
109 enc := json.NewEncoder(os.Stdout)
110 enc.SetIndent("", " ")
111
112 exp, err := stdoutmetric.New(
113 stdoutmetric.WithEncoder(enc),
114 )
115 if err != nil {
116 return nil, err
117 }
118 return sdkmetric.NewPeriodicReader(exp, opts...), nil
119 }
120 if exporter.OTLP != nil {
121 var err error
122 var exp sdkmetric.Exporter
123 switch exporter.OTLP.Protocol {
124 case protocolProtobufHTTP:
125 exp, err = otlpHTTPMetricExporter(ctx, exporter.OTLP)
126 case protocolProtobufGRPC:
127 exp, err = otlpGRPCMetricExporter(ctx, exporter.OTLP)
128 default:
129 return nil, fmt.Errorf("unsupported protocol %q", exporter.OTLP.Protocol)
130 }
131 if err != nil {
132 return nil, err
133 }
134 return sdkmetric.NewPeriodicReader(exp, opts...), nil
135 }
136 return nil, errors.New("no valid metric exporter")
137 }
138
139 func otlpHTTPMetricExporter(ctx context.Context, otlpConfig *OTLPMetric) (sdkmetric.Exporter, error) {
140 opts := []otlpmetrichttp.Option{}
141
142 if otlpConfig.Endpoint != "" {
143 u, err := url.ParseRequestURI(otlpConfig.Endpoint)
144 if err != nil {
145 return nil, err
146 }
147 opts = append(opts, otlpmetrichttp.WithEndpoint(u.Host))
148
149 if u.Scheme == "http" {
150 opts = append(opts, otlpmetrichttp.WithInsecure())
151 }
152 if u.Path != "" {
153 opts = append(opts, otlpmetrichttp.WithURLPath(u.Path))
154 }
155 }
156 if otlpConfig.Compression != nil {
157 switch *otlpConfig.Compression {
158 case compressionGzip:
159 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.GzipCompression))
160 case compressionNone:
161 opts = append(opts, otlpmetrichttp.WithCompression(otlpmetrichttp.NoCompression))
162 default:
163 return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
164 }
165 }
166 if otlpConfig.Timeout != nil {
167 opts = append(opts, otlpmetrichttp.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
168 }
169 if len(otlpConfig.Headers) > 0 {
170 opts = append(opts, otlpmetrichttp.WithHeaders(otlpConfig.Headers))
171 }
172 if otlpConfig.TemporalityPreference != nil {
173 switch *otlpConfig.TemporalityPreference {
174 case "delta":
175 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(deltaTemporality))
176 case "cumulative":
177 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(cumulativeTemporality))
178 case "lowmemory":
179 opts = append(opts, otlpmetrichttp.WithTemporalitySelector(lowMemory))
180 default:
181 return nil, fmt.Errorf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference)
182 }
183 }
184
185 return otlpmetrichttp.New(ctx, opts...)
186 }
187
188 func otlpGRPCMetricExporter(ctx context.Context, otlpConfig *OTLPMetric) (sdkmetric.Exporter, error) {
189 var opts []otlpmetricgrpc.Option
190
191 if otlpConfig.Endpoint != "" {
192 u, err := url.ParseRequestURI(otlpConfig.Endpoint)
193 if err != nil {
194 return nil, err
195 }
196 // ParseRequestURI leaves the Host field empty when no
197 // scheme is specified (i.e. localhost:4317). This check is
198 // here to support the case where a user may not specify a
199 // scheme. The code does its best effort here by using
200 // otlpConfig.Endpoint as-is in that case
201 if u.Host != "" {
202 opts = append(opts, otlpmetricgrpc.WithEndpoint(u.Host))
203 } else {
204 opts = append(opts, otlpmetricgrpc.WithEndpoint(otlpConfig.Endpoint))
205 }
206 if u.Scheme == "http" {
207 opts = append(opts, otlpmetricgrpc.WithInsecure())
208 }
209 }
210
211 if otlpConfig.Compression != nil {
212 switch *otlpConfig.Compression {
213 case compressionGzip:
214 opts = append(opts, otlpmetricgrpc.WithCompressor(*otlpConfig.Compression))
215 case compressionNone:
216 // none requires no options
217 default:
218 return nil, fmt.Errorf("unsupported compression %q", *otlpConfig.Compression)
219 }
220 }
221 if otlpConfig.Timeout != nil && *otlpConfig.Timeout > 0 {
222 opts = append(opts, otlpmetricgrpc.WithTimeout(time.Millisecond*time.Duration(*otlpConfig.Timeout)))
223 }
224 if len(otlpConfig.Headers) > 0 {
225 opts = append(opts, otlpmetricgrpc.WithHeaders(otlpConfig.Headers))
226 }
227 if otlpConfig.TemporalityPreference != nil {
228 switch *otlpConfig.TemporalityPreference {
229 case "delta":
230 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(deltaTemporality))
231 case "cumulative":
232 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(cumulativeTemporality))
233 case "lowmemory":
234 opts = append(opts, otlpmetricgrpc.WithTemporalitySelector(lowMemory))
235 default:
236 return nil, fmt.Errorf("unsupported temporality preference %q", *otlpConfig.TemporalityPreference)
237 }
238 }
239
240 return otlpmetricgrpc.New(ctx, opts...)
241 }
242
243 func cumulativeTemporality(sdkmetric.InstrumentKind) metricdata.Temporality {
244 return metricdata.CumulativeTemporality
245 }
246
247 func deltaTemporality(ik sdkmetric.InstrumentKind) metricdata.Temporality {
248 switch ik {
249 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram, sdkmetric.InstrumentKindObservableCounter:
250 return metricdata.DeltaTemporality
251 default:
252 return metricdata.CumulativeTemporality
253 }
254 }
255
256 func lowMemory(ik sdkmetric.InstrumentKind) metricdata.Temporality {
257 switch ik {
258 case sdkmetric.InstrumentKindCounter, sdkmetric.InstrumentKindHistogram:
259 return metricdata.DeltaTemporality
260 default:
261 return metricdata.CumulativeTemporality
262 }
263 }
264
265 func prometheusReader(ctx context.Context, prometheusConfig *Prometheus) (sdkmetric.Reader, error) {
266 var opts []otelprom.Option
267 if prometheusConfig.Host == nil {
268 return nil, errors.New("host must be specified")
269 }
270 if prometheusConfig.Port == nil {
271 return nil, errors.New("port must be specified")
272 }
273 if prometheusConfig.WithoutScopeInfo != nil && *prometheusConfig.WithoutScopeInfo {
274 opts = append(opts, otelprom.WithoutScopeInfo())
275 }
276
277 if prometheusConfig.WithoutTypeSuffix != nil && *prometheusConfig.WithoutTypeSuffix && prometheusConfig.WithoutUnits != nil && *prometheusConfig.WithoutUnits {
278 // NoTranslation preserves OTel dot-style label names (e.g. service.name)
279 // and suppresses metric name suffixes. The exporter's newConfig will
280 // automatically set withoutCounterSuffixes and withoutUnits when
281 // ShouldAddSuffixes() is false.
282 opts = append(opts, otelprom.WithTranslationStrategy(otlptranslator.NoTranslation))
283 } else {
284 opts = append(opts, otelprom.WithTranslationStrategy(otlptranslator.NoUTF8EscapingWithSuffixes))
285 }
286
287 if prometheusConfig.WithResourceConstantLabels != nil {
288 if prometheusConfig.WithResourceConstantLabels.Included != nil {
289 var keys []attribute.Key
290 for _, val := range prometheusConfig.WithResourceConstantLabels.Included {
291 keys = append(keys, attribute.Key(val))
292 }
293 otelprom.WithResourceAsConstantLabels(attribute.NewAllowKeysFilter(keys...))
294 }
295 if prometheusConfig.WithResourceConstantLabels.Excluded != nil {
296 var keys []attribute.Key
297 for _, val := range prometheusConfig.WithResourceConstantLabels.Included {
298 keys = append(keys, attribute.Key(val))
299 }
300 otelprom.WithResourceAsConstantLabels(attribute.NewDenyKeysFilter(keys...))
301 }
302 }
303
304 reg := prometheus.NewRegistry()
305 opts = append(opts, otelprom.WithRegisterer(reg))
306
307 reader, err := otelprom.New(opts...)
308 if err != nil {
309 return nil, fmt.Errorf("error creating otel prometheus exporter: %w", err)
310 }
311
312 mux := http.NewServeMux()
313 mux.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg}))
314 server := http.Server{
315 // Timeouts are necessary to make a server resilient to attacks, but ListenAndServe doesn't set any.
316 // We use values from this example: https://blog.cloudflare.com/exposing-go-on-the-internet/#:~:text=There%20are%20three%20main%20timeouts
317 ReadTimeout: 5 * time.Second,
318 WriteTimeout: 10 * time.Second,
319 IdleTimeout: 120 * time.Second,
320 Handler: mux,
321 }
322
323 // Remove surrounding "[]" from the host definition to allow users to define the host as "[::1]" or "::1".
324 host := *prometheusConfig.Host
325 if len(host) > 2 && host[0] == '[' && host[len(host)-1] == ']' {
326 host = host[1 : len(host)-1]
327 }
328
329 addr := net.JoinHostPort(host, strconv.Itoa(*prometheusConfig.Port))
330 lis, err := (&net.ListenConfig{}).Listen(context.Background(), "tcp", addr)
331 if err != nil {
332 return nil, errors.Join(
333 fmt.Errorf("binding address %s for Prometheus exporter: %w", addr, err),
334 reader.Shutdown(ctx),
335 )
336 }
337
338 // Only for testing reasons, add the address to the http Server, will not be used.
339 server.Addr = lis.Addr().String()
340
341 go func() {
342 if err := server.Serve(lis); err != nil && errors.Is(err, http.ErrServerClosed) {
343 otel.Handle(fmt.Errorf("the Prometheus HTTP server exited unexpectedly: %w", err))
344 }
345 }()
346
347 return readerWithServer{reader, &server}, nil
348 }
349
350 type readerWithServer struct {
351 sdkmetric.Reader
352 server *http.Server
353 }
354
355 func (rws readerWithServer) Shutdown(ctx context.Context) error {
356 return errors.Join(
357 rws.Reader.Shutdown(ctx),
358 rws.server.Shutdown(ctx),
359 )
360 }
361
362 func view(v View) (sdkmetric.View, error) {
363 if v.Selector == nil {
364 return nil, errors.New("view: no selector provided")
365 }
366
367 inst, err := instrument(*v.Selector)
368 if err != nil {
369 return nil, err
370 }
371
372 return sdkmetric.NewView(inst, stream(v.Stream)), nil
373 }
374
375 func instrument(vs ViewSelector) (sdkmetric.Instrument, error) {
376 kind, err := instrumentKind(vs.InstrumentType)
377 if err != nil {
378 return sdkmetric.Instrument{}, fmt.Errorf("view_selector: %w", err)
379 }
380 inst := sdkmetric.Instrument{
381 Name: strOrEmpty(vs.InstrumentName),
382 Unit: strOrEmpty(vs.Unit),
383 Kind: kind,
384 Scope: instrumentation.Scope{
385 Name: strOrEmpty(vs.MeterName),
386 Version: strOrEmpty(vs.MeterVersion),
387 SchemaURL: strOrEmpty(vs.MeterSchemaUrl),
388 },
389 }
390
391 if instrumentIsEmpty(inst) {
392 return sdkmetric.Instrument{}, errors.New("view_selector: empty selector not supporter")
393 }
394 return inst, nil
395 }
396
397 func stream(vs *ViewStream) sdkmetric.Stream {
398 if vs == nil {
399 return sdkmetric.Stream{}
400 }
401
402 return sdkmetric.Stream{
403 Name: strOrEmpty(vs.Name),
404 Description: strOrEmpty(vs.Description),
405 Aggregation: aggregation(vs.Aggregation),
406 AttributeFilter: attributeFilter(vs.AttributeKeys),
407 }
408 }
409
410 func attributeFilter(attributeKeys []string) attribute.Filter {
411 attrKeys := make([]attribute.Key, 0, len(attributeKeys))
412 for _, attrStr := range attributeKeys {
413 attrKeys = append(attrKeys, attribute.Key(attrStr))
414 }
415 return attribute.NewAllowKeysFilter(attrKeys...)
416 }
417
418 func aggregation(aggr *ViewStreamAggregation) sdkmetric.Aggregation {
419 if aggr == nil {
420 return nil
421 }
422
423 if aggr.Base2ExponentialBucketHistogram != nil {
424 return sdkmetric.AggregationBase2ExponentialHistogram{
425 MaxSize: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxSize),
426 MaxScale: int32OrZero(aggr.Base2ExponentialBucketHistogram.MaxScale),
427 // Need to negate because config has the positive action RecordMinMax.
428 NoMinMax: !boolOrFalse(aggr.Base2ExponentialBucketHistogram.RecordMinMax),
429 }
430 }
431 if aggr.Default != nil {
432 // TODO: Understand what to set here.
433 return nil
434 }
435 if aggr.Drop != nil {
436 return sdkmetric.AggregationDrop{}
437 }
438 if aggr.ExplicitBucketHistogram != nil {
439 return sdkmetric.AggregationExplicitBucketHistogram{
440 Boundaries: aggr.ExplicitBucketHistogram.Boundaries,
441 // Need to negate because config has the positive action RecordMinMax.
442 NoMinMax: !boolOrFalse(aggr.ExplicitBucketHistogram.RecordMinMax),
443 }
444 }
445 if aggr.LastValue != nil {
446 return sdkmetric.AggregationLastValue{}
447 }
448 if aggr.Sum != nil {
449 return sdkmetric.AggregationSum{}
450 }
451 return nil
452 }
453
454 func instrumentKind(vsit *ViewSelectorInstrumentType) (sdkmetric.InstrumentKind, error) {
455 if vsit == nil {
456 // Equivalent to instrumentKindUndefined.
457 return instrumentKindUndefined, nil
458 }
459
460 switch *vsit {
461 case ViewSelectorInstrumentTypeCounter:
462 return sdkmetric.InstrumentKindCounter, nil
463 case ViewSelectorInstrumentTypeUpDownCounter:
464 return sdkmetric.InstrumentKindUpDownCounter, nil
465 case ViewSelectorInstrumentTypeHistogram:
466 return sdkmetric.InstrumentKindHistogram, nil
467 case ViewSelectorInstrumentTypeObservableCounter:
468 return sdkmetric.InstrumentKindObservableCounter, nil
469 case ViewSelectorInstrumentTypeObservableUpDownCounter:
470 return sdkmetric.InstrumentKindObservableUpDownCounter, nil
471 case ViewSelectorInstrumentTypeObservableGauge:
472 return sdkmetric.InstrumentKindObservableGauge, nil
473 }
474
475 return instrumentKindUndefined, errors.New("instrument_type: invalid value")
476 }
477
478 func instrumentIsEmpty(i sdkmetric.Instrument) bool {
479 return i.Name == "" &&
480 i.Description == "" &&
481 i.Kind == instrumentKindUndefined &&
482 i.Unit == "" &&
483 i.Scope == zeroScope
484 }
485
486 func boolOrFalse(pBool *bool) bool {
487 if pBool == nil {
488 return false
489 }
490 return *pBool
491 }
492
493 func int32OrZero(pInt *int) int32 {
494 if pInt == nil {
495 return 0
496 }
497 i := *pInt
498 if i > math.MaxInt32 {
499 return math.MaxInt32
500 }
501 if i < math.MinInt32 {
502 return math.MinInt32
503 }
504 return int32(i)
505 }
506
507 func strOrEmpty(pStr *string) string {
508 if pStr == nil {
509 return ""
510 }
511 return *pStr
512 }