/
httpclient.go
464 lines (367 loc) · 12.8 KB
/
httpclient.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
package httpclient
import (
"bytes"
"context"
"fmt"
"github.com/elasticpath/epcc-cli/config"
"github.com/elasticpath/epcc-cli/external/authentication"
"github.com/elasticpath/epcc-cli/external/headergroups"
"github.com/elasticpath/epcc-cli/external/json"
"github.com/elasticpath/epcc-cli/external/profiles"
"github.com/elasticpath/epcc-cli/external/shutdown"
"github.com/elasticpath/epcc-cli/external/version"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
"io"
"net/http"
"net/http/httputil"
"net/url"
"os"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"time"
)
var RawHeaders []string
const EnvNameHttpPrefix = "EPCC_CLI_HTTP_HEADER_"
const EnvUrlMatch = "EPCC_CLI_URL_MATCH_REGEXP_(\\d+)"
const EnvUrlMatchPrefix = "EPCC_CLI_URL_MATCH_SUBSTITUTION_"
var urlSubstitions = map[*regexp.Regexp]string{}
var httpHeaders = map[string]string{}
var DontLog2xxs = false
var stats = struct {
totalRateLimitedTimeInMs int64
totalHttpRequestProcessingTime int64
totalRequests uint64
respCodes map[int]int
}{}
func init() {
stats.respCodes = make(map[int]int)
urlMatchRegexp := regexp.MustCompile(EnvUrlMatch)
for _, env := range os.Environ() {
splitEnv := strings.SplitN(env, "=", 2)
if len(splitEnv) == 2 {
envName := splitEnv[0]
envValue := splitEnv[1]
if strings.HasPrefix(envName, EnvNameHttpPrefix) {
headersSplit := strings.SplitN(envValue, ":", 2)
if len(headersSplit) != 2 {
log.Warnf("Found environment variable with malformed value %s => %s. Headers should be set in a Key: Value format. This value is being ignored.", envName, envValue)
} else {
httpHeaders[headersSplit[0]] = headersSplit[1]
}
}
if groups := urlMatchRegexp.FindStringSubmatch(envName); groups != nil {
if groups != nil {
r, err := regexp.Compile(envValue)
if err != nil {
log.Warnf("Environment variable %s has a malformed regex and substition cannot be performed, %v", env, err)
} else {
urlSubstitions[r] = os.Getenv(EnvUrlMatchPrefix + groups[1])
}
}
}
}
}
}
var Limit *rate.Limiter = nil
func Initialize(rateLimit uint16, requestTimeout float32, statisticsFrequency int) {
Limit = rate.NewLimiter(rate.Limit(rateLimit), 1)
HttpClient.Timeout = time.Duration(int64(requestTimeout*1000) * int64(time.Millisecond))
if statisticsFrequency > 0 {
go func() {
lastTotalRequests := uint64(0)
for {
time.Sleep(time.Duration(statisticsFrequency) * time.Second)
statsLock.Lock()
deltaRequests := stats.totalRequests - lastTotalRequests
lastTotalRequests = stats.totalRequests
statsLock.Unlock()
if shutdown.ShutdownFlag.Load() {
break
}
if deltaRequests > 0 {
log.Infof("Total requests %d, requests in past %d seconds %d, latest %d requests per second.", lastTotalRequests, statisticsFrequency, deltaRequests, deltaRequests/uint64(statisticsFrequency))
}
}
}()
}
}
var Retry429 = false
var Retry5xx = false
var RetryConnectionErrors = false
var RetryAllErrors = false
var RetryDelay uint = 500
var statsLock = &sync.Mutex{}
var HttpClient = &http.Client{}
func LogStats() {
statsLock.Lock()
defer statsLock.Unlock()
keys := make([]int, 0, len(stats.respCodes))
for k := range stats.respCodes {
keys = append(keys, k)
}
sort.Ints(keys)
counts := ""
for _, k := range keys {
if k == 0 {
counts += fmt.Sprintf("CONN_ERROR:%d, ", stats.respCodes[k])
} else {
counts += fmt.Sprintf("%d:%d, ", k, stats.respCodes[k])
}
}
if stats.totalRequests > 3 {
log.Infof("Total requests %d, and total rate limiting time %d ms, and total processing time %d ms. Response Code Count: %s", stats.totalRequests, stats.totalRateLimitedTimeInMs, stats.totalHttpRequestProcessingTime, counts)
} else {
log.Debugf("Total requests %d, and total rate limiting time %d ms and total processing time %d ms. Response Code Count: %s", stats.totalRequests, stats.totalRateLimitedTimeInMs, stats.totalHttpRequestProcessingTime, counts)
}
}
func DoRequest(ctx context.Context, method string, path string, query string, payload io.Reader) (response *http.Response, error error) {
return doRequestInternal(ctx, method, "application/json", path, query, payload)
}
func DoFileRequest(ctx context.Context, path string, payload io.Reader, contentType string) (response *http.Response, error error) {
return doRequestInternal(ctx, "POST", contentType, path, "", payload)
}
var UserAgent = fmt.Sprintf("epcc-cli/%s-%s (%s/%s)", version.Version, version.Commit, runtime.GOOS, runtime.GOARCH)
var noApiEndpointUrlWarningMessageMutex = sync.RWMutex{}
var noApiEndpointUrlWarningMessageLogged = false
// DoRequest makes a html request to the EPCC API and handles the response.
func doRequestInternal(ctx context.Context, method string, contentType string, path string, query string, payload io.Reader) (response *http.Response, error error) {
if shutdown.ShutdownFlag.Load() {
return nil, fmt.Errorf("Shutting down")
}
env := config.GetEnv()
reqURL, err := url.Parse(env.EPCC_API_BASE_URL)
if err != nil {
return nil, err
}
if reqURL.Host == "" {
noApiEndpointUrlWarningMessageMutex.RLock()
// Double check lock, read once with read lock, then once again with write lock
if !noApiEndpointUrlWarningMessageLogged {
noApiEndpointUrlWarningMessageMutex.RUnlock()
noApiEndpointUrlWarningMessageMutex.Lock()
if !noApiEndpointUrlWarningMessageLogged {
log.Infof("No API endpoint set in profile or environment variables, defaulting to \"%s\". To change this set the EPCC_API_BASE_URL environment variable (1).", config.DefaultUrl)
noApiEndpointUrlWarningMessageLogged = true
}
noApiEndpointUrlWarningMessageMutex.Unlock()
} else {
noApiEndpointUrlWarningMessageMutex.RUnlock()
}
reqURL, err = url.Parse(config.DefaultUrl)
if err != nil {
log.Fatalf("Error when parsing default host, this is a bug, %s", config.DefaultUrl)
}
}
origPath := path
for r, substitution := range urlSubstitions {
if r.MatchString(path) {
path = r.ReplaceAllString(path, substitution)
}
}
if origPath != path {
log.Tracef("URL Replacement transformed %s to %s", origPath, path)
}
reqURL.Path = path
reqURL.RawQuery = query
var bodyBuf []byte
if payload != nil {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(payload)
if err != nil {
log.Warnf("Error reading payload, %s", err)
}
bodyBuf = buf.Bytes()
payload = bytes.NewReader(bodyBuf)
}
req, err := http.NewRequest(method, reqURL.String(), payload)
if err != nil {
return nil, err
}
warnOnNoAuthentication := len(headergroups.GetAllHeaderGroups()) == 0
bearerToken, err := authentication.GetAuthenticationToken(true, nil, warnOnNoAuthentication)
if err != nil {
return nil, err
}
if bearerToken != nil {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken.AccessToken))
}
customerToken := authentication.GetCustomerToken()
if customerToken != nil {
req.Header.Add("X-Moltin-Customer-Token", customerToken.Data.Token)
}
accountManagementAuthenticationToken := authentication.GetAccountManagementAuthenticationToken()
if accountManagementAuthenticationToken != nil {
req.Header.Add("EP-Account-Management-Authentication-Token", accountManagementAuthenticationToken.Token)
}
req.Header.Add("Content-Type", contentType)
req.Header.Add("User-Agent", UserAgent)
if len(env.EPCC_BETA_API_FEATURES) > 0 {
req.Header.Add("EP-Beta-Features", env.EPCC_BETA_API_FEATURES)
}
if err = AddAdditionalHeadersSpecifiedByFlag(req); err != nil {
return nil, err
}
for k, v := range headergroups.GetAllHeaders() {
req.Header.Add(k, v)
}
dumpReq, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Error(err)
}
start := time.Now()
log.Tracef("Waiting for rate limiter")
if err := Limit.Wait(ctx); err != nil {
return nil, fmt.Errorf("rate limiter returned error %v, %w", err, err)
}
rateLimitTime := time.Since(start)
log.Tracef("Rate limiter allowed call, making HTTP Request")
resp, err := HttpClient.Do(req)
requestTime := time.Since(start)
log.Tracef("HTTP Request complete, waiting for stats lock")
statsLock.Lock()
// Lock is not deferred (for perf reasons), so don't
// forget to unlock it, if you return before it is so.
stats.totalRequests += 1
if rateLimitTime.Milliseconds() > 50 {
// Only count rate limit time if it took us longer than 50 ms to get here.
stats.totalRateLimitedTimeInMs += rateLimitTime.Milliseconds()
}
stats.totalHttpRequestProcessingTime += requestTime.Milliseconds() - rateLimitTime.Milliseconds()
if resp != nil {
stats.respCodes[resp.StatusCode] = stats.respCodes[resp.StatusCode] + 1
} else {
stats.respCodes[0] = stats.respCodes[0] + 1
}
requestNumber := stats.totalRequests
statsLock.Unlock()
log.Tracef("Stats processing complete")
requestError := err
if requestError != nil {
resp = &http.Response{
Status: "CONNECTION_ERROR",
StatusCode: 0,
Proto: "",
ProtoMajor: 0,
ProtoMinor: 0,
Header: map[string][]string{},
Body: io.NopCloser(strings.NewReader(fmt.Sprintf("%v", err))),
ContentLength: 0,
TransferEncoding: nil,
Close: true,
Uncompressed: false,
Trailer: nil,
Request: nil,
TLS: nil,
}
}
var logf func(string, ...interface{})
if resp.StatusCode >= 400 {
logf = func(a string, b ...interface{}) {
log.Warnf(a, b...)
}
} else if log.IsLevelEnabled(log.DebugLevel) {
logf = func(a string, b ...interface{}) {
log.Debugf(a, b...)
}
} else {
logf = func(a string, b ...interface{}) {
// Do nothing
}
}
requestHeaders := ""
responseHeaders := ""
if log.IsLevelEnabled(log.DebugLevel) {
for k, v := range req.Header {
requestHeaders += "\n" + k + ":" + strings.Join(v, ", ")
}
requestHeaders += "\n"
}
if log.IsLevelEnabled(log.DebugLevel) {
for k, v := range resp.Header {
responseHeaders += "\n" + k + ":" + strings.Join(v, ", ")
}
requestHeaders += "\n\n"
}
displayLongFormRequestAndResponse := resp.StatusCode >= 400
if resp.StatusCode == 429 && Retry429 {
displayLongFormRequestAndResponse = false
}
if resp.StatusCode >= 500 && Retry5xx {
displayLongFormRequestAndResponse = false
}
displayLongFormRequestAndResponse = displayLongFormRequestAndResponse || log.IsLevelEnabled(log.DebugLevel)
if displayLongFormRequestAndResponse {
if payload != nil {
body := bodyBuf
if len(body) > 0 {
logf("(%0.4d) %s %s%s", requestNumber, method, reqURL.String(), requestHeaders)
if contentType == "application/json" {
json.PrintJsonToStderr(string(body))
} else {
logf("%s", body)
}
logf("%s %s%s", resp.Proto, resp.Status, responseHeaders)
} else {
logf("(%0.4d) %s %s%s ==> %s %s%s", requestNumber, req.Method, getUrl(reqURL), requestHeaders, resp.Proto, resp.Status, responseHeaders)
}
} else {
logf("(%0.4d) %s %s%s ==> %s %s%s", requestNumber, req.Method, getUrl(reqURL), requestHeaders, resp.Proto, resp.Status, responseHeaders)
}
} else {
if resp.StatusCode >= 300 || !DontLog2xxs {
log.Infof("(%0.4d) %s %s ==> %s %s", requestNumber, method, getUrl(reqURL), resp.Proto, resp.Status)
}
}
dumpRes, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Error(err)
}
log.Tracef("Starting log to disk")
profiles.LogRequestToDisk(method, path, dumpReq, dumpRes, resp.StatusCode)
log.Tracef("Done log to disk")
if resp.StatusCode == 429 && (Retry429 || RetryAllErrors) {
if RetryDelay > 0 {
log.Debugf("Retrying request in %d ms", RetryDelay)
time.Sleep(time.Duration(RetryDelay) * time.Millisecond)
}
return doRequestInternal(ctx, method, contentType, path, query, bytes.NewReader(bodyBuf))
} else if resp.StatusCode >= 500 && (Retry5xx || RetryAllErrors) {
if RetryDelay > 0 {
log.Debugf("Retrying request in %d ms", RetryDelay)
time.Sleep(time.Duration(RetryDelay) * time.Millisecond)
}
return doRequestInternal(ctx, method, contentType, path, query, bytes.NewReader(bodyBuf))
} else if requestError != nil && (RetryConnectionErrors || RetryAllErrors) {
if RetryDelay > 0 {
log.Debugf("Retrying request in %d ms", RetryDelay)
time.Sleep(time.Duration(RetryDelay) * time.Millisecond)
}
return doRequestInternal(ctx, method, contentType, path, query, bytes.NewReader(bodyBuf))
} else {
return resp, err
}
}
func getUrl(u *url.URL) string {
query, _ := url.PathUnescape(u.String())
return query
//query, _ := url.PathUnescape(u.RawQuery)
//return fmt.Sprintf("%s://%s/%s?%s", u.Scheme, u.Host, u.Path, query)
}
func AddAdditionalHeadersSpecifiedByFlag(r *http.Request) error {
for _, header := range RawHeaders {
// Validation and formatting logic for headers could be improved
entries := strings.Split(header, ":")
if len(entries) < 2 {
return fmt.Errorf("header has invalid format")
}
r.Header.Set(entries[0], entries[1])
}
for key, val := range httpHeaders {
r.Header.Set(key, val)
}
return nil
}