Debian Codegraph @

exporters/prometheus/internal/observ/instrumentation_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package observ_test
5
6 import (
7 "errors"
8 "testing"
9
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12
13 "go.opentelemetry.io/otel"
14 "go.opentelemetry.io/otel/attribute"
15 "go.opentelemetry.io/otel/exporters/prometheus/internal/observ"
16 mapi "go.opentelemetry.io/otel/metric"
17 "go.opentelemetry.io/otel/sdk/instrumentation"
18 "go.opentelemetry.io/otel/sdk/metric"
19 "go.opentelemetry.io/otel/sdk/metric/metricdata"
20 "go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"
21 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
22 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
23 )
24
25 const ID = 0
26
27 var Scope = instrumentation.Scope{
28 Name: observ.ScopeName,
29 Version: observ.Version,
30 SchemaURL: observ.SchemaURL,
31 }
32
33 type errMeterProvider struct {
34 mapi.MeterProvider
35 err error
36 }
37
38 func (m *errMeterProvider) Meter(string, ...mapi.MeterOption) mapi.Meter {
39 return &errMeter{err: m.err}
40 }
41
42 type errMeter struct {
43 mapi.Meter
44 err error
45 }
46
47 func (m *errMeter) Int64UpDownCounter(string, ...mapi.Int64UpDownCounterOption) (mapi.Int64UpDownCounter, error) {
48 return nil, m.err
49 }
50
51 func (m *errMeter) Int64Counter(string, ...mapi.Int64CounterOption) (mapi.Int64Counter, error) {
52 return nil, m.err
53 }
54
55 func (m *errMeter) Float64Histogram(string, ...mapi.Float64HistogramOption) (mapi.Float64Histogram, error) {
56 return nil, m.err
57 }
58
59 func TestNewInstrumentationObservabilityErrors(t *testing.T) {
60 orig := otel.GetMeterProvider()
61 t.Cleanup(func() { otel.SetMeterProvider(orig) })
62 mp := &errMeterProvider{err: assert.AnError}
63 otel.SetMeterProvider(mp)
64
65 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
66
67 _, err := observ.NewInstrumentation(ID)
68 require.ErrorIs(t, err, assert.AnError, "new instrument errors should be joined")
69
70 assert.ErrorContains(t, err, "inflight metric")
71 assert.ErrorContains(t, err, "exported metric")
72 assert.ErrorContains(t, err, "operation duration metric")
73 assert.ErrorContains(t, err, "collection duration metric")
74 }
75
76 func TestNewInstrumentationObservabilityDisabled(t *testing.T) {
77 // Do not set OTEL_GO_X_OBSERVABILITY.
78 got, err := observ.NewInstrumentation(ID)
79 assert.NoError(t, err)
80 assert.Nil(t, got)
81 }
82
83 // setup installs a ManualReader MeterProvider and returns an instantiated
84 // Instrumentation plus a collector that returns the single ScopeMetrics group.
85 func setup(t *testing.T) (*observ.Instrumentation, func() metricdata.ScopeMetrics) {
86 t.Helper()
87
88 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
89
90 original := otel.GetMeterProvider()
91 t.Cleanup(func() { otel.SetMeterProvider(original) })
92
93 r := metric.NewManualReader()
94 mp := metric.NewMeterProvider(metric.WithReader(r))
95 otel.SetMeterProvider(mp)
96
97 inst, err := observ.NewInstrumentation(ID)
98 require.NoError(t, err)
99 require.NotNil(t, inst)
100
101 return inst, func() metricdata.ScopeMetrics {
102 var rm metricdata.ResourceMetrics
103 require.NoError(t, r.Collect(t.Context(), &rm))
104 require.Len(t, rm.ScopeMetrics, 1)
105 return rm.ScopeMetrics[0]
106 }
107 }
108
109 func set(err error) attribute.Set {
110 attrs := []attribute.KeyValue{
111 semconv.OTelComponentName(observ.ComponentName(ID)),
112 semconv.OTelComponentTypeKey.String(observ.ComponentType),
113 }
114 if err != nil {
115 attrs = append(attrs, semconv.ErrorType(err))
116 }
117 return attribute.NewSet(attrs...)
118 }
119
120 func scrapeInflight() metricdata.Metrics {
121 return metricdata.Metrics{
122 Name: otelconv.SDKExporterMetricDataPointInflight{}.Name(),
123 Description: otelconv.SDKExporterMetricDataPointInflight{}.Description(),
124 Unit: otelconv.SDKExporterMetricDataPointInflight{}.Unit(),
125 Data: metricdata.Sum[int64]{
126 Temporality: metricdata.CumulativeTemporality,
127 DataPoints: []metricdata.DataPoint[int64]{
128 {Attributes: set(nil), Value: 0},
129 },
130 },
131 }
132 }
133
134 func scrapeExported(success, total int64, err error) metricdata.Metrics {
135 dps := []metricdata.DataPoint[int64]{
136 {Attributes: set(nil), Value: success},
137 }
138 if err != nil {
139 dps = append(dps, metricdata.DataPoint[int64]{
140 Attributes: set(err),
141 Value: total - success,
142 })
143 }
144 return metricdata.Metrics{
145 Name: otelconv.SDKExporterMetricDataPointExported{}.Name(),
146 Description: otelconv.SDKExporterMetricDataPointExported{}.Description(),
147 Unit: otelconv.SDKExporterMetricDataPointExported{}.Unit(),
148 Data: metricdata.Sum[int64]{
149 Temporality: metricdata.CumulativeTemporality,
150 IsMonotonic: true,
151 DataPoints: dps,
152 },
153 }
154 }
155
156 func operationDuration(err error) metricdata.Metrics {
157 return metricdata.Metrics{
158 Name: otelconv.SDKExporterOperationDuration{}.Name(),
159 Description: otelconv.SDKExporterOperationDuration{}.Description(),
160 Unit: otelconv.SDKExporterOperationDuration{}.Unit(),
161 Data: metricdata.Histogram[float64]{
162 Temporality: metricdata.CumulativeTemporality,
163 DataPoints: []metricdata.HistogramDataPoint[float64]{
164 {Attributes: set(err)},
165 },
166 },
167 }
168 }
169
170 func collectionDuration(err error) metricdata.Metrics {
171 return metricdata.Metrics{
172 Name: otelconv.SDKMetricReaderCollectionDuration{}.Name(),
173 Description: otelconv.SDKMetricReaderCollectionDuration{}.Description(),
174 Unit: otelconv.SDKMetricReaderCollectionDuration{}.Unit(),
175 Data: metricdata.Histogram[float64]{
176 Temporality: metricdata.CumulativeTemporality,
177 DataPoints: []metricdata.HistogramDataPoint[float64]{
178 {Attributes: set(err)},
179 },
180 },
181 }
182 }
183
184 func assertExportMetricsMetrics(t *testing.T, got metricdata.ScopeMetrics, total, success int64, err error) {
185 t.Helper()
186
187 assert.Equal(t, Scope, got.Scope, "unexpected scope")
188
189 m := got.Metrics
190 require.Len(t, m, 3, "expected 3 metrics (inflight, exported, operationDuration)")
191
192 o := metricdatatest.IgnoreTimestamp()
193
194 want := scrapeInflight()
195 metricdatatest.AssertEqual(t, want, m[0], o)
196
197 want = scrapeExported(success, total, err)
198 metricdatatest.AssertEqual(t, want, m[1], o)
199
200 want = operationDuration(err)
201 metricdatatest.AssertEqual(t, want, m[2], o, metricdatatest.IgnoreValue())
202 }
203
204 func assertCollectionOnly(t *testing.T, got metricdata.ScopeMetrics, err error) {
205 t.Helper()
206
207 assert.Equal(t, Scope, got.Scope, "unexpected scope")
208
209 m := got.Metrics
210 require.Len(t, m, 1, "expected only collectionDuration metric")
211
212 o := metricdatatest.IgnoreTimestamp()
213 want := collectionDuration(err)
214 metricdatatest.AssertEqual(t, want, m[0], o, metricdatatest.IgnoreValue())
215 }
216
217 func TestInstrumentationExportMetricsSuccess(t *testing.T) {
218 inst, collect := setup(t)
219
220 const n = 10
221 timer := inst.RecordOperationDuration(t.Context())
222 inst.ExportMetrics(t.Context(), n).End(n, nil)
223 timer.Stop(nil)
224
225 assertExportMetricsMetrics(t, collect(), n, n, nil)
226 }
227
228 func TestInstrumentationExportMetricsAllErrored(t *testing.T) {
229 inst, collect := setup(t)
230
231 const n = 10
232 err := assert.AnError
233
234 timer := inst.RecordOperationDuration(t.Context())
235 op := inst.ExportMetrics(t.Context(), n)
236
237 const success = 0
238 op.End(success, err)
239 timer.Stop(err)
240
241 assertExportMetricsMetrics(t, collect(), n, success, err)
242 }
243
244 func TestInstrumentationExportMetricsPartialErrored(t *testing.T) {
245 inst, collect := setup(t)
246
247 const n = 10
248 err := assert.AnError
249
250 timer := inst.RecordOperationDuration(t.Context())
251 op := inst.ExportMetrics(t.Context(), n)
252
253 const success = 5
254 op.End(success, err)
255 timer.Stop(err)
256
257 assertExportMetricsMetrics(t, collect(), n, success, err)
258 }
259
260 func TestRecordCollectionDurationSuccess(t *testing.T) {
261 inst, collect := setup(t)
262
263 inst.RecordCollectionDuration(t.Context()).Stop(nil)
264
265 assertCollectionOnly(t, collect(), nil)
266 }
267
268 func TestRecordCollectionDurationError(t *testing.T) {
269 inst, collect := setup(t)
270
271 wantErr := assert.AnError
272 inst.RecordCollectionDuration(t.Context()).Stop(wantErr)
273
274 assertCollectionOnly(t, collect(), wantErr)
275 }
276
277 func setupBench(b *testing.B) *observ.Instrumentation {
278 b.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
279 inst, err := observ.NewInstrumentation(ID)
280 if err != nil {
281 b.Fatalf("failed to create instrumentation: %v", err)
282 }
283 if inst == nil {
284 b.Fatal("expected instrumentation, got nil")
285 }
286 return inst
287 }
288
289 func BenchmarkInstrumentationExportMetrics(b *testing.B) {
290 const nSpans = 10
291 run := func(success int64, err error) func(*testing.B) {
292 inst := setupBench(b)
293 return func(b *testing.B) {
294 ctx := b.Context()
295 b.ReportAllocs()
296 b.ResetTimer()
297 for b.Loop() {
298 inst.ExportMetrics(ctx, nSpans).End(success, err)
299 }
300 }
301 }
302
303 err := errors.New("benchmark error")
304 b.Run("NoError", run(nSpans, nil))
305 b.Run("AllError", run(0, err))
306 b.Run("PartialError", run(4, err))
307 }
308
309 func BenchmarkInstrumentationRecordOperationDuration(b *testing.B) {
310 run := func(err error) func(*testing.B) {
311 inst := setupBench(b)
312 return func(b *testing.B) {
313 ctx := b.Context()
314 b.ReportAllocs()
315 b.ResetTimer()
316 for b.Loop() {
317 inst.RecordOperationDuration(ctx).Stop(err)
318 }
319 }
320 }
321
322 err := errors.New("benchmark error")
323 b.Run("NoError", run(nil))
324 b.Run("Error", run(err))
325 }
326
327 func BenchmarkInstrumentationRecordCollectionDuration(b *testing.B) {
328 run := func(err error) func(*testing.B) {
329 inst := setupBench(b)
330 return func(b *testing.B) {
331 ctx := b.Context()
332 b.ReportAllocs()
333 b.ResetTimer()
334 for b.Loop() {
335 inst.RecordCollectionDuration(ctx).Stop(err)
336 }
337 }
338 }
339
340 err := errors.New("benchmark error")
341 b.Run("NoError", run(nil))
342 b.Run("Error", run(err))
343 }