-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathrequest.go
403 lines (338 loc) · 10 KB
/
request.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
package egoscale
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"time"
)
// 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)
}
// 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
}
func responseKey(key string) (string, bool) {
// XXX: addIpToNic, activateIp6, restorevmresponse are kind of special
var responseKeys = map[string]string{
"addiptonicresponse": "addiptovmnicresponse",
"activateip6response": "activateip6nicresponse",
"restorevirtualmachineresponse": "restorevmresponse",
"updatevmaffinitygroupresponse": "updatevirtualmachineresponse",
}
k, ok := responseKeys[key]
return k, ok
}
func (client *Client) parseResponse(resp *http.Response, apiName string) (json.RawMessage, error) {
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
m := map[string]json.RawMessage{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
key := fmt.Sprintf("%sresponse", strings.ToLower(apiName))
response, ok := m[key]
if !ok {
if resp.StatusCode >= 400 {
response, ok = m["errorresponse"]
}
if !ok {
// try again with the special keys
value, ok := responseKey(key)
if ok {
key = value
}
response, ok = m[key]
if !ok {
return nil, fmt.Errorf("malformed JSON response %d, %q was expected.\n%s", resp.StatusCode, key, b)
}
}
}
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
}
n := map[string]json.RawMessage{}
if err := json.Unmarshal(response, &n); err != nil {
return nil, err
}
// list response may contain only one key
if len(n) > 1 || strings.HasPrefix(key, "list") {
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
}
// 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
}
// 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
}
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
}
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
}
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
}
return response, nil
}
// BooleanRequest performs the given boolean command
func (client *Client) BooleanRequest(command Command) error {
resp, err := client.Request(command)
if err != nil {
return err
}
if b, ok := resp.(*BooleanResponse); ok {
return b.Error()
}
panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp))
}
// BooleanRequestWithContext performs the given boolean command
func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error {
resp, err := client.RequestWithContext(ctx, command)
if err != nil {
return err
}
if b, ok := resp.(*BooleanResponse); ok {
return b.Error()
}
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 c := command.(type) {
case AsyncCommand:
return client.asyncRequest(ctx, c)
default:
return client.SyncRequestWithContext(ctx, command)
}
}
// 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 {
if !callback(nil, err) {
return
}
}
jobResult, ok := result.(*AsyncJobResult)
if !ok {
callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result))
}
// Successful response
if jobResult.JobID == nil || jobResult.JobStatus != Pending {
callback(jobResult, nil)
// without a JobID, the next requests will only fail
return
}
for iteration := 0; ; iteration++ {
time.Sleep(client.RetryStrategy(int64(iteration)))
req := &QueryAsyncJobResult{JobID: jobResult.JobID}
resp, err := client.SyncRequestWithContext(ctx, req)
if err != nil && !callback(nil, err) {
return
}
result, ok := resp.(*AsyncJobResult)
if !ok {
if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) {
return
}
}
if !callback(result, nil) {
return
}
}
}
// Payload builds the HTTP request params from the given command
func (client *Client) Payload(command Command) (url.Values, error) {
params, err := prepareValues("", command)
if err != nil {
return nil, err
}
if hookReq, ok := command.(onBeforeHook); ok {
if err := hookReq.onBeforeSend(params); err != nil {
return params, err
}
}
params.Set("apikey", client.APIKey)
params.Set("command", client.APIName(command))
params.Set("response", "json")
if params.Get("expires") == "" && client.Expiration >= 0 {
params.Set("signatureversion", "3")
params.Set("expires", time.Now().Add(client.Expiration).Local().Format("2006-01-02T15:04:05-0700"))
}
return params, nil
}
// 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 {
return "", err
}
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
return signature, nil
}
// 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 {
return nil, err
}
signature, err := client.Sign(params)
if err != nil {
return nil, err
}
params.Add("signature", signature)
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)
}
request, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
request = request.WithContext(ctx)
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
}
defer resp.Body.Close() // nolint: errcheck
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))
if err != nil {
return nil, err
}
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
// 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()
}