traefik/vendor/github.com/exoscale/egoscale/request.go

398 lines
9.8 KiB
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
package egoscale
import (
"bytes"
2018-09-14 08:06:03 +00:00
"context"
2017-02-07 21:33:23 +00:00
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
2018-09-14 08:06:03 +00:00
"io"
2017-02-07 21:33:23 +00:00
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
2017-10-31 09:42:03 +00:00
"strings"
"time"
2017-02-07 21:33:23 +00:00
)
2018-09-14 08:06:03 +00:00
// Error formats a CloudStack error into a standard error
func (e ErrorResponse) Error() string {
return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText)
}
2018-09-14 08:06:03 +00:00
// Error formats a CloudStack job response into a standard error
func (e booleanResponse) Error() error {
if !e.Success {
return fmt.Errorf("API error: %s", e.DisplayText)
}
return nil
}
2018-09-14 08:06:03 +00:00
// XXX: addIpToNic, activateIp6, restorevmresponse are kind of special
var responseKeys = map[string]string{
"addiptonicresponse": "addiptovmnicresponse",
"activateip6response": "activateip6nicresponse",
"restorevirtualmachineresponse": "restorevmresponse",
}
2018-09-14 08:06:03 +00:00
func (client *Client) parseResponse(resp *http.Response, apiName string) (json.RawMessage, error) {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
m := map[string]json.RawMessage{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
key := fmt.Sprintf("%sresponse", strings.ToLower(apiName))
response, ok := m[key]
if !ok {
if resp.StatusCode >= 400 {
response, ok = m["errorresponse"]
}
2018-09-14 08:06:03 +00:00
if !ok {
// try again with the special keys
value, ok := responseKeys[key]
if ok {
key = value
}
2018-09-14 08:06:03 +00:00
response, ok = m[key]
2018-09-14 08:06:03 +00:00
if !ok {
for k := range m {
return nil, fmt.Errorf("malformed JSON response, %q was expected, got %q", key, k)
}
}
}
}
2018-09-14 08:06:03 +00:00
if resp.StatusCode >= 400 {
errorResponse := new(ErrorResponse)
if e := json.Unmarshal(response, errorResponse); e != nil && errorResponse.ErrorCode <= 0 {
return nil, fmt.Errorf("%d %s", resp.StatusCode, b)
}
return nil, errorResponse
}
2018-09-14 08:06:03 +00:00
n := map[string]json.RawMessage{}
if err := json.Unmarshal(response, &n); err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
// list response may contain only one key
if len(n) > 1 || strings.HasPrefix(key, "list") {
return response, nil
}
2018-09-14 08:06:03 +00:00
if len(n) == 1 {
for k := range n {
// boolean response and asyncjob result may also contain
// only one key
if k == "success" || k == "jobid" {
return response, nil
}
return n[k], nil
}
}
2018-09-14 08:06:03 +00:00
return response, nil
}
2018-09-14 08:06:03 +00:00
// asyncRequest perform an asynchronous job with a context
func (client *Client) asyncRequest(ctx context.Context, asyncCommand AsyncCommand) (interface{}, error) {
var err error
resp := asyncCommand.asyncResponse()
client.AsyncRequestWithContext(
ctx,
asyncCommand,
func(j *AsyncJobResult, e error) bool {
if e != nil {
err = e
return false
}
if j.JobStatus != Pending {
if r := j.Result(resp); r != nil {
err = r
}
return false
}
return true
},
)
return resp, err
}
2018-09-14 08:06:03 +00:00
// SyncRequestWithContext performs a sync request with a context
func (client *Client) SyncRequestWithContext(ctx context.Context, command Command) (interface{}, error) {
body, err := client.request(ctx, command)
if err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
response := command.response()
b, ok := response.(*booleanResponse)
if ok {
m := make(map[string]interface{})
if errUnmarshal := json.Unmarshal(body, &m); errUnmarshal != nil {
return nil, errUnmarshal
}
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
b.DisplayText, _ = m["displaytext"].(string)
if success, okSuccess := m["success"].(string); okSuccess {
b.Success = success == "true"
}
if success, okSuccess := m["success"].(bool); okSuccess {
b.Success = success
}
return b, nil
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
if err := json.Unmarshal(body, response); err != nil {
errResponse := new(ErrorResponse)
if e := json.Unmarshal(body, errResponse); e == nil && errResponse.ErrorCode > 0 {
return errResponse, nil
}
return nil, err
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
return response, nil
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
// BooleanRequest performs the given boolean command
func (client *Client) BooleanRequest(command Command) error {
resp, err := client.Request(command)
if err != nil {
return err
}
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
if b, ok := resp.(*booleanResponse); ok {
return b.Error()
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
// BooleanRequestWithContext performs the given boolean command
func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error {
resp, err := client.RequestWithContext(ctx, command)
2017-02-07 21:33:23 +00:00
if err != nil {
2018-09-14 08:06:03 +00:00
return err
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
if b, ok := resp.(*booleanResponse); ok {
return b.Error()
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
}
// Request performs the given command
func (client *Client) Request(command Command) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.RequestWithContext(ctx, command)
}
// RequestWithContext preforms a command with a context
func (client *Client) RequestWithContext(ctx context.Context, command Command) (interface{}, error) {
switch command.(type) {
case AsyncCommand:
return client.asyncRequest(ctx, command.(AsyncCommand))
default:
return client.SyncRequestWithContext(ctx, command)
}
}
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
// SyncRequest performs the command as is
func (client *Client) SyncRequest(command Command) (interface{}, error) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
return client.SyncRequestWithContext(ctx, command)
}
// AsyncRequest performs the given command
func (client *Client) AsyncRequest(asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
defer cancel()
client.AsyncRequestWithContext(ctx, asyncCommand, callback)
}
// AsyncRequestWithContext preforms a request with a context
func (client *Client) AsyncRequestWithContext(ctx context.Context, asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
result, err := client.SyncRequestWithContext(ctx, asyncCommand)
if err != nil {
2018-09-14 08:06:03 +00:00
if !callback(nil, err) {
return
}
}
2018-09-14 08:06:03 +00:00
jobResult, ok := result.(*AsyncJobResult)
if !ok {
callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result))
}
// Successful response
2018-09-14 08:06:03 +00:00
if jobResult.JobID == nil || jobResult.JobStatus != Pending {
callback(jobResult, nil)
// without a JobID, the next requests will only fail
return
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
for iteration := 0; ; iteration++ {
time.Sleep(client.RetryStrategy(int64(iteration)))
2018-09-14 08:06:03 +00:00
req := &QueryAsyncJobResult{JobID: jobResult.JobID}
resp, err := client.SyncRequestWithContext(ctx, req)
if err != nil && !callback(nil, err) {
return
}
2018-09-14 08:06:03 +00:00
result, ok := resp.(*AsyncJobResult)
if !ok {
if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) {
return
}
}
2018-09-14 08:06:03 +00:00
if !callback(result, nil) {
return
}
}
2018-09-14 08:06:03 +00:00
}
2018-09-14 08:06:03 +00:00
// Payload builds the HTTP request params from the given command
func (client *Client) Payload(command Command) (url.Values, error) {
params := url.Values{}
err := prepareValues("", params, command)
if err != nil {
return params, err
}
2018-09-14 08:06:03 +00:00
if hookReq, ok := command.(onBeforeHook); ok {
if err := hookReq.onBeforeSend(params); err != nil {
return params, err
}
}
2018-09-14 08:06:03 +00:00
params.Set("apikey", client.APIKey)
params.Set("command", client.APIName(command))
params.Set("response", "json")
2018-09-14 08:06:03 +00:00
return params, nil
2017-02-07 21:33:23 +00:00
}
2018-09-14 08:06:03 +00:00
// Sign signs the HTTP request and returns the signature as as base64 encoding
func (client *Client) Sign(params url.Values) (string, error) {
query := encodeValues(params)
query = strings.ToLower(query)
mac := hmac.New(sha1.New, []byte(client.apiSecret))
_, err := mac.Write([]byte(query))
if err != nil {
2018-09-14 08:06:03 +00:00
return "", err
}
2018-09-14 08:06:03 +00:00
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return signature, nil
}
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
// request makes a Request while being close to the metal
func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) {
params, err := client.Payload(command)
if err != nil {
2018-09-14 08:06:03 +00:00
return nil, err
}
signature, err := client.Sign(params)
if err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
params.Add("signature", signature)
2018-09-14 08:06:03 +00:00
method := "GET"
query := params.Encode()
url := fmt.Sprintf("%s?%s", client.Endpoint, query)
var body io.Reader
// respect Internet Explorer limit of 2048
if len(url) > 2048 {
url = client.Endpoint
method = "POST"
body = strings.NewReader(query)
}
2018-09-14 08:06:03 +00:00
request, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
request = request.WithContext(ctx)
request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version))
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
if method == "POST" {
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
request.Header.Add("Content-Length", strconv.Itoa(len(query)))
}
resp, err := client.HTTPClient.Do(request)
if err != nil {
return nil, err
}
2018-09-14 08:06:03 +00:00
defer resp.Body.Close() // nolint: errcheck
2018-09-14 08:06:03 +00:00
contentType := resp.Header.Get("content-type")
2018-09-14 08:06:03 +00:00
if !strings.Contains(contentType, "application/json") {
return nil, fmt.Errorf(`body content-type response expected "application/json", got %q`, contentType)
}
text, err := client.parseResponse(resp, client.APIName(command))
if err != nil {
return nil, err
}
2017-02-07 21:33:23 +00:00
2018-09-14 08:06:03 +00:00
return text, nil
}
func encodeValues(params url.Values) string {
// This code is borrowed from net/url/url.go
// The way it's encoded by net/url doesn't match
2018-09-14 08:06:03 +00:00
// how CloudStack works to determine the signature.
//
// CloudStack only encodes the values of the query parameters
// and furthermore doesn't use '+' for whitespaces. Therefore
// after encoding the values all '+' are replaced with '%20'.
if params == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(params))
for k := range params {
keys = append(keys, k)
}
sort.Strings(keys)
2017-10-31 09:42:03 +00:00
for _, k := range keys {
2018-09-14 08:06:03 +00:00
prefix := k + "="
for _, v := range params[k] {
if buf.Len() > 0 {
buf.WriteByte('&')
}
buf.WriteString(prefix)
buf.WriteString(csEncode(v))
}
}
2018-09-14 08:06:03 +00:00
return buf.String()
2017-02-07 21:33:23 +00:00
}