Debian Codegraph @

event/otel/metric.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package otel
6
7 import (
8 "context"
9 "errors"
10 "fmt"
11 "sync"
12
13 "go.opentelemetry.io/otel/attribute"
14 "go.opentelemetry.io/otel/metric"
15 "golang.org/x/exp/event"
16 )
17
18 // MetricHandler is an event.Handler for OpenTelemetry metrics.
19 // Its Event method handles Metric events and ignores all others.
20 type MetricHandler struct {
21 meter metric.Meter
22 mu sync.Mutex
23 // A map from event.Metrics to, effectively, otel Meters.
24 // But since the only thing we need from the Meter is recording a value, we
25 // use a function for that closes over the Meter itself.
26 recordFuncs map[event.Metric]recordFunc
27 }
28
29 type recordFunc func(context.Context, event.Label, []attribute.KeyValue)
30
31 var _ event.Handler = (*MetricHandler)(nil)
32
33 // NewMetricHandler creates a new MetricHandler.
34 func NewMetricHandler(m metric.Meter) *MetricHandler {
35 return &MetricHandler{
36 meter: m,
37 recordFuncs: map[event.Metric]recordFunc{},
38 }
39 }
40
41 func (m *MetricHandler) Event(ctx context.Context, e *event.Event) context.Context {
42 if e.Kind != event.MetricKind {
43 return ctx
44 }
45 // Get the otel instrument corresponding to the event's MetricDescriptor,
46 // or create a new one.
47 mi, ok := event.MetricKey.Find(e)
48 if !ok {
49 panic(errors.New("no metric key for metric event"))
50 }
51 em := mi.(event.Metric)
52 lval := e.Find(event.MetricVal)
53 if !lval.HasValue() {
54 panic(errors.New("no metric value for metric event"))
55 }
56 rf := m.getRecordFunc(em)
57 if rf == nil {
58 panic(fmt.Errorf("unable to record for metric %v", em))
59 }
60 rf(ctx, lval, labelsToAttributes(e.Labels))
61 return ctx
62 }
63
64 func (m *MetricHandler) getRecordFunc(em event.Metric) recordFunc {
65 m.mu.Lock()
66 defer m.mu.Unlock()
67 if f, ok := m.recordFuncs[em]; ok {
68 return f
69 }
70 f, err := m.newRecordFunc(em)
71 if err != nil {
72 panic(err)
73 }
74 m.recordFuncs[em] = f
75 return f
76 }
77
78 func (m *MetricHandler) newRecordFunc(em event.Metric) (recordFunc, error) {
79 opts := em.Options()
80 name := opts.Namespace + "/" + em.Name()
81 switch em.(type) {
82 case *event.Counter:
83 opts := []metric.Int64CounterOption{
84 metric.WithDescription(opts.Description),
85 metric.WithUnit(string(opts.Unit)),
86 }
87 c, err := m.meter.Int64Counter(name, opts...)
88 if err != nil {
89 return nil, err
90 }
91 return func(ctx context.Context, l event.Label, attrs []attribute.KeyValue) {
92 c.Add(ctx, l.Int64(), metric.WithAttributes(attrs...))
93 }, nil
94
95 case *event.FloatGauge:
96 g, err := m.meter.Float64UpDownCounter(name,
97 metric.WithDescription(opts.Description),
98 metric.WithUnit(string(opts.Unit)))
99 if err != nil {
100 return nil, err
101 }
102 return func(ctx context.Context, l event.Label, attrs []attribute.KeyValue) {
103 g.Add(ctx, l.Float64(), metric.WithAttributes(attrs...))
104 }, nil
105
106 case *event.DurationDistribution:
107 r, err := m.meter.Int64Histogram(name,
108 metric.WithDescription(opts.Description),
109 metric.WithUnit(string(opts.Unit)))
110 if err != nil {
111 return nil, err
112 }
113
114 return func(ctx context.Context, l event.Label, attrs []attribute.KeyValue) {
115 r.Record(ctx, l.Duration().Nanoseconds(), metric.WithAttributes(attrs...))
116 }, nil
117
118 default:
119 return nil, nil
120 }
121 }
122
123 func labelsToAttributes(ls []event.Label) []attribute.KeyValue {
124 var attrs []attribute.KeyValue
125 for _, l := range ls {
126 if l.Name == string(event.MetricKey) || l.Name == string(event.MetricVal) {
127 continue
128 }
129 attrs = append(attrs, labelToAttribute(l))
130 }
131 return attrs
132 }
133
134 func labelToAttribute(l event.Label) attribute.KeyValue {
135 switch {
136 case l.IsString():
137 return attribute.String(l.Name, l.String())
138 case l.IsInt64():
139 return attribute.Int64(l.Name, l.Int64())
140 case l.IsFloat64():
141 return attribute.Float64(l.Name, l.Float64())
142 case l.IsBool():
143 return attribute.Bool(l.Name, l.Bool())
144 default: // including uint64
145 panic(fmt.Errorf("cannot convert label value of type %T to attribute.KeyValue", l.Interface()))
146 }
147 }