-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmetrics_exporter.go
410 lines (347 loc) · 13.3 KB
/
metrics_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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package metrics_exporter provides functionality to send cumulative metric data
// using the Prometheus Remote Write API to Logz.io.
package metrics_exporter
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"strconv"
"time"
"github.com/golang/snappy"
"github.com/prometheus/prometheus/prompb"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric/global"
"go.opentelemetry.io/otel/metric/number"
"go.opentelemetry.io/otel/metric/sdkapi"
"go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/metric/aggregator/histogram"
controller "go.opentelemetry.io/otel/sdk/metric/controller/basic"
"go.opentelemetry.io/otel/sdk/metric/export"
"go.opentelemetry.io/otel/sdk/metric/export/aggregation"
processor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
"go.opentelemetry.io/otel/sdk/metric/selector/simple"
"go.opentelemetry.io/otel/sdk/resource"
)
// Exporter forwards metrics to Logz.io
type Exporter struct {
config Config
}
type exportData struct {
export.Record
Resource *resource.Resource
}
// TemporalityFor returns CumulativeExporter so the Processor correctly aggregates data
func (e *Exporter) TemporalityFor(*sdkapi.Descriptor, aggregation.Kind) aggregation.Temporality {
return aggregation.CumulativeTemporality
}
// Export forwards metrics to Logz.io from the SDK
func (e *Exporter) Export(_ context.Context, res *resource.Resource, checkpointSet export.InstrumentationLibraryReader) error {
timeseries, err := e.ConvertToTimeSeries(res, checkpointSet)
if err != nil {
return err
}
message, buildMessageErr := e.buildMessage(timeseries)
if buildMessageErr != nil {
return buildMessageErr
}
request, buildRequestErr := e.buildRequest(message)
if buildRequestErr != nil {
return buildRequestErr
}
sendRequestErr := e.sendRequest(request)
if sendRequestErr != nil {
return sendRequestErr
}
return nil
}
// NewRawExporter validates the Config struct and creates an Exporter with it.
func NewRawExporter(config Config) (*Exporter, error) {
// This is redundant when the user creates the Config struct with the NewConfig
// function.
if err := config.Validate(); err != nil {
return nil, err
}
exporter := Exporter{config}
return &exporter, nil
}
// NewExportPipeline sets up a complete export pipeline with a push Controller and
// Exporter.
func NewExportPipeline(config Config, options ...controller.Option) (*controller.Controller, error) {
exporter, err := NewRawExporter(config)
if err != nil {
return nil, err
}
cont := controller.New(
processor.NewFactory(
simple.NewWithHistogramDistribution(
histogram.WithExplicitBoundaries(config.HistogramBoundaries),
),
exporter,
),
append(options, controller.WithExporter(exporter))...,
)
return cont, cont.Start(context.TODO())
}
// InstallNewPipeline registers a push Controller's MeterProvider globally.
func InstallNewPipeline(config Config, options ...controller.Option) (*controller.Controller, error) {
cont, err := NewExportPipeline(config, options...)
if err != nil {
return nil, err
}
global.SetMeterProvider(cont)
return cont, nil
}
// ConvertToTimeSeries converts a InstrumentationLibraryReader to a slice of TimeSeries pointers
// Based on the aggregation type, ConvertToTimeSeries will call helper functions like
// convertFromSum to generate the correct number of TimeSeries.
func (e *Exporter) ConvertToTimeSeries(res *resource.Resource, checkpointSet export.InstrumentationLibraryReader) ([]prompb.TimeSeries, error) {
var aggError error
var timeSeries []prompb.TimeSeries
// Iterate over each record in the checkpoint set and convert to TimeSeries
aggError = checkpointSet.ForEach(func(library instrumentation.Library, reader export.Reader) error {
return reader.ForEach(e, func(record export.Record) error {
// Convert based on aggregation type
edata := exportData{
Resource: res,
Record: record,
}
agg := record.Aggregation()
// The following section uses loose type checking to determine how to
// convert aggregations to timeseries. More "expensive" timeseries are
// checked first.
//
// See the Aggregator Kind for more information
// https://github.com/open-telemetry/opentelemetry-go/blob/main/sdk/export/metric/aggregation/aggregation.go#L123-L138
if histogram, ok := agg.(aggregation.Histogram); ok {
tSeries, err := convertFromHistogram(edata, histogram)
if err != nil {
return err
}
timeSeries = append(timeSeries, tSeries...)
} else if sum, ok := agg.(aggregation.Sum); ok {
tSeries, err := convertFromSum(edata, sum)
if err != nil {
return err
}
timeSeries = append(timeSeries, tSeries)
} else if lastValue, ok := agg.(aggregation.LastValue); ok {
tSeries, err := convertFromLastValue(edata, lastValue)
if err != nil {
return err
}
timeSeries = append(timeSeries, tSeries)
} else {
// Report to the user when no conversion was found
fmt.Printf("No conversion found for record: %s\n", edata.Descriptor().Name())
}
return nil
})
})
// Check if error was returned in checkpointSet.ForEach()
if aggError != nil {
return nil, aggError
}
return timeSeries, nil
}
// createTimeSeries is a helper function to create a timeseries from a value and attributes
func createTimeSeries(edata exportData, value number.Number, valueNumberKind number.Kind, extraAttributes ...attribute.KeyValue) prompb.TimeSeries {
sample := prompb.Sample{
Value: value.CoerceToFloat64(valueNumberKind),
Timestamp: int64(time.Nanosecond) * edata.EndTime().UnixNano() / int64(time.Millisecond),
}
attributes := createLabelSet(edata, extraAttributes...)
return prompb.TimeSeries{
Samples: []prompb.Sample{sample},
Labels: attributes,
}
}
// convertFromSum returns a single TimeSeries based on a Record with a Sum aggregation
func convertFromSum(edata exportData, sum aggregation.Sum) (prompb.TimeSeries, error) {
// Get Sum value
value, err := sum.Sum()
if err != nil {
return prompb.TimeSeries{}, err
}
// Create TimeSeries. Note that Logz.io requires the name attribute to be in the format
// "__name__". This is the case for all time series created by this exporter.
name := sanitize(edata.Descriptor().Name())
numberKind := edata.Descriptor().NumberKind()
tSeries := createTimeSeries(edata, value, numberKind, attribute.String("__name__", name))
return tSeries, nil
}
// convertFromLastValue returns a single TimeSeries based on a Record with a LastValue aggregation
func convertFromLastValue(edata exportData, lastValue aggregation.LastValue) (prompb.TimeSeries, error) {
// Get value
value, _, err := lastValue.LastValue()
if err != nil {
return prompb.TimeSeries{}, err
}
// Create TimeSeries
name := sanitize(edata.Descriptor().Name())
numberKind := edata.Descriptor().NumberKind()
tSeries := createTimeSeries(edata, value, numberKind, attribute.String("__name__", name))
return tSeries, nil
}
// convertFromHistogram returns len(histogram.Buckets) timeseries for a histogram aggregation
func convertFromHistogram(edata exportData, histogram aggregation.Histogram) ([]prompb.TimeSeries, error) {
var timeSeries []prompb.TimeSeries
metricName := sanitize(edata.Descriptor().Name())
numberKind := edata.Descriptor().NumberKind()
// Create Sum TimeSeries
sum, err := histogram.Sum()
if err != nil {
return nil, err
}
sumTimeSeries := createTimeSeries(edata, sum, numberKind, attribute.String("__name__", metricName+"_sum"))
timeSeries = append(timeSeries, sumTimeSeries)
// Handle Histogram buckets
buckets, err := histogram.Histogram()
if err != nil {
return nil, err
}
var totalCount float64
// counts maps from the bucket upper-bound to the cumulative count.
// The bucket with upper-bound +inf is not included.
counts := make(map[float64]float64, len(buckets.Boundaries))
for i, boundary := range buckets.Boundaries {
// Add bucket count to totalCount and record in map
totalCount += float64(buckets.Counts[i])
counts[boundary] = totalCount
// Add upper boundary as a attribute. e.g. {le="5"}
boundaryStr := strconv.FormatFloat(boundary, 'f', -1, 64)
// Create timeSeries and append
boundaryTimeSeries := createTimeSeries(edata, number.NewFloat64Number(totalCount), number.Float64Kind, attribute.String("__name__", metricName), attribute.String("le", boundaryStr))
timeSeries = append(timeSeries, boundaryTimeSeries)
}
// Include the +inf boundary in the total count
totalCount += float64(buckets.Counts[len(buckets.Counts)-1])
// Create a timeSeries for the +inf bucket and total count
// These are the same and are both required by Prometheus-based backends
upperBoundTimeSeries := createTimeSeries(edata, number.NewFloat64Number(totalCount), number.Float64Kind, attribute.String("__name__", metricName), attribute.String("le", "+inf"))
countTimeSeries := createTimeSeries(edata, number.NewFloat64Number(totalCount), number.Float64Kind, attribute.String("__name__", metricName+"_count"))
timeSeries = append(timeSeries, upperBoundTimeSeries)
timeSeries = append(timeSeries, countTimeSeries)
return timeSeries, nil
}
// createLabelSet combines attributes from a Record, resource, and extra attributes to create a
// slice of prompb.Label.
func createLabelSet(edata exportData, extraAttributes ...attribute.KeyValue) []prompb.Label {
// Map ensure no duplicate label names.
labelMap := map[string]prompb.Label{}
// mergeAttributes merges Record and Resource attributes into a single set, giving precedence
// to the record's attributes.
mi := attribute.NewMergeIterator(edata.Labels(), edata.Resource.Set())
for mi.Next() {
attribute := mi.Label()
key := string(attribute.Key)
labelMap[key] = prompb.Label{
Name: sanitize(key),
Value: attribute.Value.Emit(),
}
}
// Add extra attributes created by the exporter like the metric name or attributes to
// represent histogram buckets.
for _, attribute := range extraAttributes {
// Ensure attribute doesn't exist. If it does, notify user that a user created attribute
// is being overwritten by a Prometheus reserved label (e.g. 'le' for histograms)
key := string(attribute.Key)
value := attribute.Value.AsString()
_, found := labelMap[key]
if found {
log.Printf("Attribute %s is overwritten. Check if Prometheus reserved labels are used.\n", key)
}
labelMap[key] = prompb.Label{
Name: key,
Value: value,
}
}
// Create slice of labels from labelMap and return
res := make([]prompb.Label, 0, len(labelMap))
for _, lb := range labelMap {
res = append(res, lb)
}
return res
}
// addHeaders adds required headers, an Authorization header, and all headers in the
// Config Headers map to a http request.
func (e *Exporter) addHeaders(req *http.Request) error {
// Logz.io expects Snappy-compressed protobuf messages. These three headers are
// hard-coded as they should be on every request.
req.Header.Add("X-Prometheus-Remote-Write-Version", "0.1.0")
req.Header.Add("Content-Encoding", "snappy")
req.Header.Set("Content-Type", "application/x-protobuf")
// Add Authorization header
bearerTokenString := "Bearer " + e.config.LogzioMetricsToken
req.Header.Set("Authorization", bearerTokenString)
return nil
}
// buildMessage creates a Snappy-compressed protobuf message from a slice of TimeSeries.
func (e *Exporter) buildMessage(timeseries []prompb.TimeSeries) ([]byte, error) {
// Wrap the TimeSeries as a WriteRequest since Logz.io requires it.
writeRequest := &prompb.WriteRequest{
Timeseries: timeseries,
}
// Convert the struct to a slice of bytes and then compress it.
message := make([]byte, writeRequest.Size())
written, err := writeRequest.MarshalToSizedBuffer(message)
if err != nil {
return nil, err
}
message = message[:written]
compressed := snappy.Encode(nil, message)
return compressed, nil
}
// buildRequest creates http POST request with a Snappy-compressed protocol buffer
// message as the body and with all the headers attached.
func (e *Exporter) buildRequest(message []byte) (*http.Request, error) {
req, err := http.NewRequest(
http.MethodPost,
e.config.LogzioMetricsListener,
bytes.NewBuffer(message),
)
if err != nil {
return nil, err
}
// Add the required headers and the headers from Config.Headers.
err = e.addHeaders(req)
if err != nil {
return nil, err
}
return req, nil
}
// sendRequest sends http request using the Exporter's http Client.
func (e *Exporter) sendRequest(req *http.Request) error {
// Set a client if there is no client.
if e.config.client == nil {
e.config.client = &http.Client{
Transport: http.DefaultTransport,
Timeout: e.config.RemoteTimeout,
}
}
// Attempt to send request.
res, err := e.config.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// The response should have a status code of 200.
if res.StatusCode != http.StatusOK {
return fmt.Errorf("%v", res.Status)
}
return nil
}