Debian Codegraph @

exporters/prometheus/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
5 // for the prometheus exporter.
6 package observ // import "go.opentelemetry.io/otel/exporters/prometheus/internal/observ"
7
8 import (
9 "context"
10 "errors"
11 "fmt"
12 "sync"
13 "time"
14
15 "go.opentelemetry.io/otel"
16 "go.opentelemetry.io/otel/attribute"
17 "go.opentelemetry.io/otel/exporters/prometheus/internal"
18 "go.opentelemetry.io/otel/exporters/prometheus/internal/x"
19 "go.opentelemetry.io/otel/metric"
20 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
21 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
22 )
23
24 const (
25 // ComponentType uniquely identifies the OpenTelemetry Exporter component
26 // being instrumented.
27 ComponentType = "go.opentelemetry.io/otel/exporters/prometheus/prometheus.Exporter"
28
29 // ScopeName is the unique name of the meter used for instrumentation.
30 ScopeName = "go.opentelemetry.io/otel/exporters/prometheus/internal/observ"
31
32 // SchemaURL is the schema URL of the metrics produced by this
33 // instrumentation.
34 SchemaURL = semconv.SchemaURL
35
36 // Version is the current version of this instrumentation.
37 //
38 // This matches the version of the exporter.
39 Version = internal.Version
40 )
41
42 var (
43 measureAttrsPool = &sync.Pool{
44 New: func() any {
45 // "component.name" + "component.type" + "error.type"
46 const n = 1 + 1 + 1
47 s := make([]attribute.KeyValue, 0, n)
48 // Return a pointer to a slice instead of a slice itself
49 // to avoid allocations on every call.
50 return &s
51 },
52 }
53
54 addOptPool = &sync.Pool{
55 New: func() any {
56 const n = 1 // WithAttributeSet
57 o := make([]metric.AddOption, 0, n)
58 return &o
59 },
60 }
61
62 recordOptPool = &sync.Pool{
63 New: func() any {
64 const n = 1 // WithAttributeSet
65 o := make([]metric.RecordOption, 0, n)
66 return &o
67 },
68 }
69 )
70
71 func get[T any](p *sync.Pool) *[]T { return p.Get().(*[]T) }
72
73 func put[T any](p *sync.Pool, s *[]T) {
74 *s = (*s)[:0] // Reset.
75 p.Put(s)
76 }
77
78 func ComponentName(id int64) string {
79 return fmt.Sprintf("%s/%d", ComponentType, id)
80 }
81
82 type Instrumentation struct {
83 inflightMetric metric.Int64UpDownCounter
84 exportedMetric metric.Int64Counter
85 operationDuration metric.Float64Histogram
86 collectionDuration metric.Float64Histogram
87
88 attrs []attribute.KeyValue
89 setOpt metric.MeasurementOption
90 }
91
92 func NewInstrumentation(id int64) (*Instrumentation, error) {
93 if !x.Observability.Enabled() {
94 return nil, nil
95 }
96
97 i := &Instrumentation{
98 attrs: []attribute.KeyValue{
99 semconv.OTelComponentName(ComponentName(id)),
100 semconv.OTelComponentTypeKey.String(ComponentType),
101 },
102 }
103
104 s := attribute.NewSet(i.attrs...)
105 i.setOpt = metric.WithAttributeSet(s)
106
107 mp := otel.GetMeterProvider()
108 m := mp.Meter(
109 ScopeName,
110 metric.WithInstrumentationVersion(Version),
111 metric.WithSchemaURL(SchemaURL),
112 )
113
114 var err, e error
115
116 inflightMetric, e := otelconv.NewSDKExporterMetricDataPointInflight(m)
117 if e != nil {
118 e = fmt.Errorf("failed to create inflight metric: %w", e)
119 err = errors.Join(err, e)
120 }
121 i.inflightMetric = inflightMetric.Inst()
122
123 exportedMetric, e := otelconv.NewSDKExporterMetricDataPointExported(m)
124 if e != nil {
125 e = fmt.Errorf("failed to create exported metric: %w", e)
126 err = errors.Join(err, e)
127 }
128 i.exportedMetric = exportedMetric.Inst()
129
130 operationDuration, e := otelconv.NewSDKExporterOperationDuration(m)
131 if e != nil {
132 e = fmt.Errorf("failed to create operation duration metric: %w", e)
133 err = errors.Join(err, e)
134 }
135 i.operationDuration = operationDuration.Inst()
136
137 collectionDuration, e := otelconv.NewSDKMetricReaderCollectionDuration(m)
138 if e != nil {
139 e = fmt.Errorf("failed to create collection duration metric: %w", e)
140 err = errors.Join(err, e)
141 }
142 i.collectionDuration = collectionDuration.Inst()
143
144 return i, err
145 }
146
147 // RecordOperationDuration starts the timing of an operation.
148 //
149 // It returns a [Timer] that tracks the operation duration. The [Timer.Stop]
150 // method must be called when the operation completes.
151 func (i *Instrumentation) RecordOperationDuration(ctx context.Context) Timer {
152 return Timer{
153 ctx: ctx,
154 start: time.Now(),
155 inst: i,
156 hist: i.operationDuration,
157 }
158 }
159
160 // RecordCollectionDuration starts the timing of a collection operation.
161 //
162 // It returns a [Timer] that tracks the collection duration. The [Timer.Stop]
163 // method must be called when the collection completes.
164 func (i *Instrumentation) RecordCollectionDuration(ctx context.Context) Timer {
165 return Timer{
166 ctx: ctx,
167 start: time.Now(),
168 inst: i,
169 hist: i.collectionDuration,
170 }
171 }
172
173 // Timer tracks the duration of an operation.
174 type Timer struct {
175 ctx context.Context
176 start time.Time
177
178 inst *Instrumentation
179 hist metric.Float64Histogram
180 }
181
182 // Stop ends the timing operation and records the elapsed duration.
183 //
184 // If err is non-nil, an appropriate error type attribute will be included.
185 func (t Timer) Stop(err error) {
186 if !t.hist.Enabled(t.ctx) {
187 return
188 }
189 recordOpt := get[metric.RecordOption](recordOptPool)
190 defer put(recordOptPool, recordOpt)
191 *recordOpt = append(*recordOpt, t.inst.setOpt)
192
193 if err != nil {
194 attrs := get[attribute.KeyValue](measureAttrsPool)
195 defer put(measureAttrsPool, attrs)
196 *attrs = append(*attrs, t.inst.attrs...)
197 *attrs = append(*attrs, semconv.ErrorType(err))
198
199 set := attribute.NewSet(*attrs...)
200 *recordOpt = append((*recordOpt)[:0], metric.WithAttributeSet(set))
201 }
202 t.hist.Record(t.ctx, time.Since(t.start).Seconds(), *recordOpt...)
203 }
204
205 // ExportMetrics starts the observation of a metric export operation.
206 //
207 // It returns an [ExportOp] that tracks the export operation. The
208 // [ExportOp.End] method must be called when the export completes.
209 func (i *Instrumentation) ExportMetrics(ctx context.Context, n int64) ExportOp {
210 if i.inflightMetric.Enabled(ctx) {
211 addOpt := get[metric.AddOption](addOptPool)
212 defer put(addOptPool, addOpt)
213 *addOpt = append(*addOpt, i.setOpt)
214 i.inflightMetric.Add(ctx, n, *addOpt...)
215 }
216
217 return ExportOp{ctx: ctx, nMetrics: n, inst: i}
218 }
219
220 // ExportOp tracks a metric export operation.
221 type ExportOp struct {
222 ctx context.Context
223 nMetrics int64
224
225 inst *Instrumentation
226 }
227
228 // End ends the observation of a metric export operation.
229 //
230 // The success parameter is the number of metrics that were successfully
231 // exported. If a non-nil error is provided, the number of failed metrics will
232 // be recorded with the error type attribute.
233 func (e ExportOp) End(success int64, err error) {
234 addOpt := get[metric.AddOption](addOptPool)
235 defer put(addOptPool, addOpt)
236 *addOpt = append(*addOpt, e.inst.setOpt)
237
238 if e.inst.inflightMetric.Enabled(e.ctx) {
239 e.inst.inflightMetric.Add(e.ctx, -e.nMetrics, *addOpt...)
240 }
241 if e.inst.exportedMetric.Enabled(e.ctx) {
242 e.inst.exportedMetric.Add(e.ctx, success, *addOpt...)
243 }
244
245 if err != nil && e.inst.exportedMetric.Enabled(e.ctx) {
246 attrs := get[attribute.KeyValue](measureAttrsPool)
247 defer put(measureAttrsPool, attrs)
248 *attrs = append(*attrs, e.inst.attrs...)
249 *attrs = append(*attrs, semconv.ErrorType(err))
250
251 set := attribute.NewSet(*attrs...)
252
253 *addOpt = append((*addOpt)[:0], metric.WithAttributeSet(set))
254 e.inst.exportedMetric.Add(e.ctx, e.nMetrics-success, *addOpt...)
255 }
256 }