forked from galaxydi/go-loghub
-
Notifications
You must be signed in to change notification settings - Fork 113
/
request.go
236 lines (213 loc) · 5.86 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
package sls
import (
"bytes"
"crypto/md5"
"encoding/json"
"fmt"
"github.com/go-kit/kit/log/level"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/cenkalti/backoff"
"golang.org/x/net/context"
)
// timeout configs
var (
defaultRequestTimeout = 10 * time.Second
defaultRetryTimeout = 30 * time.Second
defaultHttpClient = &http.Client{
Timeout: defaultRequestTimeout,
}
)
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["x-log-bodyrawsize"]; !ok {
return nil, NewClientError(fmt.Errorf("Can't find 'x-log-bodyrawsize' header"))
}
// SLS public request headers
// var hostStr string
// if len(project.Name) == 0 {
// hostStr = project.Endpoint
// } else {
// hostStr = project.Name + "." + project.Endpoint
// }
baseURL := project.getBaseURL()
headers["Host"] = baseURL
headers["Date"] = nowRFC1123()
headers["x-log-apiversion"] = version
headers["x-log-signaturemethod"] = signatureMethod
if len(project.UserAgent) > 0 {
headers["User-Agent"] = project.UserAgent
} else {
headers["User-Agent"] = defaultLogUserAgent
}
// Access with token
if project.SecurityToken != "" {
headers["x-acs-security-token"] = project.SecurityToken
}
if body != nil {
bodyMD5 := fmt.Sprintf("%X", md5.Sum(body))
headers["Content-MD5"] = bodyMD5
if _, ok := headers["Content-Type"]; !ok {
return nil, NewClientError(fmt.Errorf("Can't find 'Content-Type' header"))
}
}
// Calc Authorization
// Authorization = "SLS <AccessKeyId>:<Signature>"
digest, err := signature(project.AccessKeySecret, method, uri, headers)
if err != nil {
return nil, NewClientError(err)
}
auth := fmt.Sprintf("SLS %v:%v", project.AccessKeyID, digest)
headers["Authorization"] = auth
// 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
}