terraform/vendor/github.com/circonus-labs/circonus-gometrics/api/api.go

372 lines
8.9 KiB
Go
Raw Normal View History

Circonus Provider (#12338) * Begin stubbing out the Circonus provider. * Remove all references to `reverse:secret_key`. This value is dynamically set by the service and unused by Terraform. * Update the `circonus_check` resource. Still a WIP. * Add docs for the `circonus_check` resource. Commit miss, this should have been included in the last commit. * "Fix" serializing check tags I still need to figure out how I can make them order agnostic w/o using a TypeSet. I'm worried that's what I'm going to have to do. * Spike a quick circonus_broker data source. * Convert tags to a Set so the order does not matter. * Add a `circonus_account` data source. * Correctly spell account. Pointed out by: @postwait * Add the `circonus_contact_group` resource. * Push descriptions into their own file in order to reduce the busyness of the schema when reviewing code. * Rename `circonus_broker` and `broker` to `circonus_collector` and `collector`, respectively. Change made with concent by Circonus to reduce confusion (@postwait, @maier, and several others). * Use upstream contsants where available. * Import the latest circonus-gometrics. * Move to using a Set of collectors vs a list attached to a single attribute. * Rename "cid" to "id" in the circonus_account data source and elsewhere where possible. * Inject a tag automatically. Update gometrics. * Checkpoint `circonus_metric` resource. * Enable provider-level auto-tagging. This is disabled by default. * Rearrange metric. This is an experimental "style" of a provider. We'll see. That moment. When you think you've gone off the rails on a mad scientist experiment but like the outcome and think you may be onto something but haven't proven it to yourself or anyone else yet? That. That exact feeling of semi-confidence while being alone in the wilderness. Please let this not be the Terraform provider equivalent of DJB's C style of coding. We'll know in another resource or two if this was a horrible mistake or not. * Begin moving `resource_circonus_check` over to the new world order/structure: Much of this is WIP and incomplete, but here is the new supported structure: ``` variable "used_metric_name" { default = "_usage`0`_used" } resource "circonus_check" "usage" { # collectors = ["${var.collectors}"] collector { id = "${var.collectors[0]}" } name = "${var.check_name}" notes = "${var.notes}" json { url = "https://${var.target}/account/current" http_headers = { "Accept" = "application/json" "X-Circonus-App-Name" = "TerraformCheck" "X-Circonus-Auth-Token" = "${var.api_token}" } } stream { name = "${circonus_metric.used.name}" tags = "${circonus_metric.used.tags}" type = "${circonus_metric.used.type}" } tags = { source = "circonus" } } resource "circonus_metric" "used" { name = "${var.used_metric_name}" tags = { source = "circonus" } type = "numeric" } ``` * Document the `circonus_metric` resource. * Updated `circonus_check` docs. * If a port was present, automatically set it in the Config. * Alpha sort the check parameters now that they've been renamed. * Fix a handful of panics as a result of the schema changing. * Move back to a `TypeSet` for tags. After a stint with `TypeMap`, move back to `TypeSet`. A set of strings seems to match the API the best. The `map` type was convenient because it reduced the amount of boilerplate, but you loose out on other things. For instance, tags come in the form of `category:value`, so naturally it seems like you could use a map, but you can't without severe loss of functionality because assigning two values to the same category is common. And you can't normalize map input or suppress the output correctly (this was eventually what broke the camel's back). I tried an experiment of normalizing the input to be `category:value` as the key in the map and a value of `""`, but... seee diff suppress. In this case, simple is good. While here bring some cleanups to _Metric since that was my initial testing target. * Rename `providerConfig` to `_ProviderConfig` * Checkpoint the `json` check type. * Fix a few residual issues re: missing descriptions. * Rename `validateRegexp` to `_ValidateRegexp` * Use tags as real sets, not just a slice of strings. * Move the DiffSuppressFunc for tags down to the Elem. * Fix up unit tests to chase the updated, default hasher function being used. * Remove `Computed` attribute from `TypeSet` objects. This fixes a pile of issues re: update that I was having. * Rename functions. `GetStringOk` -> `GetStringOK` `GetSetAsListOk` -> `GetSetAsListOK` `GetIntOk` -> `GetIntOK` * Various small cleanups and comments rolled into a single commit. * Add a `postgresql` check type for the `circonus_check` resource. * Rename various validator functions to be _CapitalCase vs capitalCase. * Err... finish the validator renames. * Add `GetFloat64()` support. * Add `icmp_ping` check type support. * Catch up to the _API*Attr renames. Deliberately left out of the previous commit in order to create a clean example of what is required to add a new check type to the `circonus_check` resource. * Clarify when the `target` attribute is required for the `postgresql` check type. * Correctly pull the metric ID attribute from the right location. * Add a circonus_stream_group resource (a.k.a. a Circonus "metric cluster") * Add support for the [`caql`](https://login.circonus.com/user/docs/caql_reference) check type. * Add support for the `http` check type. * `s/SSL/TLS/g` * Add support for `tcp` check types. * Enumerate the available metrics that are supported for each check type. * Add [`cloudwatch`](https://login.circonus.com/user/docs/Data/CheckTypes/CloudWatch) check type support. * Add a `circonus_trigger` resource (a.k.a Circonus Ruleset). * Rename a handful of functions to make it clear in the function name the direction of flow for information moving through the provider. TL;DR: Replace `parse` and `read` with "foo to bar"-like names. * Fix the attribute name used in a validator. Absent != After. * Set the minimum `absent` predicate to 70s per testing. * Fix the regression tests for circonus_trigger now that absent has a 70s min * Fix up the `tcp` check to require a `host` attribute. Fix tests. It's clear I didn't run these before committing/pushing the `tcp` check last time. * Fix `circonus_check` for `cloudwatch` checks. * Rename `parsePerCheckTypeConfig()` to `_CheckConfigToAPI` to be consistent with other function names. grep(1)ability of code++ * Slack buttons as an integer are string encoded. * Fix updates for `circonus_contact`. * Fix the out parameters for contact groups. * Move to using `_CastSchemaToTF()` where appropriate. * Fix circonus_contact_group. Updates work as expected now. * Use `_StateSet()` in place of `d.Set()` everywhere. * Make a quick pass over the collector datasource to modernize its style * Quick pass for items identified by `golint`. * Fix up collectors * Fix the `json` check type. Reconcile possible sources of drift. Update now works as expected. * Normalize trigger durations to seconds. * Improve the robustness of the state handling for the `circonus_contact_group` resource. * I'm torn on this, but sort the contact groups in the notify list. This does mean that if the first contact group in the list has a higher lexical sort order the plan won't converge until the offending resource is tainted and recreated. But there's also some sorting happening elsewhere, so.... sort and taint for now and this will need to be revisited in the future. * Add support for the `httptrap` check type. * Remove empty units from the state file. * Metric clusters can return a 404. Detect this accordingly in its respective Exists handler. * Add a `circonus_graph` resource. * Fix a handful of bugs in the graph provider. * Re-enable the necessary `ConflictsWith` definitions and normalize attribute names. * Objects that have been deleted via the UI return a 404. Handle in Exists(). * Teach `circonus_graph`'s Stack set to accept nil values. * Set `ForceNew: true` for a graph's name. * Chase various API fixes required to make `circonus_graph` work as expected. * Fix up the handling of sub-1 zoom resolutions for graphs. * Add the `check_by_collector` out parameter to the `circonus_check` resource. * Improve validation of line vs area graphs. Fix graph_style. * Fix up the `logarithmic` graph axis option. * Resolve various trivial `go vet` issues. * Add a stream_group out parameter. * Remove incorrectly applied `Optional` attributes to the `circonus_account` resource. * Remove various `Optional` attributes from the `circonus_collector` data source. * Centralize the common need to suppress leading and trailing whitespace into `suppressWhitespace`. * Sync up with upstream vendor fixes for circonus_graph. * Update the checksum value for the http check. * Chase `circonus_graph`'s underlying `line_style` API object change from `string` to `*string`. * Clean up tests to use a generic terraform regression testing account. * Add support for the MySQL to the `circonus_check` resource. * Begin stubbing out the Circonus provider. * Remove all references to `reverse:secret_key`. This value is dynamically set by the service and unused by Terraform. * Update the `circonus_check` resource. Still a WIP. * Add docs for the `circonus_check` resource. Commit miss, this should have been included in the last commit. * "Fix" serializing check tags I still need to figure out how I can make them order agnostic w/o using a TypeSet. I'm worried that's what I'm going to have to do. * Spike a quick circonus_broker data source. * Convert tags to a Set so the order does not matter. * Add a `circonus_account` data source. * Correctly spell account. Pointed out by: @postwait * Add the `circonus_contact_group` resource. * Push descriptions into their own file in order to reduce the busyness of the schema when reviewing code. * Rename `circonus_broker` and `broker` to `circonus_collector` and `collector`, respectively. Change made with concent by Circonus to reduce confusion (@postwait, @maier, and several others). * Use upstream contsants where available. * Import the latest circonus-gometrics. * Move to using a Set of collectors vs a list attached to a single attribute. * Rename "cid" to "id" in the circonus_account data source and elsewhere where possible. * Inject a tag automatically. Update gometrics. * Checkpoint `circonus_metric` resource. * Enable provider-level auto-tagging. This is disabled by default. * Rearrange metric. This is an experimental "style" of a provider. We'll see. That moment. When you think you've gone off the rails on a mad scientist experiment but like the outcome and think you may be onto something but haven't proven it to yourself or anyone else yet? That. That exact feeling of semi-confidence while being alone in the wilderness. Please let this not be the Terraform provider equivalent of DJB's C style of coding. We'll know in another resource or two if this was a horrible mistake or not. * Begin moving `resource_circonus_check` over to the new world order/structure: Much of this is WIP and incomplete, but here is the new supported structure: ``` variable "used_metric_name" { default = "_usage`0`_used" } resource "circonus_check" "usage" { # collectors = ["${var.collectors}"] collector { id = "${var.collectors[0]}" } name = "${var.check_name}" notes = "${var.notes}" json { url = "https://${var.target}/account/current" http_headers = { "Accept" = "application/json" "X-Circonus-App-Name" = "TerraformCheck" "X-Circonus-Auth-Token" = "${var.api_token}" } } stream { name = "${circonus_metric.used.name}" tags = "${circonus_metric.used.tags}" type = "${circonus_metric.used.type}" } tags = { source = "circonus" } } resource "circonus_metric" "used" { name = "${var.used_metric_name}" tags = { source = "circonus" } type = "numeric" } ``` * Document the `circonus_metric` resource. * Updated `circonus_check` docs. * If a port was present, automatically set it in the Config. * Alpha sort the check parameters now that they've been renamed. * Fix a handful of panics as a result of the schema changing. * Move back to a `TypeSet` for tags. After a stint with `TypeMap`, move back to `TypeSet`. A set of strings seems to match the API the best. The `map` type was convenient because it reduced the amount of boilerplate, but you loose out on other things. For instance, tags come in the form of `category:value`, so naturally it seems like you could use a map, but you can't without severe loss of functionality because assigning two values to the same category is common. And you can't normalize map input or suppress the output correctly (this was eventually what broke the camel's back). I tried an experiment of normalizing the input to be `category:value` as the key in the map and a value of `""`, but... seee diff suppress. In this case, simple is good. While here bring some cleanups to _Metric since that was my initial testing target. * Rename `providerConfig` to `_ProviderConfig` * Checkpoint the `json` check type. * Fix a few residual issues re: missing descriptions. * Rename `validateRegexp` to `_ValidateRegexp` * Use tags as real sets, not just a slice of strings. * Move the DiffSuppressFunc for tags down to the Elem. * Fix up unit tests to chase the updated, default hasher function being used. * Remove `Computed` attribute from `TypeSet` objects. This fixes a pile of issues re: update that I was having. * Rename functions. `GetStringOk` -> `GetStringOK` `GetSetAsListOk` -> `GetSetAsListOK` `GetIntOk` -> `GetIntOK` * Various small cleanups and comments rolled into a single commit. * Add a `postgresql` check type for the `circonus_check` resource. * Rename various validator functions to be _CapitalCase vs capitalCase. * Err... finish the validator renames. * Add `GetFloat64()` support. * Add `icmp_ping` check type support. * Catch up to the _API*Attr renames. Deliberately left out of the previous commit in order to create a clean example of what is required to add a new check type to the `circonus_check` resource. * Clarify when the `target` attribute is required for the `postgresql` check type. * Correctly pull the metric ID attribute from the right location. * Add a circonus_stream_group resource (a.k.a. a Circonus "metric cluster") * Add support for the [`caql`](https://login.circonus.com/user/docs/caql_reference) check type. * Add support for the `http` check type. * `s/SSL/TLS/g` * Add support for `tcp` check types. * Enumerate the available metrics that are supported for each check type. * Add [`cloudwatch`](https://login.circonus.com/user/docs/Data/CheckTypes/CloudWatch) check type support. * Add a `circonus_trigger` resource (a.k.a Circonus Ruleset). * Rename a handful of functions to make it clear in the function name the direction of flow for information moving through the provider. TL;DR: Replace `parse` and `read` with "foo to bar"-like names. * Fix the attribute name used in a validator. Absent != After. * Set the minimum `absent` predicate to 70s per testing. * Fix the regression tests for circonus_trigger now that absent has a 70s min * Fix up the `tcp` check to require a `host` attribute. Fix tests. It's clear I didn't run these before committing/pushing the `tcp` check last time. * Fix `circonus_check` for `cloudwatch` checks. * Rename `parsePerCheckTypeConfig()` to `_CheckConfigToAPI` to be consistent with other function names. grep(1)ability of code++ * Slack buttons as an integer are string encoded. * Fix updates for `circonus_contact`. * Fix the out parameters for contact groups. * Move to using `_CastSchemaToTF()` where appropriate. * Fix circonus_contact_group. Updates work as expected now. * Use `_StateSet()` in place of `d.Set()` everywhere. * Make a quick pass over the collector datasource to modernize its style * Quick pass for items identified by `golint`. * Fix up collectors * Fix the `json` check type. Reconcile possible sources of drift. Update now works as expected. * Normalize trigger durations to seconds. * Improve the robustness of the state handling for the `circonus_contact_group` resource. * I'm torn on this, but sort the contact groups in the notify list. This does mean that if the first contact group in the list has a higher lexical sort order the plan won't converge until the offending resource is tainted and recreated. But there's also some sorting happening elsewhere, so.... sort and taint for now and this will need to be revisited in the future. * Add support for the `httptrap` check type. * Remove empty units from the state file. * Metric clusters can return a 404. Detect this accordingly in its respective Exists handler. * Add a `circonus_graph` resource. * Fix a handful of bugs in the graph provider. * Re-enable the necessary `ConflictsWith` definitions and normalize attribute names. * Objects that have been deleted via the UI return a 404. Handle in Exists(). * Teach `circonus_graph`'s Stack set to accept nil values. * Set `ForceNew: true` for a graph's name. * Chase various API fixes required to make `circonus_graph` work as expected. * Fix up the handling of sub-1 zoom resolutions for graphs. * Add the `check_by_collector` out parameter to the `circonus_check` resource. * Improve validation of line vs area graphs. Fix graph_style. * Fix up the `logarithmic` graph axis option. * Resolve various trivial `go vet` issues. * Add a stream_group out parameter. * Remove incorrectly applied `Optional` attributes to the `circonus_account` resource. * Remove various `Optional` attributes from the `circonus_collector` data source. * Centralize the common need to suppress leading and trailing whitespace into `suppressWhitespace`. * Sync up with upstream vendor fixes for circonus_graph. * Update the checksum value for the http check. * Chase `circonus_graph`'s underlying `line_style` API object change from `string` to `*string`. * Clean up tests to use a generic terraform regression testing account. * Rename all identifiers that began with a `_` and replace with a corresponding lowercase glyph. * Remove stale comment in types. * Move the calls to `ResourceData`'s `SetId()` calls to be first in the list so that no resources are lost in the event of a `panic()`. * Remove `stateSet` from the `circonus_trigger` resource. * Remove `stateSet` from the `circonus_stream_group` resource. * Remove `schemaSet` from the `circonus_graph` resource. * Remove `stateSet` from the `circonus_contact` resource. * Remove `stateSet` from the `circonus_metric` resource. * Remove `stateSet` from the `circonus_account` data source. * Remove `stateSet` from the `circonus_collector` data source. * Remove stray `stateSet` call from the `circonus_contact` resource. This is an odd artifact to find... I'm completely unsure as to why it was there to begin with but am mostly certain it's a bug and needs to be removed. * Remove `stateSet` from the `circonus_check` resource. * Remove the `stateSet` helper function. All call sites have been converted to return errors vs `panic()`'ing at runtime. * Remove a pile of unused functions and type definitions. * Remove the last of the `attrReader` interface. * Remove an unused `Sprintf` call. * Update `circonus-gometrics` and remove unused files. * Document what `convertToHelperSchema()` does. Rename `castSchemaToTF` to `convertToHelperSchema`. Change the function parameter ordering so the `map` of attribute descriptions: this is much easier to maintain when the description map is first when creating schema inline. * Move descriptions into their respective source files. * Remove all instances of `panic()`. In the case of software bugs, log an error. Never `panic()` and always return a value. * Rename `stream_group` to `metric_cluster`. * Rename triggers to rule sets * Rename `stream` to `metric`. * Chase the `stream` -> `metric` change into the docs. * Remove some unused test functions. * Add the now required `color` attribute for graphing a `metric_cluster`. * Add a missing description to silence a warning. * Add `id` as a selector for the account data source. * Futureproof testing: Randomize all asset names to prevent any possible resource conflicts. This isn't a necessary change for our current build and regression testing, but *just in case* we have a radical change to our testing framework in the future, make all resource names fully random. * Rename various values to match the Circonus docs. * s/alarm/alert/g * Ensure ruleset criteria can not be empty.
2017-03-10 21:19:17 +01:00
// 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.
package api
import (
"bytes"
crand "crypto/rand"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/hashicorp/go-retryablehttp"
)
func init() {
n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
rand.Seed(time.Now().UTC().UnixNano())
return
}
rand.Seed(n.Int64())
}
const (
// a few sensible defaults
defaultAPIURL = "https://api.circonus.com/v2"
defaultAPIApp = "circonus-gometrics"
minRetryWait = 1 * time.Second
maxRetryWait = 15 * time.Second
maxRetries = 4 // equating to 1 + maxRetries total attempts
)
// TokenKeyType - Circonus API Token key
type TokenKeyType string
// TokenAppType - Circonus API Token app name
type TokenAppType 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 {
URL string
TokenKey string
TokenApp string
CACert *x509.CertPool
Log *log.Logger
Debug bool
}
// API Circonus API
type API struct {
apiURL *url.URL
key TokenKeyType
app TokenAppType
caCert *x509.CertPool
Debug bool
Log *log.Logger
useExponentialBackoff 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 API configuration (nil)")
}
key := TokenKeyType(ac.TokenKey)
if key == "" {
return nil, errors.New("API Token is required")
}
app := TokenAppType(ac.TokenApp)
if app == "" {
app = defaultAPIApp
}
au := string(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, err
}
a := &API{
apiURL: apiURL,
key: key,
app: app,
caCert: ac.CACert,
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.Stderr, "", log.LstdFlags)
}
if a.Log == nil {
a.Log = log.New(ioutil.Discard, "", log.LstdFlags)
}
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 + rand.Float64())) / 2) + .5)
}
// 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 matched, _ := regexp.MatchString("code 403", err.Error()); matched {
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("[WARN] 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 URL path")
}
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(resp *http.Response, err error) (bool, error) {
if err != nil {
lastHTTPError = err
return true, err
}
// 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 := ioutil.ReadAll(resp.Body)
if readErr != nil {
lastHTTPError = fmt.Errorf("- response: %d %s", resp.StatusCode, readErr.Error())
} else {
lastHTTPError = fmt.Errorf("- response: %d %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return true, nil
}
return false, nil
}
dataReader := bytes.NewReader(data)
req, err := retryablehttp.NewRequest(reqMethod, reqURL, dataReader)
if err != nil {
return nil, fmt.Errorf("[ERROR] creating 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))
client := retryablehttp.NewClient()
if a.apiURL.Scheme == "https" && a.caCert != nil {
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: &tls.Config{RootCAs: a.caCert},
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
client.RetryWaitMax = 2
client.RetryMax = 0
} else {
client.RetryWaitMin = minRetryWait
client.RetryWaitMax = maxRetryWait
client.RetryMax = maxRetries
}
// retryablehttp only groks log or no log
if a.Debug {
client.Logger = a.Log
} else {
client.Logger = log.New(ioutil.Discard, "", log.LstdFlags)
}
client.CheckRetry = retryPolicy
resp, err := client.Do(req)
if err != nil {
if lastHTTPError != nil {
return nil, lastHTTPError
}
return nil, fmt.Errorf("[ERROR] %s: %+v", reqURL, err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("[ERROR] reading response %+v", err)
}
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("[DEBUG] %s\n", msg)
}
return nil, fmt.Errorf("[ERROR] %s", msg)
}
return body, nil
}