-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
collector.go
388 lines (325 loc) · 10.9 KB
/
collector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"
import (
"encoding/hex"
"fmt"
"sort"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
conventions "go.opentelemetry.io/collector/semconv/v1.6.1"
"go.uber.org/zap"
prometheustranslator "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/prometheus"
)
const (
targetMetricName = "target_info"
)
var (
separatorString = string([]byte{model.SeparatorByte})
)
type collector struct {
accumulator accumulator
logger *zap.Logger
sendTimestamps bool
addMetricSuffixes bool
namespace string
constLabels prometheus.Labels
}
func newCollector(config *Config, logger *zap.Logger) *collector {
return &collector{
accumulator: newAccumulator(logger, config.MetricExpiration),
logger: logger,
namespace: prometheustranslator.CleanUpString(config.Namespace),
sendTimestamps: config.SendTimestamps,
constLabels: config.ConstLabels,
addMetricSuffixes: config.AddMetricSuffixes,
}
}
func convertExemplars(exemplars pmetric.ExemplarSlice) []prometheus.Exemplar {
length := exemplars.Len()
result := make([]prometheus.Exemplar, length)
for i := 0; i < length; i++ {
e := exemplars.At(i)
exemplarLabels := make(prometheus.Labels, 0)
if traceID := e.TraceID(); !traceID.IsEmpty() {
exemplarLabels["trace_id"] = hex.EncodeToString(traceID[:])
}
if spanID := e.SpanID(); !spanID.IsEmpty() {
exemplarLabels["span_id"] = hex.EncodeToString(spanID[:])
}
var value float64
switch e.ValueType() {
case pmetric.ExemplarValueTypeDouble:
value = e.DoubleValue()
case pmetric.ExemplarValueTypeInt:
value = float64(e.IntValue())
}
result[i] = prometheus.Exemplar{
Value: value,
Labels: exemplarLabels,
Timestamp: e.Timestamp().AsTime(),
}
}
return result
}
// Describe is a no-op, because the collector dynamically allocates metrics.
// https://github.com/prometheus/client_golang/blob/v1.9.0/prometheus/collector.go#L28-L40
func (c *collector) Describe(_ chan<- *prometheus.Desc) {}
/*
Processing
*/
func (c *collector) processMetrics(rm pmetric.ResourceMetrics) (n int) {
return c.accumulator.Accumulate(rm)
}
var errUnknownMetricType = fmt.Errorf("unknown metric type")
func (c *collector) convertMetric(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
switch metric.Type() {
case pmetric.MetricTypeGauge:
return c.convertGauge(metric, resourceAttrs)
case pmetric.MetricTypeSum:
return c.convertSum(metric, resourceAttrs)
case pmetric.MetricTypeHistogram:
return c.convertDoubleHistogram(metric, resourceAttrs)
case pmetric.MetricTypeSummary:
return c.convertSummary(metric, resourceAttrs)
}
return nil, errUnknownMetricType
}
func (c *collector) getMetricMetadata(metric pmetric.Metric, attributes pcommon.Map, resourceAttrs pcommon.Map) (*prometheus.Desc, []string) {
keys := make([]string, 0, attributes.Len()+2) // +2 for job and instance labels.
values := make([]string, 0, attributes.Len()+2)
attributes.Range(func(k string, v pcommon.Value) bool {
keys = append(keys, prometheustranslator.NormalizeLabel(k))
values = append(values, v.AsString())
return true
})
if job, ok := extractJob(resourceAttrs); ok {
keys = append(keys, model.JobLabel)
values = append(values, job)
}
if instance, ok := extractInstance(resourceAttrs); ok {
keys = append(keys, model.InstanceLabel)
values = append(values, instance)
}
return prometheus.NewDesc(
prometheustranslator.BuildCompliantName(metric, c.namespace, c.addMetricSuffixes),
metric.Description(),
keys,
c.constLabels,
), values
}
func (c *collector) convertGauge(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Gauge().DataPoints().At(0)
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
var value float64
switch ip.ValueType() {
case pmetric.NumberDataPointValueTypeInt:
value = float64(ip.IntValue())
case pmetric.NumberDataPointValueTypeDouble:
value = ip.DoubleValue()
}
m, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, value, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertSum(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Sum().DataPoints().At(0)
metricType := prometheus.GaugeValue
if metric.Sum().IsMonotonic() {
metricType = prometheus.CounterValue
}
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
var value float64
switch ip.ValueType() {
case pmetric.NumberDataPointValueTypeInt:
value = float64(ip.IntValue())
case pmetric.NumberDataPointValueTypeDouble:
value = ip.DoubleValue()
}
var exemplars []prometheus.Exemplar
// Prometheus currently only supports exporting counters
if metricType == prometheus.CounterValue {
exemplars = convertExemplars(ip.Exemplars())
}
m, err := prometheus.NewConstMetric(desc, metricType, value, attributes...)
if err != nil {
return nil, err
}
if len(exemplars) > 0 {
m, err = prometheus.NewMetricWithExemplars(m, exemplars...)
if err != nil {
return nil, err
}
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertSummary(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
// TODO: In the off chance that we have multiple points
// within the same metric, how should we handle them?
point := metric.Summary().DataPoints().At(0)
quantiles := make(map[float64]float64)
qv := point.QuantileValues()
for j := 0; j < qv.Len(); j++ {
qvj := qv.At(j)
// There should be EXACTLY one quantile value lest it is an invalid exposition.
quantiles[qvj.Quantile()] = qvj.Value()
}
desc, attributes := c.getMetricMetadata(metric, point.Attributes(), resourceAttrs)
m, err := prometheus.NewConstSummary(desc, point.Count(), point.Sum(), quantiles, attributes...)
if err != nil {
return nil, err
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(point.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) convertDoubleHistogram(metric pmetric.Metric, resourceAttrs pcommon.Map) (prometheus.Metric, error) {
ip := metric.Histogram().DataPoints().At(0)
desc, attributes := c.getMetricMetadata(metric, ip.Attributes(), resourceAttrs)
indicesMap := make(map[float64]int)
buckets := make([]float64, 0, ip.BucketCounts().Len())
for index := 0; index < ip.ExplicitBounds().Len(); index++ {
bucket := ip.ExplicitBounds().At(index)
if _, added := indicesMap[bucket]; !added {
indicesMap[bucket] = index
buckets = append(buckets, bucket)
}
}
sort.Float64s(buckets)
cumCount := uint64(0)
points := make(map[float64]uint64)
for _, bucket := range buckets {
index := indicesMap[bucket]
var countPerBucket uint64
if ip.ExplicitBounds().Len() > 0 && index < ip.ExplicitBounds().Len() {
countPerBucket = ip.BucketCounts().At(index)
}
cumCount += countPerBucket
points[bucket] = cumCount
}
exemplars := convertExemplars(ip.Exemplars())
m, err := prometheus.NewConstHistogram(desc, ip.Count(), ip.Sum(), points, attributes...)
if err != nil {
return nil, err
}
if len(exemplars) > 0 {
m, err = prometheus.NewMetricWithExemplars(m, exemplars...)
if err != nil {
return nil, err
}
}
if c.sendTimestamps {
return prometheus.NewMetricWithTimestamp(ip.Timestamp().AsTime(), m), nil
}
return m, nil
}
func (c *collector) createTargetInfoMetrics(resourceAttrs []pcommon.Map) ([]prometheus.Metric, error) {
var lastErr error
// deduplicate resourceAttrs by job and instance
deduplicatedResourceAttrs := make([]pcommon.Map, 0, len(resourceAttrs))
seenResource := map[string]struct{}{}
for _, attrs := range resourceAttrs {
sig := resourceSignature(attrs)
if sig == "" {
continue
}
if _, ok := seenResource[sig]; !ok {
seenResource[sig] = struct{}{}
deduplicatedResourceAttrs = append(deduplicatedResourceAttrs, attrs)
}
}
metrics := make([]prometheus.Metric, 0, len(deduplicatedResourceAttrs))
for _, rAttributes := range deduplicatedResourceAttrs {
// map ensures no duplicate label name
labels := make(map[string]string, rAttributes.Len()+2) // +2 for job and instance labels.
// Use resource attributes (other than those used for job+instance) as the
// metric labels for the target info metric
attributes := pcommon.NewMap()
rAttributes.CopyTo(attributes)
attributes.RemoveIf(func(k string, _ pcommon.Value) bool {
switch k {
case conventions.AttributeServiceName, conventions.AttributeServiceNamespace, conventions.AttributeServiceInstanceID:
// Remove resource attributes used for job + instance
return true
default:
return false
}
})
attributes.Range(func(k string, v pcommon.Value) bool {
finalKey := prometheustranslator.NormalizeLabel(k)
if existingVal, ok := labels[finalKey]; ok {
labels[finalKey] = existingVal + ";" + v.AsString()
} else {
labels[finalKey] = v.AsString()
}
return true
})
// Map service.name + service.namespace to job
if job, ok := extractJob(rAttributes); ok {
labels[model.JobLabel] = job
}
// Map service.instance.id to instance
if instance, ok := extractInstance(rAttributes); ok {
labels[model.InstanceLabel] = instance
}
name := targetMetricName
if len(c.namespace) > 0 {
name = c.namespace + "_" + name
}
keys := make([]string, 0, len(labels))
values := make([]string, 0, len(labels))
for key, value := range labels {
keys = append(keys, key)
values = append(values, value)
}
metric, err := prometheus.NewConstMetric(
prometheus.NewDesc(name, "Target metadata", keys, nil),
prometheus.GaugeValue,
1,
values...,
)
if err != nil {
lastErr = err
continue
}
metrics = append(metrics, metric)
}
return metrics, lastErr
}
/*
Reporting
*/
func (c *collector) Collect(ch chan<- prometheus.Metric) {
c.logger.Debug("collect called")
inMetrics, resourceAttrs := c.accumulator.Collect()
targetMetrics, err := c.createTargetInfoMetrics(resourceAttrs)
if err != nil {
c.logger.Error(fmt.Sprintf("failed to convert metric %s: %s", targetMetricName, err.Error()))
}
for _, m := range targetMetrics {
ch <- m
c.logger.Debug(fmt.Sprintf("metric served: %s", m.Desc().String()))
}
for i := range inMetrics {
pMetric := inMetrics[i]
rAttr := resourceAttrs[i]
m, err := c.convertMetric(pMetric, rAttr)
if err != nil {
c.logger.Error(fmt.Sprintf("failed to convert metric %s: %s", pMetric.Name(), err.Error()))
continue
}
ch <- m
c.logger.Debug(fmt.Sprintf("metric served: %s", m.Desc().String()))
}
}