forked from sourcegraph/vcsstore
/
requests.go
249 lines (192 loc) · 5.36 KB
/
requests.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
package etcd
import (
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"net/url"
"path"
"strings"
"time"
)
// get issues a GET request
func (c *Client) get(key string, options options) (*RawResponse, error) {
// If consistency level is set to STRONG, append
// the `consistent` query string.
if c.config.Consistency == STRONG_CONSISTENCY {
options["consistent"] = true
}
str, err := options.toParameters(VALID_GET_OPTIONS)
if err != nil {
return nil, err
}
resp, err := c.sendKeyRequest("GET", key, str, nil)
if err != nil {
return nil, err
}
return resp, nil
}
// put issues a PUT request
func (c *Client) put(key string, value string, ttl uint64,
options options) (*RawResponse, error) {
str, err := options.toParameters(VALID_PUT_OPTIONS)
if err != nil {
return nil, err
}
resp, err := c.sendKeyRequest("PUT", key, str, buildValues(value, ttl))
if err != nil {
return nil, err
}
return resp, nil
}
// post issues a POST request
func (c *Client) post(key string, value string, ttl uint64) (*RawResponse, error) {
resp, err := c.sendKeyRequest("POST", key, "", buildValues(value, ttl))
if err != nil {
return nil, err
}
return resp, nil
}
// delete issues a DELETE request
func (c *Client) delete(key string, options options) (*RawResponse, error) {
str, err := options.toParameters(VALID_DELETE_OPTIONS)
if err != nil {
return nil, err
}
resp, err := c.sendKeyRequest("DELETE", key, str, nil)
if err != nil {
return nil, err
}
return resp, nil
}
// sendKeyRequest sends a HTTP request and returns a Response as defined by etcd
func (c *Client) sendKeyRequest(method string, key string, params string,
values url.Values) (*RawResponse, error) {
var req *http.Request
var resp *http.Response
var httpPath string
var err error
var b []byte
trial := 0
logger.Debugf("%s %s %s [%s]", method, key, params, c.cluster.Leader)
// Build the request path if no prefix exists
relativePath := path.Join(c.keyPrefix, key) + params
// if we connect to a follower, we will retry until we found a leader
for {
trial++
logger.Debug("begin trail ", trial)
if trial > 2*len(c.cluster.Machines) {
return nil, newError(ErrCodeEtcdNotReachable,
"Tried to connect to each peer twice and failed", 0)
}
if method == "GET" && c.config.Consistency == WEAK_CONSISTENCY {
// If it's a GET and consistency level is set to WEAK,
// then use a random machine.
httpPath = c.getHttpPath(true, relativePath)
} else {
// Else use the leader.
httpPath = c.getHttpPath(false, relativePath)
}
// Return a cURL command if curlChan is set
if c.cURLch != nil {
command := fmt.Sprintf("curl -X %s %s", method, httpPath)
for key, value := range values {
command += fmt.Sprintf(" -d %s=%s", key, value[0])
}
c.sendCURL(command)
}
logger.Debug("send.request.to ", httpPath, " | method ", method)
if values == nil {
req, _ = http.NewRequest(method, httpPath, nil)
} else {
req, _ = http.NewRequest(method, httpPath,
strings.NewReader(values.Encode()))
req.Header.Set("Content-Type",
"application/x-www-form-urlencoded; param=value")
}
// network error, change a machine!
if resp, err = c.httpClient.Do(req); err != nil {
logger.Debug("network error: ", err.Error())
c.cluster.switchLeader(trial % len(c.cluster.Machines))
time.Sleep(time.Millisecond * 200)
continue
}
if resp != nil {
logger.Debug("recv.response.from ", httpPath)
var ok bool
ok, b = c.handleResp(resp)
if !ok {
continue
}
logger.Debug("recv.success.", httpPath)
break
}
// should not reach here
// err and resp should not be nil at the same time
logger.Debug("error.from ", httpPath)
return nil, err
}
r := &RawResponse{
StatusCode: resp.StatusCode,
Body: b,
Header: resp.Header,
}
return r, nil
}
// handleResp handles the responses from the etcd server
// If status code is OK, read the http body and return it as byte array
// If status code is TemporaryRedirect, update leader.
// If status code is InternalServerError, sleep for 200ms.
func (c *Client) handleResp(resp *http.Response) (bool, []byte) {
defer resp.Body.Close()
code := resp.StatusCode
if code == http.StatusTemporaryRedirect {
u, err := resp.Location()
if err != nil {
logger.Warning(err)
} else {
c.cluster.updateLeaderFromURL(u)
}
return false, nil
} else if code == http.StatusInternalServerError {
time.Sleep(time.Millisecond * 200)
} else if validHttpStatusCode[code] {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false, nil
}
return true, b
}
logger.Warning("bad status code ", resp.StatusCode)
return false, nil
}
func (c *Client) getHttpPath(random bool, s ...string) string {
var machine string
if random {
machine = c.cluster.Machines[rand.Intn(len(c.cluster.Machines))]
} else {
machine = c.cluster.Leader
}
return machine + "/" + strings.Join(s, "/")
}
// buildValues builds a url.Values map according to the given value and ttl
func buildValues(value string, ttl uint64) url.Values {
v := url.Values{}
if value != "" {
v.Set("value", value)
}
if ttl > 0 {
v.Set("ttl", fmt.Sprintf("%v", ttl))
}
return v
}
// convert key string to http path exclude version
// for example: key[foo] -> path[foo]
// key[] -> path[/]
func keyToPath(key string) string {
clean := path.Clean(key)
if clean == "" || clean == "." {
return "/"
}
return clean
}