forked from DataDog/datadog-lambda-go
/
api.go
147 lines (122 loc) · 3.7 KB
/
api.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
/*
* Unless explicitly stated otherwise all files in this repository are licensed
* under the Apache License Version 2.0.
*
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2019 Datadog, Inc.
*/
package metrics
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/DataDog/datadog-lambda-go/internal/logger"
)
type (
// Client sends metrics to Datadog
Client interface {
SendMetrics(metrics []APIMetric) error
}
// APIClient send metrics to Datadog, via the Datadog API
APIClient struct {
apiKey string
apiKeyDecryptChan <-chan string
baseAPIURL string
httpClient *http.Client
context context.Context
}
// APIClientOptions contains instantiation options from creating an APIClient.
APIClientOptions struct {
baseAPIURL string
apiKey string
kmsAPIKey string
decrypter Decrypter
}
postMetricsModel struct {
Series []APIMetric `json:"series"`
}
)
// MakeAPIClient creates a new API client with the given api and app keys
func MakeAPIClient(ctx context.Context, options APIClientOptions) *APIClient {
httpClient := &http.Client{}
client := &APIClient{
apiKey: options.apiKey,
baseAPIURL: options.baseAPIURL,
httpClient: httpClient,
context: ctx,
}
if len(options.apiKey) == 0 && len(options.kmsAPIKey) != 0 {
client.apiKeyDecryptChan = client.decryptAPIKey(options.decrypter, options.kmsAPIKey)
}
return client
}
// SendMetrics posts a batch metrics payload to the Datadog API
func (cl *APIClient) SendMetrics(metrics []APIMetric) error {
// If the api key was provided as a kms key, wait for it to finish decrypting
if cl.apiKeyDecryptChan != nil {
cl.apiKey = <-cl.apiKeyDecryptChan
cl.apiKeyDecryptChan = nil
}
content, err := marshalAPIMetricsModel(metrics)
if err != nil {
return fmt.Errorf("Couldn't marshal metrics model: %v", err)
}
body := bytes.NewBuffer(content)
// For the moment we only support distribution metrics.
// Other metric types use the "series" endpoint, which takes an identical payload.
req, err := http.NewRequest("POST", cl.makeRoute("distribution_points"), body)
if err != nil {
return fmt.Errorf("Couldn't create send metrics request:%v", err)
}
req = req.WithContext(cl.context)
defer req.Body.Close()
logger.Debug(fmt.Sprintf("Sending payload with body %s", content))
cl.addAPICredentials(req)
resp, err := cl.httpClient.Do(req)
if err != nil {
return fmt.Errorf("Failed to send metrics to API")
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
if resp.StatusCode == 403 {
logger.Debug(fmt.Sprintf("authorization failed with api key of length %d characters", len(cl.apiKey)))
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
body := ""
if err == nil {
body = string(bodyBytes)
}
return fmt.Errorf("Failed to send metrics to API. Status Code %d, Body %s", resp.StatusCode, body)
}
return nil
}
func (cl *APIClient) decryptAPIKey(decrypter Decrypter, kmsAPIKey string) <-chan string {
ch := make(chan string)
go func() {
result, err := decrypter.Decrypt(kmsAPIKey)
if err != nil {
logger.Error(fmt.Errorf("Couldn't decrypt api kms key %s", err))
}
ch <- result
close(ch)
}()
return ch
}
func (cl *APIClient) addAPICredentials(req *http.Request) {
query := req.URL.Query()
query.Add(apiKeyParam, cl.apiKey)
req.URL.RawQuery = query.Encode()
}
func (cl *APIClient) makeRoute(route string) string {
url := fmt.Sprintf("%s/%s", cl.baseAPIURL, route)
logger.Debug(fmt.Sprintf("posting to url %s", url))
return url
}
func marshalAPIMetricsModel(metrics []APIMetric) ([]byte, error) {
pm := postMetricsModel{}
pm.Series = metrics
return json.Marshal(pm)
}