Debian Codegraph @

bridges/prometheus/producer.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package prometheus // import "go.opentelemetry.io/contrib/bridges/prometheus"
5
6 import (
7 "context"
8 "errors"
9 "fmt"
10 "math"
11 "strings"
12 "time"
13
14 "github.com/prometheus/client_golang/prometheus"
15 dto "github.com/prometheus/client_model/go"
16 "go.opentelemetry.io/otel"
17 "go.opentelemetry.io/otel/attribute"
18 "go.opentelemetry.io/otel/sdk/instrumentation"
19 "go.opentelemetry.io/otel/sdk/metric"
20 "go.opentelemetry.io/otel/sdk/metric/metricdata"
21 )
22
23 const (
24 scopeName = "go.opentelemetry.io/contrib/bridges/prometheus"
25 traceIDLabel = "trace_id"
26 spanIDLabel = "span_id"
27 )
28
29 var (
30 errUnsupportedType = errors.New("unsupported metric type")
31 processStartTime = time.Now()
32 )
33
34 type producer struct {
35 gatherers prometheus.Gatherers
36 }
37
38 // NewMetricProducer returns a metric.Producer that fetches metrics from
39 // Prometheus. This can be used to allow Prometheus instrumentation to be
40 // added to an OpenTelemetry export pipeline.
41 func NewMetricProducer(opts ...Option) metric.Producer {
42 cfg := newConfig(opts...)
43 return &producer{
44 gatherers: cfg.gatherers,
45 }
46 }
47
48 func (p *producer) Produce(context.Context) ([]metricdata.ScopeMetrics, error) {
49 now := time.Now()
50 var errs multierr
51 otelMetrics := make([]metricdata.Metrics, 0)
52 for _, gatherer := range p.gatherers {
53 promMetrics, err := gatherer.Gather()
54 if err != nil {
55 errs = append(errs, err)
56 continue
57 }
58 m, err := convertPrometheusMetricsInto(promMetrics, now)
59 otelMetrics = append(otelMetrics, m...)
60 if err != nil {
61 errs = append(errs, err)
62 }
63 }
64 if errs.errOrNil() != nil {
65 otel.Handle(errs.errOrNil())
66 }
67 if len(otelMetrics) == 0 {
68 return nil, nil
69 }
70 return []metricdata.ScopeMetrics{{
71 Scope: instrumentation.Scope{
72 Name: scopeName,
73 },
74 Metrics: otelMetrics,
75 }}, nil
76 }
77
78 func convertPrometheusMetricsInto(promMetrics []*dto.MetricFamily, now time.Time) ([]metricdata.Metrics, error) {
79 var errs multierr
80 otelMetrics := make([]metricdata.Metrics, 0)
81 for _, pm := range promMetrics {
82 if len(pm.GetMetric()) == 0 {
83 // This shouldn't ever happen
84 continue
85 }
86 newMetric := metricdata.Metrics{
87 Name: pm.GetName(),
88 Description: pm.GetHelp(),
89 }
90 switch pm.GetType() {
91 case dto.MetricType_GAUGE:
92 newMetric.Data = convertGauge(pm.GetMetric(), now)
93 case dto.MetricType_COUNTER:
94 newMetric.Data = convertCounter(pm.GetMetric(), now)
95 case dto.MetricType_SUMMARY:
96 newMetric.Data = convertSummary(pm.GetMetric(), now)
97 case dto.MetricType_HISTOGRAM:
98 if isExponentialHistogram(pm.GetMetric()[0].GetHistogram()) {
99 newMetric.Data = convertExponentialHistogram(pm.GetMetric(), now)
100 } else {
101 newMetric.Data = convertHistogram(pm.GetMetric(), now)
102 }
103 default:
104 // MetricType_GAUGE_HISTOGRAM, MetricType_UNTYPED
105 errs = append(errs, fmt.Errorf("%w: %v for metric %v", errUnsupportedType, pm.GetType(), pm.GetName()))
106 continue
107 }
108 otelMetrics = append(otelMetrics, newMetric)
109 }
110 return otelMetrics, errs.errOrNil()
111 }
112
113 func isExponentialHistogram(hist *dto.Histogram) bool {
114 // The prometheus go client ensures at least one of these is non-zero
115 // so it can be distinguished from a fixed-bucket histogram.
116 // https://github.com/prometheus/client_golang/blob/7ac90362b02729a65109b33d172bafb65d7dab50/prometheus/histogram.go#L818
117 return hist.GetZeroThreshold() > 0 ||
118 hist.GetZeroCount() > 0 ||
119 len(hist.GetPositiveSpan()) > 0 ||
120 len(hist.GetNegativeSpan()) > 0
121 }
122
123 func convertGauge(metrics []*dto.Metric, now time.Time) metricdata.Gauge[float64] {
124 otelGauge := metricdata.Gauge[float64]{
125 DataPoints: make([]metricdata.DataPoint[float64], len(metrics)),
126 }
127 for i, m := range metrics {
128 dp := metricdata.DataPoint[float64]{
129 Attributes: convertLabels(m.GetLabel()),
130 Time: now,
131 Value: m.GetGauge().GetValue(),
132 }
133 if m.GetTimestampMs() != 0 {
134 dp.Time = time.UnixMilli(m.GetTimestampMs())
135 }
136 otelGauge.DataPoints[i] = dp
137 }
138 return otelGauge
139 }
140
141 func convertCounter(metrics []*dto.Metric, now time.Time) metricdata.Sum[float64] {
142 otelCounter := metricdata.Sum[float64]{
143 DataPoints: make([]metricdata.DataPoint[float64], len(metrics)),
144 Temporality: metricdata.CumulativeTemporality,
145 IsMonotonic: true,
146 }
147 for i, m := range metrics {
148 dp := metricdata.DataPoint[float64]{
149 Attributes: convertLabels(m.GetLabel()),
150 StartTime: processStartTime,
151 Time: now,
152 Value: m.GetCounter().GetValue(),
153 }
154 if ex := m.GetCounter().GetExemplar(); ex != nil {
155 dp.Exemplars = []metricdata.Exemplar[float64]{convertExemplar(ex)}
156 }
157 createdTs := m.GetCounter().GetCreatedTimestamp()
158 if createdTs.IsValid() {
159 dp.StartTime = createdTs.AsTime()
160 }
161 if m.GetTimestampMs() != 0 {
162 dp.Time = time.UnixMilli(m.GetTimestampMs())
163 }
164 otelCounter.DataPoints[i] = dp
165 }
166 return otelCounter
167 }
168
169 func convertExponentialHistogram(metrics []*dto.Metric, now time.Time) metricdata.ExponentialHistogram[float64] {
170 otelExpHistogram := metricdata.ExponentialHistogram[float64]{
171 DataPoints: make([]metricdata.ExponentialHistogramDataPoint[float64], len(metrics)),
172 Temporality: metricdata.CumulativeTemporality,
173 }
174 for i, m := range metrics {
175 dp := metricdata.ExponentialHistogramDataPoint[float64]{
176 Attributes: convertLabels(m.GetLabel()),
177 StartTime: processStartTime,
178 Time: now,
179 Count: m.GetHistogram().GetSampleCount(),
180 Sum: m.GetHistogram().GetSampleSum(),
181 Scale: m.GetHistogram().GetSchema(),
182 ZeroCount: m.GetHistogram().GetZeroCount(),
183 ZeroThreshold: m.GetHistogram().GetZeroThreshold(),
184 PositiveBucket: convertExponentialBuckets(
185 m.GetHistogram().GetPositiveSpan(),
186 m.GetHistogram().GetPositiveDelta(),
187 ),
188 NegativeBucket: convertExponentialBuckets(
189 m.GetHistogram().GetNegativeSpan(),
190 m.GetHistogram().GetNegativeDelta(),
191 ),
192 // TODO: Support exemplars
193 }
194 createdTs := m.GetHistogram().GetCreatedTimestamp()
195 if createdTs.IsValid() {
196 dp.StartTime = createdTs.AsTime()
197 }
198 if t := m.GetTimestampMs(); t != 0 {
199 dp.Time = time.UnixMilli(t)
200 }
201 otelExpHistogram.DataPoints[i] = dp
202 }
203 return otelExpHistogram
204 }
205
206 func convertExponentialBuckets(bucketSpans []*dto.BucketSpan, deltas []int64) metricdata.ExponentialBucket {
207 if len(bucketSpans) == 0 {
208 return metricdata.ExponentialBucket{}
209 }
210 // Prometheus Native Histograms buckets are indexed by upper boundary
211 // while Exponential Histograms are indexed by lower boundary, the result
212 // being that the Offset fields are different-by-one.
213 initialOffset := bucketSpans[0].GetOffset() - 1
214 // We will have one bucket count for each delta, and zeros for the offsets
215 // after the initial offset.
216 lenCounts := len(deltas)
217 for i, bs := range bucketSpans {
218 if i != 0 {
219 lenCounts += int(bs.GetOffset())
220 }
221 }
222 counts := make([]uint64, lenCounts)
223 deltaIndex := 0
224 countIndex := int32(0)
225 count := int64(0)
226 for i, bs := range bucketSpans {
227 // Do not insert zeroes if this is the first bucketSpan, since those
228 // zeroes are accounted for in the Offset field.
229 if i != 0 {
230 // Increase the count index by the Offset to insert Offset zeroes
231 countIndex += bs.GetOffset()
232 }
233 for range bs.GetLength() {
234 // Convert deltas to the cumulative number of observations
235 count += deltas[deltaIndex]
236 deltaIndex++
237 // count should always be positive after accounting for deltas
238 if count > 0 {
239 counts[countIndex] = uint64(count)
240 }
241 countIndex++
242 }
243 }
244 return metricdata.ExponentialBucket{
245 Offset: initialOffset,
246 Counts: counts,
247 }
248 }
249
250 func convertHistogram(metrics []*dto.Metric, now time.Time) metricdata.Histogram[float64] {
251 otelHistogram := metricdata.Histogram[float64]{
252 DataPoints: make([]metricdata.HistogramDataPoint[float64], len(metrics)),
253 Temporality: metricdata.CumulativeTemporality,
254 }
255 for i, m := range metrics {
256 bounds, bucketCounts, exemplars := convertBuckets(m.GetHistogram().GetBucket(), m.GetHistogram().GetSampleCount())
257 dp := metricdata.HistogramDataPoint[float64]{
258 Attributes: convertLabels(m.GetLabel()),
259 StartTime: processStartTime,
260 Time: now,
261 Count: m.GetHistogram().GetSampleCount(),
262 Sum: m.GetHistogram().GetSampleSum(),
263 Bounds: bounds,
264 BucketCounts: bucketCounts,
265 Exemplars: exemplars,
266 }
267 createdTs := m.GetHistogram().GetCreatedTimestamp()
268 if createdTs.IsValid() {
269 dp.StartTime = createdTs.AsTime()
270 }
271 if m.GetTimestampMs() != 0 {
272 dp.Time = time.UnixMilli(m.GetTimestampMs())
273 }
274 otelHistogram.DataPoints[i] = dp
275 }
276 return otelHistogram
277 }
278
279 func convertBuckets(buckets []*dto.Bucket, sampleCount uint64) ([]float64, []uint64, []metricdata.Exemplar[float64]) {
280 if len(buckets) == 0 {
281 // This should never happen
282 return nil, nil, nil
283 }
284 // buckets will only include the +Inf bucket if there is an exemplar for it
285 // https://github.com/prometheus/client_golang/blob/d038ab96c0c7b9cd217a39072febd610bcdf1fd8/prometheus/metric.go#L189
286 // we need to handle the case where it is present, or where it is missing.
287 hasInf := math.IsInf(buckets[len(buckets)-1].GetUpperBound(), +1)
288 var bounds []float64
289 var bucketCounts []uint64
290 if hasInf {
291 bounds = make([]float64, len(buckets)-1)
292 bucketCounts = make([]uint64, len(buckets))
293 } else {
294 bounds = make([]float64, len(buckets))
295 bucketCounts = make([]uint64, len(buckets)+1)
296 }
297 exemplars := make([]metricdata.Exemplar[float64], 0)
298 var previousCount uint64
299 for i, bucket := range buckets {
300 // The last bound may be the +Inf bucket, which is implied in OTel, but
301 // is explicit in Prometheus. Skip the last boundary if it is the +Inf
302 // bound.
303 if bound := bucket.GetUpperBound(); !math.IsInf(bound, +1) {
304 bounds[i] = bound
305 }
306 previousCount, bucketCounts[i] = bucket.GetCumulativeCount(), bucket.GetCumulativeCount()-previousCount
307 if ex := bucket.GetExemplar(); ex != nil {
308 exemplars = append(exemplars, convertExemplar(ex))
309 }
310 }
311 if !hasInf {
312 // The Inf bucket was missing, so set the last bucket counts to the
313 // overall count
314 bucketCounts[len(bucketCounts)-1] = sampleCount - previousCount
315 }
316 return bounds, bucketCounts, exemplars
317 }
318
319 func convertSummary(metrics []*dto.Metric, now time.Time) metricdata.Summary {
320 otelSummary := metricdata.Summary{
321 DataPoints: make([]metricdata.SummaryDataPoint, len(metrics)),
322 }
323 for i, m := range metrics {
324 dp := metricdata.SummaryDataPoint{
325 Attributes: convertLabels(m.GetLabel()),
326 StartTime: processStartTime,
327 Time: now,
328 Count: m.GetSummary().GetSampleCount(),
329 Sum: m.GetSummary().GetSampleSum(),
330 QuantileValues: convertQuantiles(m.GetSummary().GetQuantile()),
331 }
332 createdTs := m.GetSummary().GetCreatedTimestamp()
333 if createdTs.IsValid() {
334 dp.StartTime = createdTs.AsTime()
335 }
336 if t := m.GetTimestampMs(); t != 0 {
337 dp.Time = time.UnixMilli(t)
338 }
339 otelSummary.DataPoints[i] = dp
340 }
341 return otelSummary
342 }
343
344 func convertQuantiles(quantiles []*dto.Quantile) []metricdata.QuantileValue {
345 otelQuantiles := make([]metricdata.QuantileValue, len(quantiles))
346 for i, quantile := range quantiles {
347 dp := metricdata.QuantileValue{
348 Quantile: quantile.GetQuantile(),
349 Value: quantile.GetValue(),
350 }
351 otelQuantiles[i] = dp
352 }
353 return otelQuantiles
354 }
355
356 func convertLabels(labels []*dto.LabelPair) attribute.Set {
357 kvs := make([]attribute.KeyValue, len(labels))
358 for i, l := range labels {
359 kvs[i] = attribute.String(l.GetName(), l.GetValue())
360 }
361 return attribute.NewSet(kvs...)
362 }
363
364 func convertExemplar(exemplar *dto.Exemplar) metricdata.Exemplar[float64] {
365 attrs := make([]attribute.KeyValue, 0)
366 var traceID, spanID []byte
367 // find the trace ID and span ID in attributes, if it exists
368 for _, label := range exemplar.GetLabel() {
369 switch label.GetName() {
370 case traceIDLabel:
371 traceID = []byte(label.GetValue())
372 case spanIDLabel:
373 spanID = []byte(label.GetValue())
374 default:
375 attrs = append(attrs, attribute.String(label.GetName(), label.GetValue()))
376 }
377 }
378 return metricdata.Exemplar[float64]{
379 Value: exemplar.GetValue(),
380 Time: exemplar.GetTimestamp().AsTime(),
381 TraceID: traceID,
382 SpanID: spanID,
383 FilteredAttributes: attrs,
384 }
385 }
386
387 type multierr []error
388
389 func (e multierr) errOrNil() error {
390 if len(e) == 0 {
391 return nil
392 } else if len(e) == 1 {
393 return e[0]
394 }
395 return e
396 }
397
398 func (e multierr) Error() string {
399 es := make([]string, len(e))
400 for i, err := range e {
401 es[i] = fmt.Sprintf("* %s", err)
402 }
403 return strings.Join(es, "\n\t")
404 }