-
Notifications
You must be signed in to change notification settings - Fork 479
/
exporter.go
231 lines (202 loc) · 6.79 KB
/
exporter.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
package remotewriteexporter
import (
"context"
"fmt"
"strconv"
"strings"
"time"
util "github.com/cortexproject/cortex/pkg/util/log"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"github.com/grafana/agent/pkg/metrics/instance"
"github.com/grafana/agent/pkg/traces/contextkeys"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/timestamp"
"github.com/prometheus/prometheus/storage"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/model/pdata"
"go.uber.org/atomic"
)
const (
nameLabelKey = "__name__"
sumSuffix = "sum"
countSuffix = "count"
bucketSuffix = "bucket"
leStr = "le"
infBucket = "+Inf"
noSuffix = ""
)
type dataPoint interface {
Attributes() pdata.AttributeMap
}
type remoteWriteExporter struct {
done atomic.Bool
manager instance.Manager
promInstance string
constLabels labels.Labels
namespace string
logger log.Logger
}
func newRemoteWriteExporter(cfg *Config) (component.MetricsExporter, error) {
logger := log.With(util.Logger, "component", "traces remote write exporter")
ls := make(labels.Labels, 0, len(cfg.ConstLabels))
for name, value := range cfg.ConstLabels {
ls = append(ls, labels.Label{Name: name, Value: value})
}
return &remoteWriteExporter{
done: atomic.Bool{},
constLabels: ls,
namespace: cfg.Namespace,
promInstance: cfg.PromInstance,
logger: logger,
}, nil
}
func (e *remoteWriteExporter) Start(ctx context.Context, _ component.Host) error {
manager, ok := ctx.Value(contextkeys.Metrics).(instance.Manager)
if !ok || manager == nil {
return fmt.Errorf("key does not contain a InstanceManager instance")
}
e.manager = manager
return nil
}
func (e *remoteWriteExporter) Shutdown(_ context.Context) error {
e.done.Store(true)
return nil
}
func (e *remoteWriteExporter) Capabilities() consumer.Capabilities {
return consumer.Capabilities{}
}
func (e *remoteWriteExporter) ConsumeMetrics(ctx context.Context, md pdata.Metrics) error {
if e.done.Load() {
return nil
}
prom, err := e.manager.GetInstance(e.promInstance)
if err != nil {
level.Warn(e.logger).Log("msg", "failed to get prom instance", "err", err)
return nil
}
app := prom.Appender(ctx)
rm := md.ResourceMetrics()
for i := 0; i < rm.Len(); i++ {
ilm := rm.At(i).InstrumentationLibraryMetrics()
for j := 0; j < ilm.Len(); j++ {
ms := ilm.At(j).Metrics()
for k := 0; k < ms.Len(); k++ {
switch m := ms.At(k); m.DataType() {
case pdata.MetricDataTypeSum, pdata.MetricDataTypeGauge:
if err := e.processScalarMetric(app, m); err != nil {
return fmt.Errorf("failed to process metric %s", err)
}
case pdata.MetricDataTypeHistogram:
if err := e.processHistogramMetrics(app, m); err != nil {
return fmt.Errorf("failed to process metric %s", err)
}
case pdata.MetricDataTypeSummary:
return fmt.Errorf("%s processing unimplemented", m.DataType())
default:
return fmt.Errorf("unsupported m data type %s", m.DataType())
}
}
}
}
return app.Commit()
}
func (e *remoteWriteExporter) processHistogramMetrics(app storage.Appender, m pdata.Metric) error {
dps := m.Histogram().DataPoints()
return e.handleHistogramIntDataPoints(app, m.Name(), dps)
}
func (e *remoteWriteExporter) handleHistogramIntDataPoints(app storage.Appender, name string, dataPoints pdata.HistogramDataPointSlice) error {
for ix := 0; ix < dataPoints.Len(); ix++ {
dataPoint := dataPoints.At(ix)
if err := e.appendDataPoint(app, name, sumSuffix, dataPoint, dataPoint.Sum()); err != nil {
return err
}
if err := e.appendDataPoint(app, name, countSuffix, dataPoint, float64(dataPoint.Count())); err != nil {
return err
}
var cumulativeCount uint64
for ix, eb := range dataPoint.ExplicitBounds() {
if ix >= len(dataPoint.BucketCounts()) {
break
}
cumulativeCount += dataPoint.BucketCounts()[ix]
boundStr := strconv.FormatFloat(eb, 'f', -1, 64)
ls := labels.Labels{{Name: leStr, Value: boundStr}}
if err := e.appendDataPointWithLabels(app, name, bucketSuffix, dataPoint, float64(cumulativeCount), ls); err != nil {
return err
}
}
// add le=+Inf bucket
cumulativeCount += dataPoint.BucketCounts()[len(dataPoint.BucketCounts())-1]
ls := labels.Labels{{Name: leStr, Value: infBucket}}
if err := e.appendDataPointWithLabels(app, name, bucketSuffix, dataPoint, float64(cumulativeCount), ls); err != nil {
return err
}
}
return nil
}
func (e *remoteWriteExporter) processScalarMetric(app storage.Appender, m pdata.Metric) error {
switch m.DataType() {
case pdata.MetricDataTypeSum:
dataPoints := m.Sum().DataPoints()
if err := e.handleScalarIntDataPoints(app, m.Name(), dataPoints); err != nil {
return err
}
case pdata.MetricDataTypeGauge:
dataPoints := m.Gauge().DataPoints()
if err := e.handleScalarIntDataPoints(app, m.Name(), dataPoints); err != nil {
return err
}
}
return nil
}
func (e *remoteWriteExporter) handleScalarIntDataPoints(app storage.Appender, name string, dataPoints pdata.NumberDataPointSlice) error {
for ix := 0; ix < dataPoints.Len(); ix++ {
dataPoint := dataPoints.At(ix)
if err := e.appendDataPoint(app, name, noSuffix, dataPoint, float64(dataPoint.IntVal())); err != nil {
return err
}
}
return nil
}
func (e *remoteWriteExporter) appendDataPoint(app storage.Appender, name, suffix string, dp dataPoint, v float64) error {
return e.appendDataPointWithLabels(app, name, suffix, dp, v, labels.Labels{})
}
func (e *remoteWriteExporter) appendDataPointWithLabels(app storage.Appender, name, suffix string, dp dataPoint, v float64, customLabels labels.Labels) error {
ls := e.createLabelSet(name, suffix, dp.Attributes(), customLabels)
// TODO(mario.rodriguez): Use timestamp from metric
// time.Now() is used to avoid out-of-order metrics
ts := timestamp.FromTime(time.Now())
if _, err := app.Append(0, ls, ts, v); err != nil {
return err
}
return nil
}
func (e *remoteWriteExporter) createLabelSet(name, suffix string, labelMap pdata.AttributeMap, customLabels labels.Labels) labels.Labels {
ls := make(labels.Labels, 0, labelMap.Len()+1+len(e.constLabels)+len(customLabels))
// Labels from spanmetrics processor
labelMap.Range(func(k string, v pdata.AttributeValue) bool {
ls = append(ls, labels.Label{
Name: strings.Replace(k, ".", "_", -1),
Value: v.StringVal(),
})
return true
})
// Metric name label
ls = append(ls, labels.Label{
Name: nameLabelKey,
Value: metricName(e.namespace, name, suffix),
})
// Const labels
ls = append(ls, e.constLabels...)
// Custom labels
ls = append(ls, customLabels...)
return ls
}
func metricName(namespace, metric, suffix string) string {
if len(suffix) != 0 {
return fmt.Sprintf("%s_%s_%s", namespace, metric, suffix)
}
return fmt.Sprintf("%s_%s", namespace, metric)
}