forked from galaxydi/go-loghub
-
Notifications
You must be signed in to change notification settings - Fork 113
/
request.go
261 lines (234 loc) · 6.59 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
package sls
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/cenkalti/backoff"
"github.com/go-kit/kit/log/level"
"golang.org/x/net/context"
)
// timeout configs
var (
defaultRequestTimeout = 60 * time.Second
defaultRetryTimeout = 90 * time.Second
defaultHttpClient = newDefaultHTTPClient(defaultRequestTimeout)
defaultHTTPIdleTimeout = time.Second * 55
)
func newDefaultTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.IdleConnTimeout = defaultHTTPIdleTimeout
return t
}
// returns a new http client instance with default config
func newDefaultHTTPClient(requestTimeout time.Duration) *http.Client {
return &http.Client{
Transport: newDefaultTransport(),
Timeout: requestTimeout,
}
}
func retryReadErrorCheck(ctx context.Context, err error) (bool, error) {
if err == nil {
return false, nil
}
switch e := err.(type) {
case *url.Error:
return true, e
case *Error:
if RetryOnServerErrorEnabled {
if e.HTTPCode >= 500 && e.HTTPCode <= 599 {
return true, e
}
}
case *BadResponseError:
if RetryOnServerErrorEnabled {
if e.HTTPCode >= 500 && e.HTTPCode <= 599 {
return true, e
}
}
default:
return false, e
}
return false, err
}
func retryWriteErrorCheck(ctx context.Context, err error) (bool, error) {
if err == nil {
return false, nil
}
switch e := err.(type) {
case *Error:
if RetryOnServerErrorEnabled {
if e.HTTPCode == 500 || e.HTTPCode == 502 || e.HTTPCode == 503 {
return true, e
}
}
case *BadResponseError:
if RetryOnServerErrorEnabled {
if e.HTTPCode == 500 || e.HTTPCode == 502 || e.HTTPCode == 503 {
return true, e
}
}
default:
return false, e
}
return false, err
}
// request sends a request to SLS.
// mock param only for test, default is []
func request(project *LogProject, method, uri string, headers map[string]string,
body []byte, mock ...interface{}) (*http.Response, error) {
var r *http.Response
var slsErr error
var err error
var mockErr *mockErrorRetry
project.init()
ctx, cancel := context.WithTimeout(context.Background(), project.retryTimeout)
defer cancel()
//fmt.Println("request ", project, method, uri, headers, body)
// all GET method is read function
if method == http.MethodGet {
err = RetryWithCondition(ctx, backoff.NewExponentialBackOff(), func() (bool, error) {
if len(mock) == 0 {
//fmt.Println("real request", project, method, uri, headers, body)
r, slsErr = realRequest(ctx, project, method, uri, headers, body)
//fmt.Println("real request done")
} else {
r, mockErr = nil, mock[0].(*mockErrorRetry)
mockErr.RetryCnt--
if mockErr.RetryCnt <= 0 {
r = &http.Response{}
slsErr = nil
return false, nil
}
slsErr = &mockErr.Err
}
return retryReadErrorCheck(ctx, slsErr)
})
} else {
err = RetryWithCondition(ctx, backoff.NewExponentialBackOff(), func() (bool, error) {
if len(mock) == 0 {
r, slsErr = realRequest(ctx, project, method, uri, headers, body)
} else {
r, mockErr = nil, mock[0].(*mockErrorRetry)
mockErr.RetryCnt--
if mockErr.RetryCnt <= 0 {
r = &http.Response{}
slsErr = nil
return false, nil
}
slsErr = &mockErr.Err
}
return retryWriteErrorCheck(ctx, slsErr)
})
}
if err != nil {
return r, err
}
return r, slsErr
}
// request sends a request to alibaba cloud Log Service.
// @note if error is nil, you must call http.Response.Body.Close() to finalize reader
func realRequest(ctx context.Context, project *LogProject, method, uri string, headers map[string]string,
body []byte) (*http.Response, error) {
// The caller should provide 'x-log-bodyrawsize' header
if _, ok := headers[HTTPHeaderBodyRawSize]; !ok {
return nil, NewClientError(fmt.Errorf("Can't find 'x-log-bodyrawsize' header"))
}
// SLS public request headers
baseURL := project.getBaseURL()
headers[HTTPHeaderHost] = baseURL
headers[HTTPHeaderAPIVersion] = version
if len(project.UserAgent) > 0 {
headers[HTTPHeaderUserAgent] = project.UserAgent
} else {
headers[HTTPHeaderUserAgent] = DefaultLogUserAgent
}
stsToken := project.SecurityToken
accessKeyID := project.AccessKeyID
accessKeySecret := project.AccessKeySecret
if project.credentialProvider != nil {
c, err := project.credentialProvider.GetCredentials()
if err != nil {
return nil, NewClientError(fmt.Errorf("fail to get credentials: %w", err))
}
stsToken = c.SecurityToken
accessKeyID = c.AccessKeyID
accessKeySecret = c.AccessKeySecret
}
// Access with token
if stsToken != "" {
headers[HTTPHeaderAcsSecurityToken] = stsToken
}
if body != nil {
if _, ok := headers[HTTPHeaderContentType]; !ok {
return nil, NewClientError(fmt.Errorf("Can't find 'Content-Type' header"))
}
}
for k, v := range project.InnerHeaders {
headers[k] = v
}
var signer Signer
if project.AuthVersion == AuthV4 {
headers[HTTPHeaderLogDate] = dateTimeISO8601()
signer = NewSignerV4(accessKeyID, accessKeySecret, project.Region)
} else if project.AuthVersion == AuthV0 {
signer = NewSignerV0()
} else {
headers[HTTPHeaderDate] = nowRFC1123()
signer = NewSignerV1(accessKeyID, accessKeySecret)
}
if err := signer.Sign(method, uri, headers, body); err != nil {
return nil, err
}
addHeadersAfterSign(project.CommonHeaders, headers)
// Initialize http request
reader := bytes.NewReader(body)
// Handle the endpoint
urlStr := fmt.Sprintf("%s%s", baseURL, uri)
req, err := http.NewRequest(method, urlStr, reader)
if err != nil {
return nil, NewClientError(err)
}
for k, v := range headers {
req.Header.Add(k, v)
}
if IsDebugLevelMatched(5) {
dump, e := httputil.DumpRequest(req, true)
if e != nil {
level.Info(Logger).Log("msg", e)
}
level.Info(Logger).Log("msg", "HTTP Request:\n%v", string(dump))
}
// Get ready to do request
resp, err := project.httpClient.Do(req)
if err != nil {
return nil, err
}
// Parse the sls error from body.
if resp.StatusCode != http.StatusOK {
err := &Error{}
err.HTTPCode = (int32)(resp.StatusCode)
defer resp.Body.Close()
buf, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
return nil, NewBadResponseError(ioErr.Error(), resp.Header, resp.StatusCode)
}
if jErr := json.Unmarshal(buf, err); jErr != nil {
return nil, NewBadResponseError(string(buf), resp.Header, resp.StatusCode)
}
err.RequestID = resp.Header.Get(RequestIDHeader)
return nil, err
}
if IsDebugLevelMatched(5) {
dump, e := httputil.DumpResponse(resp, true)
if e != nil {
level.Info(Logger).Log("msg", e)
}
level.Info(Logger).Log("msg", "HTTP Response:\n%v", string(dump))
}
return resp, nil
}