/
datadog.go
475 lines (398 loc) · 12.9 KB
/
datadog.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright 2022 Block, Inc.
package sink
import (
"bytes"
"compress/zlib"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/cashapp/blip/event"
"github.com/DataDog/datadog-go/v5/statsd"
"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
"github.com/cashapp/blip"
"github.com/cashapp/blip/sink/tr"
"github.com/cashapp/blip/status"
)
var portRe = regexp.MustCompile(`:\d+$`)
const (
MAX_PAYLOAD_SIZE int = 512000
)
// Datadog sends metrics to Datadog.
type Datadog struct {
monitorId string
tags []string // monitor.tags (dimensions)
tr tr.DomainTranslator // datadog.metric-translator
prefix string // datadog.metric-prefix
// -- Api
metricsApi *datadogV2.MetricsApi
apiKeyAuth string
appKeyAuth string
resources []datadogV2.MetricResource
compress bool
maxMetricsPerRequest int // Limit the number of metrics we send per request. Only used with the API
maxMetricsPerRequestLock sync.Mutex
maxPayloadSize int
// -- DogStatsD
dogstatsd bool
dogstatsdClient *statsd.Client
dogstatsdHost string
}
func NewDatadog(monitorId string, opts, tags map[string]string, httpClient *http.Client) (*Datadog, error) {
tagList := make([]string, 0, len(tags))
var resources []datadogV2.MetricResource = nil
for k, v := range tags {
tagList = append(tagList, fmt.Sprintf("%s:%s", k, v))
// If we have a "host" tag, we should include a resource definition for host
// so that metrics are properly associated with infrastructure in Datadog
if k == "host" {
resources = []datadogV2.MetricResource{
{
Name: datadog.PtrString(v),
Type: datadog.PtrString("host"),
},
}
}
}
d := &Datadog{
monitorId: monitorId,
tags: tagList,
resources: resources,
maxMetricsPerRequest: math.MaxInt32, // By default don't limit the number of metrics per request.
compress: true,
maxPayloadSize: MAX_PAYLOAD_SIZE,
}
for k, v := range opts {
switch k {
case "api-key-auth":
d.apiKeyAuth = v
case "api-key-auth-file":
bytes, err := ioutil.ReadFile(v)
if err != nil {
return nil, err
} else {
d.apiKeyAuth = string(bytes)
}
case "app-key-auth":
d.appKeyAuth = v
case "app-key-auth-file":
bytes, err := ioutil.ReadFile(v)
if err != nil {
return nil, err
} else {
d.appKeyAuth = string(bytes)
}
case "metric-translator":
tr, err := tr.Make(v)
if err != nil {
return nil, err
}
d.tr = tr
case "metric-prefix":
if v == "" {
return nil, fmt.Errorf("datadog sink metric-prefix is empty string; value required when option is specified")
}
d.prefix = v
case "api-compress":
d.compress = blip.Bool(v)
case "dogstatsd-host":
d.dogstatsdHost = v
default:
return nil, fmt.Errorf("invalid option: %s", k)
}
}
if d.dogstatsdHost != "" {
d.dogstatsd = true
}
// if DogStatsD and api are both setup, return error as it will otherwise result in duplicate metrics
if d.dogstatsd && (d.apiKeyAuth != "" && d.appKeyAuth != "") {
return nil, fmt.Errorf("datadog sink requires either dogstatsd host or (api-key-auth and app-key-auth), not both at the same time")
}
if d.dogstatsd {
if !portRe.MatchString(d.dogstatsdHost) {
d.dogstatsdHost += ":8125"
}
client, err := statsd.New(d.dogstatsdHost)
if err != nil {
return nil, err
}
d.dogstatsdClient = client
} else {
if d.apiKeyAuth == "" {
return nil, fmt.Errorf("datadog sink requires either api-key-auth or api-key-auth-file")
}
if d.appKeyAuth == "" {
return nil, fmt.Errorf("datadog sink requires either app-key-auth or app-key-auth-file")
}
c := datadog.NewConfiguration()
c.HTTPClient = httpClient
c.Compress = d.compress
metricsApi := datadogV2.NewMetricsApi(datadog.NewAPIClient(c))
d.metricsApi = metricsApi
}
return d, nil
}
func (s *Datadog) Send(ctx context.Context, m *blip.Metrics) error {
status.Monitor(s.monitorId, s.Name(), "sending metrics")
// On return, set monitor status for this sink
n := 0
defer func() {
status.Monitor(s.monitorId, s.Name(), "last sent %d metrics at %s", n, time.Now())
}()
// Pre-alloc SFX data points
for _, metrics := range m.Values {
n += len(metrics)
}
if n == 0 {
return fmt.Errorf("no Blip metrics were collected")
}
var dp []datadogV2.MetricSeries
if !s.dogstatsd {
dp = make([]datadogV2.MetricSeries, n)
}
n = 0
// Make a copy of maxMetricsPerRequest in case it gets updated by other threads
localMaxMetricsPerRequest := s.maxMetricsPerRequest
rangeStart := 0
var apiErrors []string
// Setup our context for API calls
ddCtx := context.WithValue(
ctx,
datadog.ContextAPIKeys,
map[string]datadog.APIKey{
"apiKeyAuth": {
Key: s.apiKeyAuth,
},
"appKeyAuth": {
Key: s.apiKeyAuth,
},
},
)
// Convert each Blip metric value to an SFX data point
for domain := range m.Values { // each domain
metrics := m.Values[domain]
var name string
METRICS:
for i := range metrics { // each metric in this domain
// Set full metric name: translator (if any) else Blip standard,
// then prefix (if any)
if s.tr == nil {
name = domain + "." + metrics[i].Name
} else {
name = s.tr.Translate(domain, metrics[i].Name)
}
if s.prefix != "" {
name = s.prefix + name
}
// Copy metric meta and groups into tags (dimensions), if any
var tags []string
if len(metrics[i].Meta) == 0 && len(metrics[i].Group) == 0 {
// Optimization: if no meta or group, then reuse pointer to
// s.tags which points to the tags--never modify s.tags!
tags = s.tags
} else {
// There are meta or groups (or both), so we MUST COPY tags
// from s.tags and the rest into a new map
tags = make([]string, 0, len(s.tags)+len(metrics[i].Meta)+len(metrics[i].Group))
for _, v := range s.tags { // copy tags (from config)
tags = append(tags, v)
}
for k, v := range metrics[i].Meta { // metric meta
if k == "ts" { // avoid time series explosion: ts is high cardinality
continue
}
tags = append(tags, fmt.Sprintf("%s:%s", k, v))
}
for k, v := range metrics[i].Group { // metric groups
tags = append(tags, fmt.Sprintf("%s:%s", k, v))
}
}
var timestamp int64
// Datadog requires a timestamp when creating a data point
if tsStr, ok := metrics[i].Meta["ts"]; !ok {
timestamp = m.Begin.Unix()
} else {
var err error
msTs, err := strconv.ParseInt(tsStr, 10, 64) // ts in milliseconds, string -> int64
if err != nil {
blip.Debug("invalid timestamp for %s %s: %s: %s", domain, metrics[i].Name, tsStr, err)
continue METRICS
}
timestamp = msTs / 1000 // convert to seconds
}
// Convert Blip metric type to Datadog metric type
switch metrics[i].Type {
case blip.COUNTER:
if s.dogstatsd {
err := s.dogstatsdClient.Count(name, int64(metrics[i].Value), tags, 1)
if err != nil {
blip.Debug("error sending data points to Datadog: %s", err)
}
} else {
dp[n] = datadogV2.MetricSeries{
Metric: name,
Type: datadogV2.METRICINTAKETYPE_COUNT.Ptr(),
Points: []datadogV2.MetricPoint{
{
Value: datadog.PtrFloat64(metrics[i].Value),
Timestamp: datadog.PtrInt64(timestamp),
},
},
Tags: tags,
Resources: s.resources,
}
}
case blip.GAUGE, blip.BOOL:
if s.dogstatsd {
err := s.dogstatsdClient.Gauge(name, metrics[i].Value, tags, 1)
if err != nil {
blip.Debug("error sending data points to Datadog: %s", err)
}
} else {
dp[n] = datadogV2.MetricSeries{
Metric: name,
Type: datadogV2.METRICINTAKETYPE_GAUGE.Ptr(),
Points: []datadogV2.MetricPoint{
{
Value: datadog.PtrFloat64(metrics[i].Value),
Timestamp: datadog.PtrInt64(timestamp),
},
},
Tags: tags,
Resources: s.resources,
}
}
default:
// datadog doesn't support this Blip metric type, so skip it
continue METRICS // @todo error?
}
n++
// Check if we have reached the maximum number of metrics per request
if !s.dogstatsd && n%localMaxMetricsPerRequest == 0 {
if err := s.sendApi(ddCtx, dp[rangeStart:n]); err != nil {
apiErrors = append(apiErrors, err.Error())
}
rangeStart = n
}
} // metric
} // domain
// This shouldn't happen: >0 Blip metrics in but =0 Datadog data points out
if n == 0 {
return fmt.Errorf("no Datadog data points after processing %d Blip metrics", len(m.Values))
}
// dogstatsd metrics are sent to the datadog agent inside the loop, there's nothing else to do
if s.dogstatsd {
return nil
}
if n-rangeStart > 0 {
if err := s.sendApi(ddCtx, dp[rangeStart:n]); err != nil {
apiErrors = append(apiErrors, err.Error())
}
}
if len(apiErrors) > 0 {
return fmt.Errorf("%s", strings.Join(apiErrors, "\n"))
}
return nil
}
// Send metrics to the API taking into consideration the number of metrics sent per request.
func (s *Datadog) sendApi(ddCtx context.Context, dp []datadogV2.MetricSeries) error {
localMaxMetricsPerRequest := s.maxMetricsPerRequest
for rangeStart := 0; rangeStart < len(dp); {
// Determine the subetset of metrics to send based on our
// max per request
rangeEnd := rangeStart + localMaxMetricsPerRequest
if rangeEnd > len(dp) {
rangeEnd = len(dp)
}
optParams := *datadogV2.NewSubmitMetricsOptionalParameters()
if s.compress {
optParams.ContentEncoding = datadogV2.METRICCONTENTENCODING_GZIP.Ptr()
}
apiResponse, r, err := s.metricsApi.SubmitMetrics(ddCtx, *datadogV2.NewMetricPayload(dp[rangeStart:rangeEnd]), optParams)
if err != nil {
if r != nil && r.StatusCode == http.StatusRequestEntityTooLarge {
// Is the number of metrics sent already the smallest possible?
if localMaxMetricsPerRequest == 1 {
return fmt.Errorf("unable to send metrics: %v", err)
}
// The payload was too large, so we need to recalculate it and try with a smaller size
if localMaxMetricsPerRequest, err = s.estimateMaxMetricsPerRequest(dp[rangeStart:rangeEnd], localMaxMetricsPerRequest); err != nil {
return fmt.Errorf("unable to determine proper number of metrics per request: %v", err)
}
// Retry the metrics with the new payload size
continue
}
blip.Debug("error sending data points to Datadog: %s, Http Response: %s", err, r)
return err
}
if len(apiResponse.Errors) > 0 {
// datadog can return a 202 Accepted response code but errors in response payload
// this can be partial success, log it, raise an event and continue
errMsg := fmt.Sprintf("%s: error(s) returned from datadog: %s", s.monitorId, strings.Join(apiResponse.Errors, ","))
blip.Debug(errMsg)
// Send an event as well
event.Errorf(event.SINK_ERROR, errMsg) // log by default
}
rangeStart = rangeEnd
}
// Update the maxMetricsPerRequest for the sink
if localMaxMetricsPerRequest < s.maxMetricsPerRequest {
s.maxMetricsPerRequestLock.Lock()
defer s.maxMetricsPerRequestLock.Unlock()
// Check the value again in case it changed after getting the lock
if localMaxMetricsPerRequest < s.maxMetricsPerRequest {
s.maxMetricsPerRequest = localMaxMetricsPerRequest
}
}
return nil
}
// Estimate the number of metrics we can send in a payload based on a sample metric
func (s *Datadog) estimateMaxMetricsPerRequest(metrics []datadogV2.MetricSeries, currentMaxMetricsPerRequest int) (int, error) {
// Estimate the size of a single metric
estMetricSize, err := s.estimateSize(metrics)
if err != nil {
return 0, err
}
// Using our estimated metric size determine out how many metrics can fit inside the max payload, but pad it slightly to control for headers, etc.
estMaxMetricsPerRequest := (s.maxPayloadSize - 300) / estMetricSize
if estMaxMetricsPerRequest >= currentMaxMetricsPerRequest {
// If the estimated maximum is greater than what we currently have set as the maximum then
// reduce the current maximum by 10% as a guess for finding a maximnum number of metrics
// to send that will not be rejected by the API.
estMaxMetricsPerRequest = int(float32(currentMaxMetricsPerRequest) * .9)
}
// Ensure we send at least one metric per request
if estMaxMetricsPerRequest <= 0 {
estMaxMetricsPerRequest = 1
}
return estMaxMetricsPerRequest, nil
}
// Estimate the size of a metric payload for use in determining the maximum number of
// metrics per request. We take the total size of the payload and divide by the number
// of metrics.
func (s *Datadog) estimateSize(metrics []datadogV2.MetricSeries) (int, error) {
data, err := json.Marshal(metrics)
if err != nil {
return 0, err
}
size := len(data)
if s.compress {
var b bytes.Buffer
w := zlib.NewWriter(&b)
w.Write(data)
w.Close()
size = len(b.Bytes())
}
return size / len(metrics), nil
}
func (s *Datadog) Name() string {
return "datadog"
}