//nolint:golint package dcxAutohost import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" "github.com/pkg/errors" raxidentity "github.rackspace.com/gorax/clients/raxIdentity" ) // DCXRateLimit is the rate at which we will limit calls to DCX within our client // DCX Rate limits at 100 req/second: // - https://github.rackspace.com/dcx/gateway/blob/master/ansible/roles/deploy/files/rate-limiting.cfg.xml#L6 // So that would be one request, every 10 milliseconds. We'll bump it up just a little more for safety sake. const DCXRateLimit = time.Millisecond * 15 type ( // Client type is the main receiver created to // interact with the DCX library. Client struct { Username string pass, token string Staging bool transport *http.Transport ticker *time.Ticker } // Auth defines a signature for an authentication method passed into the // dcxAutohost init function. Auth func(c *Client) ) // WithCredential is an authentication method to initialize the client by first // authenticating to the Rackspace Identity endpoint, then storing the // authentication token. func WithCredential(user, pass string) Auth { return func(c *Client) { c.Username = user c.pass = pass } } // WithToken is an authentication method to initialize the client using a // token already retrieved from Rackspace Identity. //nolint:unused,deadcode func WithToken(token string) Auth { return func(c *Client) { c.token = token } } // New authenticates to the API and returns an AutoHost object and error object. func New(auth Auth, staging bool) (*Client, error) { // Initialize a new dcx client. client := &Client{Staging: staging} // Apply the authentication method auth(client) // If the authentication method was username and password. if client.Username != "" && client.pass != "" { token, err := raxidentity.InternalAuth(client.Username, client.pass, staging) if err != nil { return nil, err } client.token = token.Access.Token.ID } // transport is assigned at client creation time and reused for subsequent connections. // https://godoc.org/net/http#Transport // "Transports should be reused instead of created as needed. // Transports are safe for concurrent use by multiple goroutines." client.transport = &http.Transport{ MaxIdleConnsPerHost: 20, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } // NewTicker will create a Ticker type with two important things in it. // 1. A channel of type time.Time with a 1 element buffer 'make(chan time.Time, 1)' // 2. A runtime Timer that holds the duration, next iteration, and increment func // // When time reaches 'duration', the timer will send the current time (time.Now()) // on it's channel. This allows the receiving function to receive the current time, // unblocking it for an iteration. // // A 1 element buffered channel guarantees that the previous signal that was sent has been received. // Because the receive of the first signal, happens before the send of the second signal completes. client.ticker = time.NewTicker(DCXRateLimit) return client, nil } // NewWithToken authenticates to the API and returns an AutoHost object and error object. // Deprecated: Use the New(Auth, bool) function to initialize a DCX Autohost client. func NewWithToken(token string, staging bool) (*Client, error) { return &Client{ token: token, Staging: staging, transport: &http.Transport{ MaxIdleConnsPerHost: 20, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, ticker: time.NewTicker(DCXRateLimit), }, nil } // get method is a helper used to initiate a GET request to the Autohost API endpoint. func (a *Client) get(uri string, params url.Values) ([]byte, error) { return a.request(http.MethodGet, uri, params, nil) } // post method is a helper used to initiate a POST request to the Autohost API endpoint. func (a *Client) post(uri string, payload []byte) ([]byte, error) { return a.request(http.MethodPost, uri, nil, payload) } // put method is a helper used to initiate a PUT request to the Autohost API endpoint. func (a *Client) put(uri string, payload []byte) ([]byte, error) { return a.request(http.MethodPut, uri, nil, payload) } // request method will initiate a general request to the Autohost API endpoint. Method takes an Autohost // receiver struct and the URI path. // TODO: Using a general request helper method that attempts to handle all of the request/response decoding // is a bad idea, but there's a huge amount of work needed to convert all the caller functions // so that they can handle their own request. This still needs to be addressed. func (a *Client) request(method, uri string, params url.Values, payload []byte) ([]byte, error) { // Here, we wait in a blocking state until the timer func signals on its // channel with the current time. <-a.ticker.C req, err := http.NewRequest(method, a.path(uri), bytes.NewBuffer(payload)) if err != nil { return nil, err } req.Header.Set("X-Auth-Token", a.token) req.Header.Set("Accept-Encoding", "application/json") req.Header.Set("Content-Type", "application/json") if params != nil { enc := params.Encode() req.Header.Add("Content-Length", strconv.Itoa(len(enc))) req.URL.RawQuery = enc } client := &http.Client{Transport: a.transport} res, err := client.Do(req) if res != nil { // Note: We use a func to error check defer as opposed to using // defer res.Body.Close(), which will never return an error. defer func() { if defErr := res.Body.Close(); defErr != nil { err = errors.Wrap(err, defErr.Error()) } }() } if err != nil { return nil, err } body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } if res.StatusCode > http.StatusIMUsed { return nil, DCXError(res.Status, body) } return body, nil } func (a *Client) path(uri string) string { if a.Staging { return "https://api.staging.dcx.rackspace.com" + uri } return "https://dcx.rackspace.com/api" + uri } // DCXErr defines the type returned anytime there is an error in the // DCX response payload type DCXErr struct { Errors []string `json:"errors"` Status string } // Error function will handle any DCX errors as they come back from // the API. func (e DCXErr) Error() string { if len(e.Errors) == 0 { return "" } return fmt.Sprintf("%s: %s", e.Status, strings.Join(e.Errors, ",")) } // DCXError function will handle any DCX errors as they come back from // the API. func DCXError(status string, err []byte) DCXErr { var payload DCXErr if decErr := json.NewDecoder(bytes.NewReader(err)).Decode(&payload); decErr != nil { return DCXErr{Errors: []string{decErr.Error(), string(err)}, Status: status} } payload.Status = status return payload }