-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
accumulator.go
318 lines (264 loc) · 10.2 KB
/
accumulator.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package prometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/prometheusexporter"
import (
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/prometheus/common/model"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.uber.org/zap"
)
type accumulatedValue struct {
// value contains a metric with exactly one aggregated datapoint.
value pmetric.Metric
// resourceAttrs contain the resource attributes. They are used to output instance and job labels.
resourceAttrs pcommon.Map
// updated indicates when metric was last changed.
updated time.Time
scope pcommon.InstrumentationScope
}
// accumulator stores aggragated values of incoming metrics
type accumulator interface {
// Accumulate stores aggragated metric values
Accumulate(resourceMetrics pmetric.ResourceMetrics) (processed int)
// Collect returns a slice with relevant aggregated metrics and their resource attributes.
// The number or metrics and attributes returned will be the same.
Collect() (metrics []pmetric.Metric, resourceAttrs []pcommon.Map)
}
// LastValueAccumulator keeps last value for accumulated metrics
type lastValueAccumulator struct {
logger *zap.Logger
registeredMetrics sync.Map
// metricExpiration contains duration for which metric
// should be served after it was updated
metricExpiration time.Duration
}
// NewAccumulator returns LastValueAccumulator
func newAccumulator(logger *zap.Logger, metricExpiration time.Duration) accumulator {
return &lastValueAccumulator{
logger: logger,
metricExpiration: metricExpiration,
}
}
// Accumulate stores one datapoint per metric
func (a *lastValueAccumulator) Accumulate(rm pmetric.ResourceMetrics) (n int) {
now := time.Now()
ilms := rm.ScopeMetrics()
resourceAttrs := rm.Resource().Attributes()
for i := 0; i < ilms.Len(); i++ {
ilm := ilms.At(i)
metrics := ilm.Metrics()
for j := 0; j < metrics.Len(); j++ {
n += a.addMetric(metrics.At(j), ilm.Scope(), resourceAttrs, now)
}
}
return
}
func (a *lastValueAccumulator) addMetric(metric pmetric.Metric, il pcommon.InstrumentationScope, resourceAttrs pcommon.Map, now time.Time) int {
a.logger.Debug(fmt.Sprintf("accumulating metric: %s", metric.Name()))
switch metric.Type() {
case pmetric.MetricTypeGauge:
return a.accumulateGauge(metric, il, resourceAttrs, now)
case pmetric.MetricTypeSum:
return a.accumulateSum(metric, il, resourceAttrs, now)
case pmetric.MetricTypeHistogram:
return a.accumulateDoubleHistogram(metric, il, resourceAttrs, now)
case pmetric.MetricTypeSummary:
return a.accumulateSummary(metric, il, resourceAttrs, now)
default:
a.logger.With(
zap.String("data_type", string(metric.Type())),
zap.String("metric_name", metric.Name()),
).Error("failed to translate metric")
}
return 0
}
func (a *lastValueAccumulator) accumulateSummary(metric pmetric.Metric, il pcommon.InstrumentationScope, resourceAttrs pcommon.Map, now time.Time) (n int) {
dps := metric.Summary().DataPoints()
for i := 0; i < dps.Len(); i++ {
ip := dps.At(i)
signature := timeseriesSignature(il.Name(), metric, ip.Attributes(), resourceAttrs)
if ip.Flags().NoRecordedValue() {
a.registeredMetrics.Delete(signature)
return 0
}
v, ok := a.registeredMetrics.Load(signature)
stalePoint := ok &&
ip.Timestamp().AsTime().Before(v.(*accumulatedValue).value.Summary().DataPoints().At(0).Timestamp().AsTime())
if stalePoint {
// Only keep this datapoint if it has a later timestamp.
continue
}
m := copyMetricMetadata(metric)
ip.CopyTo(m.SetEmptySummary().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
}
return n
}
func (a *lastValueAccumulator) accumulateGauge(metric pmetric.Metric, il pcommon.InstrumentationScope, resourceAttrs pcommon.Map, now time.Time) (n int) {
dps := metric.Gauge().DataPoints()
for i := 0; i < dps.Len(); i++ {
ip := dps.At(i)
signature := timeseriesSignature(il.Name(), metric, ip.Attributes(), resourceAttrs)
if ip.Flags().NoRecordedValue() {
a.registeredMetrics.Delete(signature)
return 0
}
v, ok := a.registeredMetrics.Load(signature)
if !ok {
m := copyMetricMetadata(metric)
ip.CopyTo(m.SetEmptyGauge().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
continue
}
mv := v.(*accumulatedValue)
if ip.Timestamp().AsTime().Before(mv.value.Gauge().DataPoints().At(0).Timestamp().AsTime()) {
// only keep datapoint with latest timestamp
continue
}
m := copyMetricMetadata(metric)
ip.CopyTo(m.SetEmptyGauge().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
}
return
}
func (a *lastValueAccumulator) accumulateSum(metric pmetric.Metric, il pcommon.InstrumentationScope, resourceAttrs pcommon.Map, now time.Time) (n int) {
doubleSum := metric.Sum()
// Drop metrics with unspecified aggregations
if doubleSum.AggregationTemporality() == pmetric.AggregationTemporalityUnspecified {
return
}
// Drop non-monotonic and non-cumulative metrics
if doubleSum.AggregationTemporality() == pmetric.AggregationTemporalityDelta && !doubleSum.IsMonotonic() {
return
}
dps := doubleSum.DataPoints()
for i := 0; i < dps.Len(); i++ {
ip := dps.At(i)
signature := timeseriesSignature(il.Name(), metric, ip.Attributes(), resourceAttrs)
if ip.Flags().NoRecordedValue() {
a.registeredMetrics.Delete(signature)
return 0
}
v, ok := a.registeredMetrics.Load(signature)
if !ok {
m := copyMetricMetadata(metric)
m.SetEmptySum().SetIsMonotonic(metric.Sum().IsMonotonic())
m.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
ip.CopyTo(m.Sum().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
continue
}
mv := v.(*accumulatedValue)
if ip.Timestamp().AsTime().Before(mv.value.Sum().DataPoints().At(0).Timestamp().AsTime()) {
// only keep datapoint with latest timestamp
continue
}
// Delta-to-Cumulative
if doubleSum.AggregationTemporality() == pmetric.AggregationTemporalityDelta && ip.StartTimestamp() == mv.value.Sum().DataPoints().At(0).Timestamp() {
ip.SetStartTimestamp(mv.value.Sum().DataPoints().At(0).StartTimestamp())
switch ip.ValueType() {
case pmetric.NumberDataPointValueTypeInt:
ip.SetIntValue(ip.IntValue() + mv.value.Sum().DataPoints().At(0).IntValue())
case pmetric.NumberDataPointValueTypeDouble:
ip.SetDoubleValue(ip.DoubleValue() + mv.value.Sum().DataPoints().At(0).DoubleValue())
}
}
m := copyMetricMetadata(metric)
m.SetEmptySum().SetIsMonotonic(metric.Sum().IsMonotonic())
m.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
ip.CopyTo(m.Sum().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
}
return
}
func (a *lastValueAccumulator) accumulateDoubleHistogram(metric pmetric.Metric, il pcommon.InstrumentationScope, resourceAttrs pcommon.Map, now time.Time) (n int) {
doubleHistogram := metric.Histogram()
// Drop metrics with non-cumulative aggregations
if doubleHistogram.AggregationTemporality() != pmetric.AggregationTemporalityCumulative {
return
}
dps := doubleHistogram.DataPoints()
for i := 0; i < dps.Len(); i++ {
ip := dps.At(i)
signature := timeseriesSignature(il.Name(), metric, ip.Attributes(), resourceAttrs)
if ip.Flags().NoRecordedValue() {
a.registeredMetrics.Delete(signature)
return 0
}
v, ok := a.registeredMetrics.Load(signature)
if !ok {
m := copyMetricMetadata(metric)
ip.CopyTo(m.SetEmptyHistogram().DataPoints().AppendEmpty())
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
continue
}
mv := v.(*accumulatedValue)
if ip.Timestamp().AsTime().Before(mv.value.Histogram().DataPoints().At(0).Timestamp().AsTime()) {
// only keep datapoint with latest timestamp
continue
}
m := copyMetricMetadata(metric)
ip.CopyTo(m.SetEmptyHistogram().DataPoints().AppendEmpty())
m.Histogram().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
a.registeredMetrics.Store(signature, &accumulatedValue{value: m, resourceAttrs: resourceAttrs, scope: il, updated: now})
n++
}
return
}
// Collect returns a slice with relevant aggregated metrics and their resource attributes.
func (a *lastValueAccumulator) Collect() ([]pmetric.Metric, []pcommon.Map) {
a.logger.Debug("Accumulator collect called")
var metrics []pmetric.Metric
var resourceAttrs []pcommon.Map
expirationTime := time.Now().Add(-a.metricExpiration)
a.registeredMetrics.Range(func(key, value any) bool {
v := value.(*accumulatedValue)
if expirationTime.After(v.updated) {
a.logger.Debug(fmt.Sprintf("metric expired: %s", v.value.Name()))
a.registeredMetrics.Delete(key)
return true
}
metrics = append(metrics, v.value)
resourceAttrs = append(resourceAttrs, v.resourceAttrs)
return true
})
return metrics, resourceAttrs
}
func timeseriesSignature(ilmName string, metric pmetric.Metric, attributes pcommon.Map, resourceAttrs pcommon.Map) string {
var b strings.Builder
b.WriteString(metric.Type().String())
b.WriteString("*" + ilmName)
b.WriteString("*" + metric.Name())
attrs := make([]string, 0, attributes.Len())
attributes.Range(func(k string, v pcommon.Value) bool {
attrs = append(attrs, k+"*"+v.AsString())
return true
})
sort.Strings(attrs)
b.WriteString("*" + strings.Join(attrs, "*"))
if job, ok := extractJob(resourceAttrs); ok {
b.WriteString("*" + model.JobLabel + "*" + job)
}
if instance, ok := extractInstance(resourceAttrs); ok {
b.WriteString("*" + model.InstanceLabel + "*" + instance)
}
return b.String()
}
func copyMetricMetadata(metric pmetric.Metric) pmetric.Metric {
m := pmetric.NewMetric()
m.SetName(metric.Name())
m.SetDescription(metric.Description())
m.SetUnit(metric.Unit())
return m
}