2018-05-30 22:28:41 +00:00
|
|
|
package egoscale
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha1"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"sort"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Error formats a CloudStack error into a standard error
|
2018-09-08 10:09:59 +00:00
|
|
|
func (e ErrorResponse) Error() string {
|
2018-05-30 22:28:41 +00:00
|
|
|
return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText)
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +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)
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
return nil
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
// XXX: addIpToNic, activateIp6, restorevmresponse are kind of special
|
|
|
|
var responseKeys = map[string]string{
|
|
|
|
"addiptonicresponse": "addiptovmnicresponse",
|
|
|
|
"activateip6response": "activateip6nicresponse",
|
|
|
|
"restorevirtualmachineresponse": "restorevmresponse",
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) parseResponse(resp *http.Response, apiName string) (json.RawMessage, error) {
|
|
|
|
b, err := ioutil.ReadAll(resp.Body)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
2018-09-08 10:09:59 +00:00
|
|
|
return nil, err
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
m := map[string]json.RawMessage{}
|
|
|
|
if err := json.Unmarshal(b, &m); err != nil {
|
|
|
|
return nil, err
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
key := fmt.Sprintf("%sresponse", strings.ToLower(apiName))
|
|
|
|
response, ok := m[key]
|
|
|
|
if !ok {
|
|
|
|
if resp.StatusCode >= 400 {
|
|
|
|
response, ok = m["errorresponse"]
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
if !ok {
|
|
|
|
// try again with the special keys
|
|
|
|
value, ok := responseKeys[key]
|
|
|
|
if ok {
|
|
|
|
key = value
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
response, ok = m[key]
|
2018-05-30 22:28:41 +00:00
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
if !ok {
|
|
|
|
for k := range m {
|
|
|
|
return nil, fmt.Errorf("malformed JSON response, %q was expected, got %q", key, k)
|
|
|
|
}
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode >= 400 {
|
|
|
|
errorResponse := new(ErrorResponse)
|
2018-09-08 10:09:59 +00:00
|
|
|
if e := json.Unmarshal(response, errorResponse); e != nil && errorResponse.ErrorCode <= 0 {
|
|
|
|
return nil, fmt.Errorf("%d %s", resp.StatusCode, b)
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
return nil, errorResponse
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
n := map[string]json.RawMessage{}
|
|
|
|
if err := json.Unmarshal(response, &n); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(n) > 1 {
|
|
|
|
return response, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return response, nil
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// asyncRequest perform an asynchronous job with a context
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) asyncRequest(ctx context.Context, asyncCommand AsyncCommand) (interface{}, error) {
|
2018-05-30 22:28:41 +00:00
|
|
|
var err error
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
resp := asyncCommand.asyncResponse()
|
|
|
|
client.AsyncRequestWithContext(
|
|
|
|
ctx,
|
|
|
|
asyncCommand,
|
|
|
|
func(j *AsyncJobResult, e error) bool {
|
|
|
|
if e != nil {
|
|
|
|
err = e
|
|
|
|
return false
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
if j.JobStatus == Success {
|
|
|
|
if r := j.Result(resp); r != nil {
|
|
|
|
err = r
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
},
|
|
|
|
)
|
|
|
|
return resp, err
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +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)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +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
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
|
2018-09-08 10:09:59 +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
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
|
|
|
|
return b, nil
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
if err := json.Unmarshal(body, response); err != nil {
|
2018-05-30 22:28:41 +00:00
|
|
|
errResponse := new(ErrorResponse)
|
|
|
|
if e := json.Unmarshal(body, errResponse); e == nil && errResponse.ErrorCode > 0 {
|
|
|
|
return errResponse, nil
|
|
|
|
}
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return response, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// BooleanRequest performs the given boolean command
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) BooleanRequest(command Command) error {
|
|
|
|
resp, err := client.Request(command)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if b, ok := resp.(*booleanResponse); ok {
|
|
|
|
return b.Error()
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// BooleanRequestWithContext performs the given boolean command
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error {
|
|
|
|
resp, err := client.RequestWithContext(ctx, command)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if b, ok := resp.(*booleanResponse); ok {
|
|
|
|
return b.Error()
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Request performs the given command
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) Request(command Command) (interface{}, error) {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
|
2018-05-30 22:28:41 +00:00
|
|
|
defer cancel()
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
return client.RequestWithContext(ctx, command)
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
// RequestWithContext preforms a command with a context
|
|
|
|
func (client *Client) RequestWithContext(ctx context.Context, command Command) (interface{}, error) {
|
|
|
|
switch command.(type) {
|
2018-05-30 22:28:41 +00:00
|
|
|
case AsyncCommand:
|
2018-09-08 10:09:59 +00:00
|
|
|
return client.asyncRequest(ctx, command.(AsyncCommand))
|
2018-05-30 22:28:41 +00:00
|
|
|
default:
|
2018-09-08 10:09:59 +00:00
|
|
|
return client.SyncRequestWithContext(ctx, command)
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +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)
|
|
|
|
}
|
|
|
|
|
2018-05-30 22:28:41 +00:00
|
|
|
// AsyncRequest performs the given command
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) AsyncRequest(asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), client.Timeout)
|
2018-05-30 22:28:41 +00:00
|
|
|
defer cancel()
|
2018-09-08 10:09:59 +00:00
|
|
|
|
|
|
|
client.AsyncRequestWithContext(ctx, asyncCommand, callback)
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// AsyncRequestWithContext preforms a request with a context
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) AsyncRequestWithContext(ctx context.Context, asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) {
|
|
|
|
result, err := client.SyncRequestWithContext(ctx, asyncCommand)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
if !callback(nil, err) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
jobResult, ok := result.(*AsyncJobResult)
|
|
|
|
if !ok {
|
|
|
|
callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result))
|
|
|
|
}
|
|
|
|
|
2018-05-30 22:28:41 +00:00
|
|
|
// Successful response
|
2018-09-08 10:09:59 +00:00
|
|
|
if jobResult.JobID == nil || jobResult.JobStatus != Pending {
|
2018-05-30 22:28:41 +00:00
|
|
|
callback(jobResult, nil)
|
|
|
|
// without a JobID, the next requests will only fail
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for iteration := 0; ; iteration++ {
|
2018-09-08 10:09:59 +00:00
|
|
|
time.Sleep(client.RetryStrategy(int64(iteration)))
|
2018-05-30 22:28:41 +00:00
|
|
|
|
|
|
|
req := &QueryAsyncJobResult{JobID: jobResult.JobID}
|
2018-09-08 10:09:59 +00:00
|
|
|
resp, err := client.SyncRequestWithContext(ctx, req)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil && !callback(nil, err) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
result, ok := resp.(*AsyncJobResult)
|
|
|
|
if !ok {
|
|
|
|
if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) {
|
|
|
|
return
|
|
|
|
}
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
if result.JobStatus == Failure {
|
|
|
|
if !callback(nil, result.Error()) {
|
2018-05-30 22:28:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
2018-09-08 10:09:59 +00:00
|
|
|
if !callback(result, nil) {
|
2018-05-30 22:28:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
// Payload builds the HTTP request params from the given command
|
|
|
|
func (client *Client) Payload(command Command) (url.Values, error) {
|
2018-05-30 22:28:41 +00:00
|
|
|
params := url.Values{}
|
2018-09-08 10:09:59 +00:00
|
|
|
err := prepareValues("", params, command)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
2018-09-08 10:09:59 +00:00
|
|
|
return params, err
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
if hookReq, ok := command.(onBeforeHook); ok {
|
|
|
|
if err := hookReq.onBeforeSend(params); err != nil {
|
|
|
|
return params, err
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
params.Set("apikey", client.APIKey)
|
|
|
|
params.Set("command", client.APIName(command))
|
2018-05-30 22:28:41 +00:00
|
|
|
params.Set("response", "json")
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
return params, nil
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +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))
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
|
|
|
return signature, nil
|
2018-05-30 22:28:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// request makes a Request while being close to the metal
|
2018-09-08 10:09:59 +00:00
|
|
|
func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) {
|
|
|
|
params, err := client.Payload(command)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
signature, err := client.Sign(params)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
params.Add("signature", signature)
|
2018-05-30 22:28:41 +00:00
|
|
|
|
|
|
|
method := "GET"
|
2018-09-08 10:09:59 +00:00
|
|
|
query := params.Encode()
|
|
|
|
url := fmt.Sprintf("%s?%s", client.Endpoint, query)
|
2018-05-30 22:28:41 +00:00
|
|
|
|
|
|
|
var body io.Reader
|
|
|
|
// respect Internet Explorer limit of 2048
|
2018-09-08 10:09:59 +00:00
|
|
|
if len(url) > 2048 {
|
|
|
|
url = client.Endpoint
|
2018-05-30 22:28:41 +00:00
|
|
|
method = "POST"
|
|
|
|
body = strings.NewReader(query)
|
|
|
|
}
|
|
|
|
|
|
|
|
request, err := http.NewRequest(method, url, body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
request = request.WithContext(ctx)
|
|
|
|
request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version))
|
|
|
|
|
|
|
|
if method == "POST" {
|
|
|
|
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
request.Header.Add("Content-Length", strconv.Itoa(len(query)))
|
|
|
|
}
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
resp, err := client.HTTPClient.Do(request)
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close() // nolint: errcheck
|
|
|
|
|
2018-09-08 10:09:59 +00:00
|
|
|
contentType := resp.Header.Get("content-type")
|
|
|
|
|
|
|
|
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))
|
2018-05-30 22:28:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return text, nil
|
|
|
|
}
|
2018-09-08 10:09:59 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
// 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)
|
|
|
|
for _, k := range keys {
|
|
|
|
prefix := k + "="
|
|
|
|
for _, v := range params[k] {
|
|
|
|
if buf.Len() > 0 {
|
|
|
|
buf.WriteByte('&')
|
|
|
|
}
|
|
|
|
buf.WriteString(prefix)
|
|
|
|
buf.WriteString(csEncode(v))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return buf.String()
|
|
|
|
}
|