forked from DataDog/datadog-agent
-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
222 lines (185 loc) · 6.97 KB
/
client.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
package httpclient
import (
"bytes"
"compress/gzip"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/StackVista/stackstate-agent/pkg/config"
"github.com/StackVista/stackstate-agent/pkg/util/log"
"github.com/StackVista/stackstate-agent/pkg/version"
retryablehttp "github.com/hashicorp/go-retryablehttp"
)
// GET is used for HTTP GET calls
const GET = "GET"
// POST is used for HTTP POST calls
const POST = "POST"
// PUT is used for HTTP PUT calls
const PUT = "PUT"
// HTTPResponse is used to represent the response from the request
type HTTPResponse struct {
Response *http.Response
RequestPayload []byte
Err error
}
// ClientHost specifies an host that the client communicates with.
type ClientHost struct {
APIKey string `json:"-"` // never marshal this
Host string
// NoProxy will be set to true when the proxy setting for the trace API endpoint
// needs to be ignored (e.g. it is part of the "no_proxy" list in the yaml settings).
NoProxy bool
ProxyURL *url.URL
SkipSSLValidation bool
ContentEncoding ContentEncoding // TODO: make this per request
}
// RetryableHTTPClient describes the functionality of a http client with retries and backoff
type RetryableHTTPClient interface {
Get(path string) *HTTPResponse
Put(path string, body []byte) *HTTPResponse
Post(path string, body []byte) *HTTPResponse
}
// RetryableHTTPClient creates a http client to communicate to StackState
type retryableHTTPClient struct {
*ClientHost
*retryablehttp.Client
}
// StackStateClient creates a wrapper around the RetryableHTTPClient that is used for communication with StackState over http(s)
type StackStateClient struct {
RetryableHTTPClient
}
// NewStackStateClient returns a RetryableHTTPClient containing a http.Client configured with the Agent options.
func NewStackStateClient() RetryableHTTPClient {
return &StackStateClient{NewHTTPClient("sts_url")}
}
// NewHTTPClient returns a RetryableHTTPClient containing a http.Client configured with the Agent options.
func NewHTTPClient(baseURLConfigKey string) RetryableHTTPClient {
return makeRetryableHTTPClient(baseURLConfigKey)
}
func makeRetryableHTTPClient(baseURLConfigKey string) RetryableHTTPClient {
host := &ClientHost{}
if hostURL := config.Datadog.GetString(baseURLConfigKey); hostURL != "" {
host.Host = hostURL
}
host.APIKey = config.Datadog.GetString("api_key")
host.ContentEncoding = NewGzipContentEncoding(gzip.BestCompression)
proxyList := config.Datadog.GetStringSlice("proxy.no_proxy")
noProxy := make(map[string]bool, len(proxyList))
for _, host := range proxyList {
// map of hosts that need to be skipped by proxy
noProxy[host] = true
}
host.NoProxy = noProxy[host.Host]
if addr := config.Datadog.GetString("proxy.https"); addr != "" {
url, err := url.Parse(addr)
if err == nil {
host.ProxyURL = url
} else {
log.Errorf("Failed to parse proxy URL from proxy.https configuration: %s", err)
}
}
if config.Datadog.IsSet("skip_ssl_validation") {
host.SkipSSLValidation = config.Datadog.GetBool("skip_ssl_validation")
}
return &retryableHTTPClient{
ClientHost: host,
Client: newClient(host),
}
}
// newClient returns a http.Client configured with the Agent options.
func newClient(host *ClientHost) *retryablehttp.Client {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: host.SkipSSLValidation},
}
if host.ProxyURL != nil && !host.NoProxy {
log.Infof("configuring proxy through: %s", host.ProxyURL.String())
transport.Proxy = http.ProxyURL(host.ProxyURL)
}
retryableClient := retryablehttp.NewClient()
// Make retryableClient logging use log level settings by replace the default logger with wrapped leveledLogger
retryableClient.Logger = &leveledLogger{}
retryableClient.HTTPClient = &http.Client{Timeout: 30 * time.Second, Transport: transport}
if config.Datadog.IsSet("transactional_forwarder_retry_min") {
retryableClient.RetryWaitMin = config.Datadog.GetDuration("transactional_forwarder_retry_min")
}
if config.Datadog.IsSet("transactional_forwarder_retry_max") {
retryableClient.RetryWaitMax = config.Datadog.GetDuration("transactional_forwarder_retry_max")
}
return retryableClient
}
// Get performs a GET request to some path
func (rc *retryableHTTPClient) Get(path string) *HTTPResponse {
return rc.handleRequest(GET, path, nil)
}
// Put performs a PUT request to some path
func (rc *retryableHTTPClient) Put(path string, body []byte) *HTTPResponse {
return rc.handleRequest(PUT, path, body)
}
// Post performs a POST request to some path
func (rc *retryableHTTPClient) Post(path string, body []byte) *HTTPResponse {
return rc.handleRequest(POST, path, body)
}
// getSupportedFeatures returns the features supported by the StackState API
func (rc *retryableHTTPClient) handleRequest(method, path string, body []byte) *HTTPResponse {
req, err := rc.makeRequest(method, path, body)
if err != nil {
return &HTTPResponse{
Err: err,
}
}
response, err := rc.Do(req)
return &HTTPResponse{Response: response, RequestPayload: body, Err: err}
}
// makeRequest
func (rc *retryableHTTPClient) makeRequest(method, path string, body []byte) (*retryablehttp.Request, error) {
url := fmt.Sprintf("%s/%s%s", rc.Host, path, fmt.Sprintf("?api_key=%s", rc.APIKey))
var req *retryablehttp.Request
var err error
if body != nil {
if gzipped, encodingError := rc.ContentEncoding.encode(body); encodingError != nil {
_ = log.Warnf("http client was not able to send payload as %s, reverting to uncompressed payload: %s",
rc.ContentEncoding.name(), err)
req, err = retryablehttp.NewRequest(method, url, bytes.NewBuffer(body))
} else {
log.Debugf("Using %s compression for payload", rc.ContentEncoding.name())
req, err = retryablehttp.NewRequest(method, url, gzipped)
req.Header.Add("content-encoding", rc.ContentEncoding.name())
}
} else {
req, err = retryablehttp.NewRequest(method, url, nil)
}
if err != nil {
return nil, fmt.Errorf("could not create request to %s/%s: %s", url, path, err)
}
req.Header.Add("sts-api-key", rc.APIKey)
req.Header.Add("sts-hostname", rc.Host)
req.Header.Add("sts-agent-version", version.AgentVersion)
req.Header.Add("content-type", "application/json")
return req, nil
}
// Wrapper for the agent logger to be recognized as a retryablehttp.LeveledLogger
type leveledLogger struct {
}
func (l *leveledLogger) Error(msg string, keysAndValues ...interface{}) {
log.Errorf(msg, keysAndValues...)
}
func (l *leveledLogger) Info(msg string, keysAndValues ...interface{}) {
log.Infof(msg, keysAndValues...)
}
func (l *leveledLogger) Debug(msg string, keysAndValues ...interface{}) {
log.Debugf(msg, keysAndValues)
}
func (l *leveledLogger) Warn(msg string, keysAndValues ...interface{}) {
log.Warn(msg, keysAndValues)
}