/
http.go
388 lines (327 loc) · 11.6 KB
/
http.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
package cdsclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"regexp"
"runtime/pprof"
"strings"
"time"
"github.com/ovh/cds/cli"
"github.com/ovh/cds/sdk/telemetry"
"github.com/dgrijalva/jwt-go"
"github.com/ovh/cds/sdk"
)
const (
// RequestedIfModifiedSinceHeader is used as HTTP header
RequestedIfModifiedSinceHeader = "If-Modified-Since"
// ResponseAPITimeHeader is used as HTTP header
ResponseAPITimeHeader = "X-Api-Time"
// ResponseAPINanosecondsTimeHeader is used as HTTP header
ResponseAPINanosecondsTimeHeader = "X-Api-Nanoseconds-Time"
// ResponseEtagHeader is used as HTTP header
ResponseEtagHeader = "Etag"
// ResponseProcessTimeHeader is used as HTTP header
ResponseProcessTimeHeader = "X-Api-Process-Time"
)
// RequestModifier is used to modify behavior of Request and Steam functions
type RequestModifier func(req *http.Request)
// HTTPClient is a interface for HTTPClient mock
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// SetHeader modify headers of http.Request
func SetHeader(key, value string) RequestModifier {
return func(req *http.Request) {
req.Header.Set(key, value)
}
}
// WithQueryParameter add query parameters to your http.Request
func WithQueryParameter(key, value string) RequestModifier {
return func(req *http.Request) {
q := req.URL.Query()
q.Set(key, value)
req.URL.RawQuery = q.Encode()
}
}
// PostJSON post the *in* struct as json. If set, it unmarshalls the response to *out*
func (c *client) PostJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {
_, _, code, err := c.RequestJSON(ctx, http.MethodPost, path, in, out, mods...)
return code, err
}
// PostJSON ut the *in* struct as json. If set, it unmarshalls the response to *out*
func (c *client) PutJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {
_, _, code, err := c.RequestJSON(ctx, http.MethodPut, path, in, out, mods...)
return code, err
}
// GetJSON get the requested path If set, it unmarshalls the response to *out*
func (c *client) GetJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {
_, _, code, err := c.RequestJSON(ctx, http.MethodGet, path, nil, out, mods...)
return code, err
}
// GetJSONWithHeaders get the requested path If set, it unmarshalls the response to *out* and return response headers
func (c *client) GetJSONWithHeaders(path string, out interface{}, mods ...RequestModifier) (http.Header, int, error) {
_, header, code, err := c.RequestJSON(context.Background(), http.MethodGet, path, nil, out, mods...)
return header, code, err
}
// DeleteJSON deletes the requested path If set, it unmarshalls the response to *out*
func (c *client) DeleteJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {
_, _, code, err := c.RequestJSON(ctx, http.MethodDelete, path, nil, out, mods...)
return code, err
}
// RequestJSON does a request with the *in* struct as json. If set, it unmarshalls the response to *out*
func (c *client) RequestJSON(ctx context.Context, method, path string, in interface{}, out interface{}, mods ...RequestModifier) ([]byte, http.Header, int, error) {
var b = []byte{}
var err error
if in != nil {
b, err = json.Marshal(in)
if err != nil {
return nil, nil, 0, newError(err)
}
}
var body io.Reader
if len(b) > 0 {
body = bytes.NewBuffer(b)
}
res, header, code, err := c.Request(ctx, method, path, body, mods...)
if err != nil {
return nil, nil, code, err
}
if code >= 400 {
if err := sdk.DecodeError(res); err != nil {
return res, nil, code, err
}
return res, nil, code, newAPIError(fmt.Errorf("HTTP %d", code))
}
if code == 204 {
return res, header, code, nil
}
if out != nil {
if err := json.Unmarshal(res, out); err != nil {
return res, nil, code, newError(err)
}
}
return res, header, code, nil
}
// Request executes an authentificated HTTP request on $path given $method and $args
func (c *client) Request(ctx context.Context, method string, path string, body io.Reader, mods ...RequestModifier) ([]byte, http.Header, int, error) {
respBody, respHeader, code, err := c.Stream(ctx, c.httpClient, method, path, body, mods...)
if err != nil {
return nil, nil, 0, err
}
defer func() {
// Drain and close the body to let the Transport reuse the connection
_, _ = io.Copy(ioutil.Discard, respBody)
_ = respBody.Close()
}()
var bodyBtes []byte
bodyBtes, err = ioutil.ReadAll(respBody)
if err != nil {
return nil, nil, code, newTransportError(err)
}
if c.config.Verbose {
if len(bodyBtes) > 0 {
log.Printf("Response Body: %s\n", bodyBtes)
}
}
if code >= 400 {
if err := sdk.DecodeError(bodyBtes); err != nil {
return bodyBtes, nil, code, newAPIError(err)
}
return bodyBtes, nil, code, newAPIError(fmt.Errorf("HTTP %d", code))
}
return bodyBtes, respHeader, code, nil
}
// signin route pattern
var signinRouteRegexp = regexp.MustCompile(`\/auth\/consumer\/.*\/signin`)
func extractBodyErrorFromResponse(r *http.Response) error {
body, _ := ioutil.ReadAll(r.Body)
r.Body.Close() // nolint
if err := sdk.DecodeError(body); err != nil {
return newAPIError(err)
}
return newAPIError(fmt.Errorf("HTTP %d", r.StatusCode))
}
// Stream makes an authenticated http request and return io.ReadCloser
func (c *client) Stream(ctx context.Context, httpClient HTTPClient, method string, path string, body io.Reader, mods ...RequestModifier) (io.ReadCloser, http.Header, int, error) {
// Checks that current session_token is still valid
// If not, challenge a new one against the authenticationToken
var checkToken = !strings.Contains(path, "/auth/consumer/builtin/signin") &&
!strings.Contains(path, "/auth/consumer/local/signin") &&
!strings.Contains(path, "/auth/consumer/local/signup") &&
!strings.Contains(path, "/auth/consumer/local/verify") &&
!strings.Contains(path, "/auth/consumer/worker/signin")
if checkToken && !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != "" {
if c.config.Verbose {
log.Printf("session token invalid: (%s). Relogin...\n", c.config.SessionToken)
}
resp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{"token": c.config.BuitinConsumerAuthenticationToken})
if err != nil {
return nil, nil, -1, err
}
if c.config.Verbose {
log.Println("jwt: ", sdk.StringFirstN(resp.Token, 12))
}
c.config.SessionToken = resp.Token
}
labels := pprof.Labels("path", path, "method", method)
ctx = pprof.WithLabels(ctx, labels)
pprof.SetGoroutineLabels(ctx)
// In case where the given reader is not a ReadSeeker we should store the body in ram to retry http request
var bodyBytes []byte
var err error
if _, ok := body.(io.ReadSeeker); !ok && body != nil {
bodyBytes, err = ioutil.ReadAll(body)
if err != nil {
return nil, nil, 0, newTransportError(err)
}
}
var url string
if strings.HasPrefix(path, "http") {
url = path
} else {
url = c.config.Host + path
}
var savederror error
for i := 0; i <= c.config.Retry; i++ {
var req *http.Request
var requestError error
if rs, ok := body.(io.ReadSeeker); ok {
if _, err := rs.Seek(0, 0); err != nil {
return nil, nil, 0, newError(fmt.Errorf("request failed after %d retries: %v. Original error: %v", i, err, savederror))
}
req, requestError = http.NewRequest(method, url, body)
} else {
req, requestError = http.NewRequest(method, url, bytes.NewBuffer(bodyBytes))
}
if requestError != nil {
savederror = newError(requestError)
continue
}
req = req.WithContext(ctx)
date := sdk.FormatDateRFC5322(time.Now())
req.Header.Set("Date", date)
req.Header.Set("X-CDS-RemoteTime", date)
if c.config.Verbose {
log.Printf("Stream > context> %s\n", telemetry.DumpContext(ctx))
}
spanCtx, ok := telemetry.ContextToSpanContext(ctx)
if ok {
telemetry.DefaultFormat.SpanContextToRequest(spanCtx, req)
}
for i := range mods {
if mods[i] != nil {
mods[i](req)
}
}
if req.Header.Get("Content-Type") == "" {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Connection", "close")
//No auth on signing routes or on url that is not cds configured in config.Host
if strings.HasPrefix(url, c.config.Host) && !signinRouteRegexp.MatchString(path) {
if _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {
if c.config.Verbose {
log.Println("JWT recognized")
}
auth := "Bearer " + c.config.SessionToken
req.Header.Add("Authorization", auth)
}
}
if c.config.Verbose {
log.Println(cli.Green("********REQUEST**********"))
dmp, _ := httputil.DumpRequestOut(req, true)
log.Printf("%s", string(dmp))
log.Println(cli.Green("**************************"))
}
resp, err := httpClient.Do(req)
if err != nil {
savederror = newError(err)
continue
}
if c.config.Verbose {
log.Println(cli.Yellow("********RESPONSE**********"))
dmp, _ := httputil.DumpResponse(resp, true)
log.Printf("%s", string(dmp))
log.Println(cli.Yellow("**************************"))
}
if resp.StatusCode == 401 {
c.config.SessionToken = ""
}
if resp.StatusCode == 409 || resp.StatusCode > 500 {
time.Sleep(250 * time.Millisecond)
savederror = extractBodyErrorFromResponse(resp)
continue
}
// if no request error by status > 500, check CDS error
// if there is a CDS errors, return it
if resp.StatusCode == 500 {
return nil, resp.Header, resp.StatusCode, extractBodyErrorFromResponse(resp)
}
return resp.Body, resp.Header, resp.StatusCode, nil
}
return nil, nil, 0, newError(fmt.Errorf("request failed after %d retries: %v", c.config.Retry, savederror))
}
// UploadMultiPart upload multipart
func (c *client) UploadMultiPart(method string, path string, body *bytes.Buffer, mods ...RequestModifier) ([]byte, int, error) {
// Checks that current session_token is still valid
// If not, challenge a new one against the authenticationToken
if !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != "" {
resp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{"token": c.config.BuitinConsumerAuthenticationToken})
if err != nil {
return nil, -1, err
}
c.config.SessionToken = resp.Token
}
var req *http.Request
req, errRequest := http.NewRequest(method, c.config.Host+path, body)
if errRequest != nil {
return nil, 0, newError(errRequest)
}
req.Header.Set("Content-Type", "application/octet-stream")
req.Header.Set("Connection", "close")
for i := range mods {
mods[i](req)
}
//No auth on signing routes
if !signinRouteRegexp.MatchString(path) {
if _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {
if c.config.Verbose {
fmt.Println("JWT recognized")
}
auth := "Bearer " + c.config.SessionToken
req.Header.Add("Authorization", auth)
}
}
resp, err := c.HTTPNoTimeoutClient().Do(req)
if err != nil {
return nil, 0, newTransportError(err)
}
defer resp.Body.Close()
if c.config.Verbose {
fmt.Printf("Response Status: %s\n", resp.Status)
fmt.Printf("Request path: %s\n", c.config.Host+path)
fmt.Printf("Request Headers: %s\n", req.Header)
fmt.Printf("Response Headers: %s\n", resp.Header)
}
if resp.StatusCode == 401 {
c.config.SessionToken = ""
}
var respBody []byte
respBody, err = ioutil.ReadAll(resp.Body)
if err != nil {
return nil, resp.StatusCode, newTransportError(err)
}
if c.config.Verbose {
if len(body.Bytes()) > 0 {
fmt.Printf("Response Body: %s\n", body.String())
}
}
return respBody, resp.StatusCode, nil
}