-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
459 lines (395 loc) · 11.6 KB
/
main.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
// Copyright 2016 Circonus, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build go1.17
// +build go1.17
package apiclient
import (
"bytes"
"context"
crand "crypto/rand"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"math"
"math/big"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
retryablehttp "github.com/hashicorp/go-retryablehttp"
"github.com/pkg/errors"
)
var rnd *rand.Rand
func init() {
n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
rnd = rand.New(rand.NewSource(time.Now().UTC().UnixNano())) //nolint:gosec //G404
return
}
rand.New(rand.NewSource(n.Int64())) //nolint:gosec //G404
}
const (
// a few sensible defaults
defaultAPIURL = "https://api.circonus.com/v2"
defaultAPIApp = "circonus-goapiclient"
minRetryWait = 1 * time.Second
maxRetryWait = 15 * time.Second
maxRetries = 4 // equating to 1 + maxRetries total attempts
)
// Logger facilitates use of any logger supporting the required methods
// rather than just standard log package log.Logger
type Logger interface {
Printf(string, ...interface{})
}
// TokenKeyType - Circonus API Token key
type TokenKeyType string
// TokenAppType - Circonus API Token app name
type TokenAppType string
// TokenAccountIDType - Circonus API Token account id
type TokenAccountIDType string
// CIDType Circonus object cid
type CIDType *string
// IDType Circonus object id
type IDType int
// URLType submission url type
type URLType string
// SearchQueryType search query (see: https://login.circonus.com/resources/api#searching)
type SearchQueryType string
// SearchFilterType search filter (see: https://login.circonus.com/resources/api#filtering)
type SearchFilterType map[string][]string
// TagType search/select/custom tag(s) type
type TagType []string
// Config options for Circonus API
type Config struct {
Log Logger
// TLSConfig defines a custom tls configuration to use when communicating with the API
TLSConfig *tls.Config
// CACert deprecating, use TLSConfig instead
CACert *x509.CertPool
// URL defines the API URL - default https://api.circonus.com/v2/
URL string
// TokenKey defines the key to use when communicating with the API
TokenKey string
// TokenApp defines the app to use when communicating with the API
TokenApp string
TokenAccountID string
MinRetryDelay string
MaxRetryDelay string
MaxRetries uint
DisableRetries bool
Debug bool
}
// API Circonus API
type API struct {
Log Logger
caCert *x509.CertPool
tlsConfig *tls.Config
apiURL *url.URL
key TokenKeyType
app TokenAppType
accountID TokenAccountIDType
minRetryDelay time.Duration
maxRetryDelay time.Duration
maxRetries uint
useExponentialBackoff bool
Debug bool
useExponentialBackoffmu sync.Mutex
}
// NewClient returns a new Circonus API (alias for New)
func NewClient(ac *Config) (*API, error) {
return New(ac)
}
// NewAPI returns a new Circonus API (alias for New)
func NewAPI(ac *Config) (*API, error) {
return New(ac)
}
// New returns a new Circonus API
func New(ac *Config) (*API, error) {
if ac == nil {
return nil, errors.New("invalid Circonus API configuration (nil)")
}
key := TokenKeyType(ac.TokenKey)
if key == "" {
return nil, errors.New("Circonus API Token is required")
}
app := TokenAppType(ac.TokenApp)
if app == "" {
app = defaultAPIApp
}
acctID := TokenAccountIDType(ac.TokenAccountID)
au := ac.URL
if au == "" {
au = defaultAPIURL
}
if !strings.Contains(au, "/") {
// if just a hostname is passed, ASSume "https" and a path prefix of "/v2"
au = fmt.Sprintf("https://%s/v2", ac.URL)
}
if last := len(au) - 1; last >= 0 && au[last] == '/' {
// strip off trailing '/'
au = au[:last]
}
apiURL, err := url.Parse(au)
if err != nil {
return nil, errors.Wrap(err, "parsing Circonus API URL")
}
a := &API{
apiURL: apiURL,
key: key,
app: app,
accountID: acctID,
caCert: ac.CACert,
tlsConfig: ac.TLSConfig,
Debug: ac.Debug,
Log: ac.Log,
useExponentialBackoff: false,
}
a.Debug = ac.Debug
a.Log = ac.Log
if a.Debug && a.Log == nil {
a.Log = log.New(os.Stdout, "", log.LstdFlags)
}
if a.Log == nil {
a.Log = log.New(io.Discard, "", log.LstdFlags)
}
a.maxRetries = maxRetries
if ac.MaxRetries > 0 {
a.maxRetries = ac.MaxRetries
}
if ac.DisableRetries {
a.maxRetries = 0
}
a.minRetryDelay = minRetryWait
if ac.MinRetryDelay != "" {
mr, err := time.ParseDuration(ac.MinRetryDelay)
if err != nil {
a.Log.Printf("[ERR] min retry delay (%s): %s", ac.MinRetryDelay, err)
}
a.minRetryDelay = mr
}
a.maxRetryDelay = maxRetryWait
if ac.MaxRetryDelay != "" {
mr, err := time.ParseDuration(ac.MaxRetryDelay)
if err != nil {
a.Log.Printf("[ERR] max retry delay (%s): %s", ac.MaxRetryDelay, err)
}
a.maxRetryDelay = mr
}
return a, nil
}
// EnableExponentialBackoff enables use of exponential backoff for next API call(s)
// and use exponential backoff for all API calls until exponential backoff is disabled.
func (a *API) EnableExponentialBackoff() {
a.useExponentialBackoffmu.Lock()
a.useExponentialBackoff = true
a.useExponentialBackoffmu.Unlock()
}
// DisableExponentialBackoff disables use of exponential backoff. If a request using
// exponential backoff is currently running, it will stop using exponential backoff
// on its next iteration (if needed).
func (a *API) DisableExponentialBackoff() {
a.useExponentialBackoffmu.Lock()
a.useExponentialBackoff = false
a.useExponentialBackoffmu.Unlock()
}
// Get API request
func (a *API) Get(reqPath string) ([]byte, error) {
return a.apiRequest("GET", reqPath, nil)
}
// Delete API request
func (a *API) Delete(reqPath string) ([]byte, error) {
return a.apiRequest("DELETE", reqPath, nil)
}
// Post API request
func (a *API) Post(reqPath string, data []byte) ([]byte, error) {
return a.apiRequest("POST", reqPath, data)
}
// Put API request
func (a *API) Put(reqPath string, data []byte) ([]byte, error) {
return a.apiRequest("PUT", reqPath, data)
}
func backoff(interval uint) float64 {
return math.Floor(((float64(interval) * (1 + rnd.Float64())) / 2) + .5) //nolint:gosec
}
// apiRequest manages retry strategy for exponential backoffs
func (a *API) apiRequest(reqMethod string, reqPath string, data []byte) ([]byte, error) {
backoffs := []uint{2, 4, 8, 16, 32}
attempts := 0
success := false
var result []byte
var err error
for !success {
result, err = a.apiCall(reqMethod, reqPath, data)
if err == nil {
success = true
}
// break and return error if not using exponential backoff
if err != nil {
if !a.useExponentialBackoff {
break
}
if strings.Contains(err.Error(), "code 400") {
break
}
if strings.Contains(err.Error(), "code 403") {
break
}
if strings.Contains(err.Error(), "code 404") {
break
}
}
if !success {
var wait float64
if attempts >= len(backoffs) {
wait = backoff(backoffs[len(backoffs)-1])
} else {
wait = backoff(backoffs[attempts])
}
attempts++
a.Log.Printf("Circonus API call failed %s, retrying in %d seconds.\n", err.Error(), uint(wait))
time.Sleep(time.Duration(wait) * time.Second)
}
}
return result, err
}
// apiCall call Circonus API
func (a *API) apiCall(reqMethod string, reqPath string, data []byte) ([]byte, error) {
reqURL := a.apiURL.String()
if reqPath == "" {
return nil, errors.New("invalid Circonus API URL path (empty)")
}
if reqPath[:1] != "/" {
reqURL += "/"
}
if len(reqPath) >= 3 && reqPath[:3] == "/v2" {
reqURL += reqPath[3:]
} else {
reqURL += reqPath
}
// keep last HTTP error in the event of retry failure
var lastHTTPError error
retryPolicy := func(ctx context.Context, resp *http.Response, err error) (bool, error) {
if ctxErr := ctx.Err(); ctxErr != nil {
return false, errors.Wrap(ctxErr, "Circonus API call")
}
if err != nil {
lastHTTPError = err
return true, errors.Wrap(err, "Circonus API call")
}
// Check the response code. We retry on 500-range responses to allow
// the server time to recover, as 500's are typically not permanent
// errors and may relate to outages on the server side. This will catch
// invalid response codes as well, like 0 and 999.
// Retry on 429 (rate limit) as well.
if resp.StatusCode == 0 || // wtf?!
resp.StatusCode >= 500 || // rutroh
resp.StatusCode == 429 { // rate limit
body, readErr := io.ReadAll(resp.Body)
if readErr != nil {
lastHTTPError = errors.Errorf("- response: %d %s", resp.StatusCode, readErr.Error())
} else {
lastHTTPError = errors.Errorf("- response: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return true, nil
}
return false, nil
}
if len(data) > 0 {
a.Log.Printf("[DEBUG] sending json (%s)\n", string(data))
}
dataReader := bytes.NewReader(data)
req, err := retryablehttp.NewRequest(reqMethod, reqURL, dataReader)
if err != nil {
return nil, errors.Errorf("creating Circonus API request: %s %+v", reqURL, err)
}
req.Header.Add("Accept", "application/json")
req.Header.Add("X-Circonus-Auth-Token", string(a.key))
req.Header.Add("X-Circonus-App-Name", string(a.app))
if string(a.accountID) != "" {
req.Header.Add("X-Circonus-Account-ID", string(a.accountID))
}
req.Header.Add("Cache-Control", "no-store")
client := retryablehttp.NewClient()
if a.apiURL.Scheme == "https" {
var tlscfg *tls.Config
if a.tlsConfig != nil { // preference full custom tls config
tlscfg = a.tlsConfig
} else if a.caCert != nil {
tlscfg = &tls.Config{
RootCAs: a.caCert,
MinVersion: tls.VersionTLS12,
}
}
client.HTTPClient.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
TLSClientConfig: tlscfg,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1,
DisableCompression: true,
}
} else {
client.HTTPClient.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
DisableKeepAlives: true,
MaxIdleConnsPerHost: -1,
DisableCompression: true,
}
}
a.useExponentialBackoffmu.Lock()
eb := a.useExponentialBackoff
a.useExponentialBackoffmu.Unlock()
if eb {
// limit to one request if using exponential backoff
client.RetryWaitMin = 1 * time.Second
client.RetryWaitMax = 60 * time.Second
client.RetryMax = 0
} else {
client.RetryWaitMin = a.minRetryDelay
client.RetryWaitMax = a.maxRetryDelay
client.RetryMax = int(a.maxRetries)
}
// retryablehttp only groks log or no log
if a.Debug {
client.Logger = a.Log
} else {
client.Logger = log.New(io.Discard, "", log.LstdFlags)
}
client.CheckRetry = retryPolicy
resp, err := client.Do(req)
if err != nil {
if lastHTTPError != nil {
return nil, lastHTTPError
}
return nil, errors.Errorf("Circonus API call - %s: %+v", reqURL, err)
}
defer resp.Body.Close() // nolint: errcheck
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "reading Circonus API response")
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
msg := fmt.Sprintf("API response code %d: %s", resp.StatusCode, string(body))
if a.Debug {
a.Log.Printf("%s\n", msg)
}
return nil, errors.New(msg)
}
return body, nil
}