/
client_2_5.go
280 lines (232 loc) · 7.52 KB
/
client_2_5.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
package goaviatrix
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
type APIError struct {
Message string
}
func checkAndReturnAPIResp25(resp *http.Response, v interface{}, method, path string) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(resp.Body)
if err != nil {
return fmt.Errorf("reading response body %q failed: %v", path, err)
}
bodyString := buf.String()
if resp.StatusCode >= 300 || resp.StatusCode < 200 {
var apiError APIError
if err := json.NewDecoder(strings.NewReader(bodyString)).Decode(&apiError); err != nil {
return fmt.Errorf("Json Decode failed: %v\n Body: %s", err, bodyString)
}
return fmt.Errorf("HTTP %s %q failed: %v\n", method, path, apiError.Message)
}
if v != nil {
if err := json.NewDecoder(strings.NewReader(bodyString)).Decode(&v); err != nil {
return fmt.Errorf("Json Decode failed: %v\n Body: %s", err, bodyString)
}
}
return nil
}
func (c *Client) urlencode25(d map[string]string, path string) (string, error) {
link := fmt.Sprintf("https://%s/v2.5/api/%s", c.ControllerIP, path)
Url, err := url.Parse(link)
if err != nil {
return "", fmt.Errorf("parsing url: %v", err)
}
v := url.Values{}
for key, val := range d {
v.Add(key, val)
}
Url.RawQuery = v.Encode()
return Url.String(), nil
}
func (c *Client) GetAPIContext25(ctx context.Context, v interface{}, path string, d map[string]string) error {
Url, err := c.urlencode25(d, path)
if err != nil {
return fmt.Errorf("could not url encode values for path %q: %v", path, err)
}
try, maxTries, backoff := 0, 5, 500*time.Millisecond
var resp *http.Response
for {
try++
resp, err = c.RequestContext25(ctx, "GET", Url, nil)
if err == nil {
break
}
log.WithFields(log.Fields{
"try": try,
"action": path,
"err": err.Error(),
}).Warnf("HTTP GET request failed")
if try == maxTries {
return fmt.Errorf("HTTP Get %s failed: %v", path, err)
}
time.Sleep(backoff)
// Double the backoff time after each failed try
backoff *= 2
}
return checkAndReturnAPIResp25(resp, v, "GET", path)
}
func (c *Client) PostAPIContext25(ctx context.Context, v interface{}, path string, d interface{}) error {
return c.DoAPIContext25(ctx, "POST", v, path, d)
}
func (c *Client) PutAPIContext25(ctx context.Context, path string, d interface{}) error {
return c.DoAPIContext25(ctx, "PUT", nil, path, d)
}
func (c *Client) DeleteAPIContext25(ctx context.Context, path string, d interface{}) error {
return c.DoAPIContext25(ctx, "DELETE", nil, path, d)
}
func (c *Client) DoAPIContext25(ctx context.Context, verb string, v interface{}, path string, d interface{}) error {
Url := fmt.Sprintf("https://%s/v2.5/api/%s", c.ControllerIP, path)
resp, err := c.RequestContext25(ctx, verb, Url, d)
if err != nil {
return fmt.Errorf("HTTP %s %q failed: %v", verb, path, err)
}
return checkAndReturnAPIResp25(resp, v, verb, path)
}
func (c *Client) RequestContext25(ctx context.Context, verb string, Url string, i interface{}) (*http.Response, error) {
log.Tracef("%s %s", verb, Url)
try, maxTries, backoff := 0, 2, 500*time.Millisecond
var req *http.Request
var err error
var apiError *APIError
var resp *http.Response
if i != nil {
body, err := json.Marshal(i)
if err != nil {
return nil, err
}
log.Tracef("%s %s Body: %s", verb, Url, body)
reader := bytes.NewReader(body)
req, err = http.NewRequestWithContext(ctx, verb, Url, reader)
if err == nil {
req.Header.Set("Content-Type", "application/json")
}
} else {
req, err = http.NewRequestWithContext(ctx, verb, Url, nil)
}
if err != nil {
return nil, err
}
for {
try++
// Set CID as Authorization header for v2.5
req.Header.Set("Authorization", fmt.Sprintf("cid %s", c.CID))
resp, err = c.HTTPClient.Do(req)
if err != nil {
return resp, err
}
if resp.StatusCode == 403 {
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
resp.Body.Close()
// Replace resp.Body with new ReadCloser so that other methods can read the buffer again
resp.Body = io.NopCloser(buf)
bodyString := buf.String()
apiError = new(APIError)
if err := json.NewDecoder(strings.NewReader(bodyString)).Decode(apiError); err != nil {
return resp, fmt.Errorf("Json Decode into error message failed: %v\n Body: %s", err, bodyString)
}
if !strings.Contains(apiError.Message, "Invalid CID") {
log.Debugf("[DEBUG] API Response Error: %s\n", apiError.Message)
return resp, err
}
log.Tracef("CID invalid or expired. Trying to login again")
if err = c.Login(); err != nil {
return resp, err
}
log.WithFields(log.Fields{
"try": try,
"err": "CID is invalid",
}).Warnf("HTTP request failed with expired CID")
if try == maxTries {
return resp, fmt.Errorf("%v", apiError.Message)
}
time.Sleep(backoff)
// Double the backoff time after each failed try
backoff *= 2
} else {
log.Debugf("[DEBUG] HTTP Response: %v\n", resp)
return resp, err
}
}
}
// PostFileContext25 will encode the files and parameters with multipart form encoding.
func (c *Client) PostFileContext25(ctx context.Context, path string, params map[string]string, files []File) error {
return c.DoAPIFileContext25(ctx, "POST", path, params, files)
}
func (c *Client) DoAPIFileContext25(ctx context.Context, verb string, path string, params map[string]string, files []File) error {
Url := fmt.Sprintf("https://%s/v2.5/api/%s", c.ControllerIP, path)
resp, err := c.RequestFileContext25(ctx, verb, Url, params, files)
if err != nil {
return fmt.Errorf("HTTP %s %q failed: %v", verb, path, err)
}
return checkAndReturnAPIResp25(resp, nil, verb, path)
}
func (c *Client) RequestFileContext25(ctx context.Context, verb string, Url string, params map[string]string, files []File) (*http.Response, error) {
log.Tracef("%s %s", verb, Url)
try, maxTries, backoff := 0, 2, 500*time.Millisecond
var req *http.Request
var err error
var apiError *APIError
var resp *http.Response
body, contentType, err := encodeMultipartFormData(params, files)
if err != nil {
return nil, err
}
req, err = http.NewRequestWithContext(ctx, verb, Url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
for {
try++
// Set CID as Authorization header for v2.5
req.Header.Set("Authorization", fmt.Sprintf("cid %s", c.CID))
resp, err = c.HTTPClient.Do(req)
if err != nil {
return resp, err
}
if resp.StatusCode == 403 {
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
resp.Body.Close()
// Replace resp.Body with new ReadCloser so that other methods can read the buffer again
resp.Body = io.NopCloser(buf)
bodyString := buf.String()
apiError = new(APIError)
if err := json.NewDecoder(strings.NewReader(bodyString)).Decode(apiError); err != nil {
return resp, fmt.Errorf("Json Decode into error message failed: %v\n Body: %s", err, bodyString)
}
if !strings.Contains(apiError.Message, "Invalid CID") {
log.Debugf("[DEBUG] API Response Error: %s\n", apiError.Message)
return resp, err
}
log.Tracef("CID invalid or expired. Trying to login again")
if err = c.Login(); err != nil {
return resp, err
}
log.WithFields(log.Fields{
"try": try,
"err": "CID is invalid",
}).Warnf("HTTP request failed with expired CID")
if try == maxTries {
return resp, fmt.Errorf("%v", apiError.Message)
}
time.Sleep(backoff)
// Double the backoff time after each failed try
backoff *= 2
} else {
log.Debugf("[DEBUG] HTTP Response: %v\n", resp)
return resp, err
}
}
}