-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
metrics_exporter.go
322 lines (265 loc) · 9.53 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
// 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
//
// https://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 dynatraceexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/dynatraceexporter"
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/dynatrace-oss/dynatrace-metric-utils-go/metric/apiconstants"
"github.com/dynatrace-oss/dynatrace-metric-utils-go/metric/dimensions"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer/consumererror"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/dynatraceexporter/config"
"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/dynatraceexporter/internal/serialization"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/common/ttlmap"
)
const (
cSweepIntervalSeconds = 300
cMaxAgeSeconds = 900
)
// NewExporter exports to a Dynatrace Metrics v2 API
func newMetricsExporter(params component.ExporterCreateSettings, cfg *config.Config) *exporter {
confDefaultDims := []dimensions.Dimension{}
for key, value := range cfg.DefaultDimensions {
confDefaultDims = append(confDefaultDims, dimensions.NewDimension(key, value))
}
defaultDimensions := dimensions.MergeLists(
dimensionsFromTags(cfg.Tags),
dimensions.NewNormalizedDimensionList(confDefaultDims...),
)
staticDimensions := dimensions.NewNormalizedDimensionList(dimensions.NewDimension("dt.metrics.source", "opentelemetry"))
prevPts := ttlmap.New(cSweepIntervalSeconds, cMaxAgeSeconds)
prevPts.Start()
return &exporter{
settings: params.TelemetrySettings,
cfg: cfg,
defaultDimensions: defaultDimensions,
staticDimensions: staticDimensions,
prevPts: prevPts,
}
}
// exporter forwards metrics to a Dynatrace agent
type exporter struct {
settings component.TelemetrySettings
cfg *config.Config
client *http.Client
isDisabled bool
defaultDimensions dimensions.NormalizedDimensionList
staticDimensions dimensions.NormalizedDimensionList
prevPts *ttlmap.TTLMap
}
// for backwards-compatibility with deprecated `Tags` config option
func dimensionsFromTags(tags []string) dimensions.NormalizedDimensionList {
dims := []dimensions.Dimension{}
for _, tag := range tags {
parts := strings.SplitN(tag, "=", 2)
if len(parts) == 2 {
dims = append(dims, dimensions.NewDimension(parts[0], parts[1]))
}
}
return dimensions.NewNormalizedDimensionList(dims...)
}
func (e *exporter) PushMetricsData(ctx context.Context, md pmetric.Metrics) error {
if e.isDisabled {
return nil
}
lines := e.serializeMetrics(md)
e.settings.Logger.Debug(
"Serialization complete",
zap.Int("data-point-count", md.DataPointCount()),
zap.Int("lines", len(lines)),
)
// If request is empty string, there are no serializable metrics in the batch.
// This can happen if all metric names are invalid
if len(lines) == 0 {
return nil
}
err := e.send(ctx, lines)
if err != nil {
return err
}
return nil
}
func (e *exporter) serializeMetrics(md pmetric.Metrics) []string {
lines := make([]string, 0)
resourceMetrics := md.ResourceMetrics()
for i := 0; i < resourceMetrics.Len(); i++ {
resourceMetric := resourceMetrics.At(i)
libraryMetrics := resourceMetric.ScopeMetrics()
for j := 0; j < libraryMetrics.Len(); j++ {
libraryMetric := libraryMetrics.At(j)
metrics := libraryMetric.Metrics()
for k := 0; k < metrics.Len(); k++ {
metric := metrics.At(k)
metricLines, err := serialization.SerializeMetric(e.settings.Logger, e.cfg.Prefix, metric, e.defaultDimensions, e.staticDimensions, e.prevPts)
if err != nil {
e.settings.Logger.Warn(
"failed to serialize",
zap.String("name", metric.Name()),
zap.String("data-type", metric.DataType().String()),
zap.Error(err),
)
}
if len(metricLines) > 0 {
lines = append(lines, metricLines...)
}
e.settings.Logger.Debug(
"Serialized metric data",
zap.String("name", metric.Name()),
zap.String("data-type", metric.DataType().String()),
zap.Int("data-len", len(metricLines)),
)
}
}
}
return lines
}
var lastLog int64
// send sends a serialized metric batch to Dynatrace.
// An error indicates all lines were dropped regardless of the returned number.
func (e *exporter) send(ctx context.Context, lines []string) error {
e.settings.Logger.Debug("Exporting", zap.Int("lines", len(lines)))
if now := time.Now().Unix(); len(lines) > apiconstants.GetPayloadLinesLimit() && now-lastLog > 60 {
e.settings.Logger.Warn(
fmt.Sprintf(
"Batch too large. Sending in chunks of %[1]d metrics. If any chunk fails, previous chunks in the batch could be retried by the batch processor. Please set send_batch_max_size to %[1]d or less. Suppressing this log for 60 seconds.",
apiconstants.GetPayloadLinesLimit(),
),
)
lastLog = time.Now().Unix()
}
for i := 0; i < len(lines); i += apiconstants.GetPayloadLinesLimit() {
end := i + apiconstants.GetPayloadLinesLimit()
if end > len(lines) {
end = len(lines)
}
err := e.sendBatch(ctx, lines[i:end])
if err != nil {
return err
}
}
return nil
}
// send sends a serialized metric batch to Dynatrace.
// An error indicates all lines were dropped regardless of the returned number.
func (e *exporter) sendBatch(ctx context.Context, lines []string) error {
message := strings.Join(lines, "\n")
e.settings.Logger.Debug(
"sending a batch of metric lines",
zap.Int("lines", len(lines)),
zap.String("endpoint", e.cfg.Endpoint),
)
req, err := http.NewRequestWithContext(ctx, "POST", e.cfg.Endpoint, bytes.NewBufferString(message))
if err != nil {
return consumererror.NewPermanent(err)
}
resp, err := e.client.Do(req)
if err != nil {
e.settings.Logger.Error("failed to send request", zap.Error(err))
return fmt.Errorf("sendBatch: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusRequestEntityTooLarge {
// If a payload is too large, resending it will not help
return consumererror.NewPermanent(fmt.Errorf("payload too large"))
}
if resp.StatusCode == http.StatusBadRequest {
// At least some metrics were not accepted
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
// if the response cannot be read, do not retry the batch as it may have been successful
e.settings.Logger.Error("Failed to read response from Dynatrace", zap.Error(err))
return nil
}
responseBody := metricsResponse{}
if err := json.Unmarshal(bodyBytes, &responseBody); err != nil {
// if the response cannot be read, do not retry the batch as it may have been successful
bodyStr := string(bodyBytes)
bodyStr = truncateString(bodyStr, 1000)
e.settings.Logger.Error("Failed to unmarshal response from Dynatrace", zap.Error(err), zap.String("body", bodyStr))
return nil
}
e.settings.Logger.Warn(
"Response from Dynatrace",
zap.Int("accepted-lines", responseBody.Ok),
zap.Int("rejected-lines", responseBody.Invalid),
zap.String("error-message", responseBody.Error.Message),
zap.String("status", resp.Status),
)
for _, line := range responseBody.Error.InvalidLines {
// Enabled debug logging to see which lines were dropped
if line.Line >= 0 && line.Line < len(lines) {
e.settings.Logger.Debug(
fmt.Sprintf("rejected line %3d: [%s] %s", line.Line, line.Error, lines[line.Line]),
)
}
}
return nil
}
if resp.StatusCode == http.StatusUnauthorized {
// token is missing or wrong format
e.isDisabled = true
return consumererror.NewPermanent(fmt.Errorf("API token missing or invalid"))
}
if resp.StatusCode == http.StatusForbidden {
return consumererror.NewPermanent(fmt.Errorf("API token missing the required scope (metrics.ingest)"))
}
if resp.StatusCode == http.StatusNotFound {
return consumererror.NewPermanent(fmt.Errorf("metrics ingest v2 module not found - ensure module is enabled and endpoint is correct"))
}
// No known errors
return nil
}
// start starts the exporter
func (e *exporter) start(_ context.Context, host component.Host) (err error) {
client, err := e.cfg.HTTPClientSettings.ToClient(host.GetExtensions(), e.settings)
if err != nil {
e.settings.Logger.Error("Failed to construct HTTP client", zap.Error(err))
return fmt.Errorf("start: %w", err)
}
e.client = client
return nil
}
func truncateString(str string, num int) string {
truncated := str
if len(str) > num {
if num > 3 {
num -= 3
}
truncated = str[0:num] + "..."
}
return truncated
}
// Response from Dynatrace is expected to be in JSON format
type metricsResponse struct {
Ok int `json:"linesOk"`
Invalid int `json:"linesInvalid"`
Error metricsResponseError `json:"error"`
}
type metricsResponseError struct {
Code int `json:"code"`
Message string `json:"message"`
InvalidLines []metricsResponseErrorInvalidLine `json:"invalidLines"`
}
type metricsResponseErrorInvalidLine struct {
Line int `json:"line"`
Error string `json:"error"`
}