Debian Codegraph @

sdk/metric/internal/observ/instrumentation.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package observ provides experimental observability instrumentation for the
5 // metric reader.
6 package observ // import "go.opentelemetry.io/otel/sdk/metric/internal/observ"
7
8 import (
9 "context"
10 "fmt"
11 "sync"
12 "time"
13
14 "go.opentelemetry.io/otel"
15 "go.opentelemetry.io/otel/attribute"
16 "go.opentelemetry.io/otel/metric"
17 "go.opentelemetry.io/otel/sdk"
18 "go.opentelemetry.io/otel/sdk/internal/x"
19 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
20 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
21 )
22
23 const (
24 // ScopeName is the unique name of the meter used for instrumentation.
25 ScopeName = "go.opentelemetry.io/otel/sdk/metric/internal/observ"
26
27 // SchemaURL is the schema URL of the metrics produced by this
28 // instrumentation.
29 SchemaURL = semconv.SchemaURL
30 )
31
32 var (
33 measureAttrsPool = &sync.Pool{
34 New: func() any {
35 const n = 1 + // component.name
36 1 + // component.type
37 1 // error.type
38 s := make([]attribute.KeyValue, 0, n)
39 // Return a pointer to a slice instead of a slice itself
40 // to avoid allocations on every call.
41 return &s
42 },
43 }
44
45 recordOptPool = &sync.Pool{
46 New: func() any {
47 const n = 1 // WithAttributeSet
48 o := make([]metric.RecordOption, 0, n)
49 return &o
50 },
51 }
52 )
53
54 func get[T any](p *sync.Pool) *[]T { return p.Get().(*[]T) }
55
56 func put[T any](p *sync.Pool, s *[]T) {
57 *s = (*s)[:0] // Reset.
58 p.Put(s)
59 }
60
61 // ComponentName returns the component name for the metric reader with the
62 // provided ComponentType and ID.
63 func ComponentName(componentType string, id int64) string {
64 return fmt.Sprintf("%s/%d", componentType, id)
65 }
66
67 // Instrumentation is experimental instrumentation for the metric reader.
68 type Instrumentation struct {
69 colDuration metric.Float64Histogram
70
71 attrs []attribute.KeyValue
72 recOpt metric.RecordOption
73 }
74
75 // NewInstrumentation returns instrumentation for metric reader with the provided component
76 // type (such as periodic and manual metric reader) and ID. It uses the global
77 // MeterProvider to create the instrumentation.
78 //
79 // The id should be the unique metric reader instance ID. It is used
80 // to set the "component.name" attribute.
81 //
82 // If the experimental observability is disabled, nil is returned.
83 func NewInstrumentation(componentType string, id int64) (*Instrumentation, error) {
84 if !x.Observability.Enabled() {
85 return nil, nil
86 }
87
88 i := &Instrumentation{
89 attrs: []attribute.KeyValue{
90 semconv.OTelComponentName(ComponentName(componentType, id)),
91 semconv.OTelComponentTypeKey.String(componentType),
92 },
93 }
94
95 r := attribute.NewSet(i.attrs...)
96 i.recOpt = metric.WithAttributeSet(r)
97
98 meter := otel.GetMeterProvider().Meter(
99 ScopeName,
100 metric.WithInstrumentationVersion(sdk.Version()),
101 metric.WithSchemaURL(SchemaURL),
102 )
103
104 colDuration, err := otelconv.NewSDKMetricReaderCollectionDuration(meter)
105 if err != nil {
106 err = fmt.Errorf("failed to create collection duration metric: %w", err)
107 }
108 i.colDuration = colDuration.Inst()
109
110 return i, err
111 }
112
113 // CollectMetrics instruments the collect method of metric reader. It returns an
114 // [CollectOp] that must have its [CollectOp.End] method called when the
115 // collection end.
116 func (i *Instrumentation) CollectMetrics(ctx context.Context) CollectOp {
117 start := time.Now()
118
119 return CollectOp{
120 ctx: ctx,
121 start: start,
122 inst: i,
123 }
124 }
125
126 // CollectOp tracks the collect operation being observed by
127 // [Instrumentation.CollectMetrics].
128 type CollectOp struct {
129 ctx context.Context
130 start time.Time
131
132 inst *Instrumentation
133 }
134
135 // End completes the observation of the operation being observed by a call to
136 // [Instrumentation.CollectMetrics].
137 //
138 // Any error that is encountered is provided as err.
139 func (e CollectOp) End(err error) {
140 recOpt := get[metric.RecordOption](recordOptPool)
141 defer put(recordOptPool, recOpt)
142 *recOpt = append(*recOpt, e.inst.recordOption(err))
143
144 d := time.Since(e.start).Seconds()
145 e.inst.colDuration.Record(e.ctx, d, *recOpt...)
146 }
147
148 // recordOption returns a RecordOption with attributes representing the
149 // outcome of the collection being recorded.
150 //
151 // If err is nil, the default recOpt of the Instrumentation is returned.
152 //
153 // Otherwise, a new RecordOption is returned with the base attributes of the
154 // Instrumentation plus the error.type attribute set to the type of the error.
155 func (i *Instrumentation) recordOption(err error) metric.RecordOption {
156 if err == nil {
157 return i.recOpt
158 }
159
160 attrs := get[attribute.KeyValue](measureAttrsPool)
161 defer put(measureAttrsPool, attrs)
162 *attrs = append(*attrs, i.attrs...)
163 *attrs = append(*attrs, semconv.ErrorType(err))
164
165 // Do not inefficiently make a copy of attrs by using WithAttributes
166 // instead of WithAttributeSet.
167 return metric.WithAttributeSet(attribute.NewSet(*attrs...))
168 }