This repository has been archived by the owner on Apr 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
http.go
398 lines (331 loc) · 10.7 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
389
390
391
392
393
394
395
396
397
398
package canoe
import (
"bytes"
"encoding/json"
"fmt"
cTypes "github.com/compose/canoe/types"
eTypes "github.com/coreos/etcd/pkg/types"
"github.com/coreos/etcd/raft/raftpb"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"net"
"net/http"
"net/url"
"strconv"
)
var peerEndpoint = "/peers"
func (rn *Node) peerAPI() *mux.Router {
r := mux.NewRouter()
r.HandleFunc(peerEndpoint, rn.peerAddHandlerFunc()).Methods("POST")
r.HandleFunc(peerEndpoint, rn.peerDeleteHandlerFunc()).Methods("DELETE")
r.HandleFunc(peerEndpoint, rn.peerMembersHandlerFunc()).Methods("GET")
return r
}
func (rn *Node) serveHTTP() error {
router := rn.peerAPI()
ln, err := newStoppableListener(fmt.Sprintf(":%d", rn.configPort), rn.stopc)
if err != nil {
panic(err)
}
err = (&http.Server{Handler: router}).Serve(ln)
select {
case <-rn.stopc:
return nil
default:
return errors.Wrap(err, "Error serving HTTP API")
}
}
func (rn *Node) serveRaft() error {
ln, err := newStoppableListener(fmt.Sprintf(":%d", rn.raftPort), rn.stopc)
if err != nil {
return errors.Wrap(err, "Error creating a new stoppable listener")
}
err = (&http.Server{Handler: rn.transport.Handler()}).Serve(ln)
select {
case <-rn.stopc:
return nil
default:
return errors.Wrap(err, "Error serving raft http server")
}
}
func (rn *Node) peerMembersHandlerFunc() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
rn.handlePeerMembersRequest(w, req)
}
}
func (rn *Node) handlePeerMembersRequest(w http.ResponseWriter, req *http.Request) {
if !rn.initialized {
rn.writeNodeNotReady(w)
} else {
membersResp := &cTypes.ConfigMembershipResponseData{
cTypes.ConfigPeerData{
RaftPort: rn.raftPort,
ConfigurationPort: rn.configPort,
ID: rn.id,
RemotePeers: rn.peerMap,
},
}
rn.writeSuccess(w, membersResp)
}
}
func (rn *Node) peerDeleteHandlerFunc() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
rn.handlePeerDeleteRequest(w, req)
}
}
func (rn *Node) handlePeerDeleteRequest(w http.ResponseWriter, req *http.Request) {
if rn.canAlterPeer() {
var delReq cTypes.ConfigDeletionRequest
if err := json.NewDecoder(req.Body).Decode(&delReq); err != nil {
rn.writeError(w, http.StatusBadRequest, err)
}
confChange := &raftpb.ConfChange{
NodeID: delReq.ID,
}
if err := rn.proposePeerDeletion(confChange, false); err != nil {
rn.writeError(w, http.StatusInternalServerError, err)
}
rn.writeSuccess(w, nil)
} else {
rn.writeNodeNotReady(w)
}
}
// wrapper to allow rn state to persist through handler func
func (rn *Node) peerAddHandlerFunc() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
rn.handlePeerAddRequest(w, req)
}
}
// if bootstrap node or in a cluster then accept these attempts,
// and wait for the message to be committed(err or retry after timeout?)
//
// Otherwise respond with an error that this node isn't in a state to add
// members
func (rn *Node) handlePeerAddRequest(w http.ResponseWriter, req *http.Request) {
if rn.canAlterPeer() {
var addReq cTypes.ConfigAdditionRequest
if err := json.NewDecoder(req.Body).Decode(&addReq); err != nil {
rn.writeError(w, http.StatusBadRequest, err)
}
var reqHost string
if addReq.Host == "" {
var err error
reqHost, _, err = net.SplitHostPort(req.RemoteAddr)
if err != nil {
rn.writeError(w, 500, err)
}
} else {
reqHost = addReq.Host
}
confContext := cTypes.Peer{
IP: reqHost,
RaftPort: addReq.RaftPort,
ConfigurationPort: addReq.ConfigurationPort,
}
confContextData, err := json.Marshal(confContext)
if err != nil {
rn.writeError(w, http.StatusInternalServerError, err)
}
confChange := &raftpb.ConfChange{
NodeID: addReq.ID,
Context: confContextData,
}
if err := rn.proposePeerAddition(confChange, false); err != nil {
rn.writeError(w, http.StatusInternalServerError, err)
}
addResp := &cTypes.ConfigAdditionResponseData{
cTypes.ConfigPeerData{
RaftPort: rn.raftPort,
ConfigurationPort: rn.configPort,
ID: rn.id,
RemotePeers: rn.peerMap,
},
}
rn.writeSuccess(w, addResp)
} else {
rn.writeNodeNotReady(w)
}
}
// TODO: Figure out how to handle these errs rather than just continue...
// thought of having a slice of accumulated errors?
// Or log.Warning on all failed attempts and if unsuccessful return a general failure
// error
func (rn *Node) requestRejoinCluster() error {
var resp *http.Response
var respData cTypes.ConfigServiceResponse
if len(rn.bootstrapPeers) == 0 {
return nil
}
for _, peer := range rn.bootstrapPeers {
peerAPIURL := fmt.Sprintf("%s%s", peer, peerEndpoint)
resp, err := http.Get(peerAPIURL)
if err != nil {
rn.logger.Warning(err.Error())
continue
//return err
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&respData); err != nil {
rn.logger.Warning(err.Error())
//return err
}
if respData.Status == peerServiceStatusError {
continue
} else if respData.Status == peerServiceStatusSuccess {
var peerData cTypes.ConfigMembershipResponseData
if err := json.Unmarshal(respData.Data, &peerData); err != nil {
return errors.Wrap(err, "Error unmarshaling peer membership data")
}
return rn.addPeersFromRemote(peer, &peerData.ConfigPeerData)
}
}
if respData.Status == peerServiceStatusError {
return fmt.Errorf("Error %d - %s", resp.StatusCode, respData.Message)
}
// TODO: Should return the general error from here
return errors.New("Couldn't connect to thingy")
}
func (rn *Node) addPeersFromRemote(remotePeer string, remoteMemberResponse *cTypes.ConfigPeerData) error {
peerURL, err := url.Parse(remotePeer)
if err != nil {
return errors.Wrap(err, "Error parsing remote peer string for URL")
}
reqHost, _, err := net.SplitHostPort(peerURL.Host)
if err != nil {
return err
}
addURL := fmt.Sprintf("http://%s",
net.JoinHostPort(reqHost, strconv.Itoa(remoteMemberResponse.RaftPort)))
rn.transport.AddPeer(eTypes.ID(remoteMemberResponse.ID), []string{addURL})
rn.logger.Info("Adding peer from HTTP request: %x\n", remoteMemberResponse.ID)
rn.peerMap[remoteMemberResponse.ID] = cTypes.Peer{
IP: reqHost,
RaftPort: remoteMemberResponse.RaftPort,
ConfigurationPort: remoteMemberResponse.ConfigurationPort,
}
rn.logger.Debugf("Current Peer Map: %v", rn.peerMap)
for id, context := range remoteMemberResponse.RemotePeers {
if id != rn.id {
addURL := fmt.Sprintf("http://%s", net.JoinHostPort(context.IP, strconv.Itoa(context.RaftPort)))
rn.transport.AddPeer(eTypes.ID(id), []string{addURL})
rn.logger.Info("Adding peer from HTTP request: %x\n", id)
}
rn.peerMap[id] = context
rn.logger.Debugf("Current Peer Map: %v", rn.peerMap)
}
return nil
}
func (rn *Node) requestSelfAddition() error {
var resp *http.Response
var respData cTypes.ConfigServiceResponse
reqData := cTypes.ConfigAdditionRequest{
ID: rn.id,
RaftPort: rn.raftPort,
ConfigurationPort: rn.configPort,
}
for _, peer := range rn.bootstrapPeers {
mar, err := json.Marshal(reqData)
if err != nil {
rn.logger.Warning(err.Error())
//return err
}
reader := bytes.NewReader(mar)
peerAPIURL := fmt.Sprintf("%s%s", peer, peerEndpoint)
resp, err = http.Post(peerAPIURL, "application/json", reader)
if err != nil {
rn.logger.Warning(err.Error())
return err
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&respData); err != nil {
rn.logger.Warning(err.Error())
// return err
}
if respData.Status == peerServiceStatusError {
continue
} else if respData.Status == peerServiceStatusSuccess {
// this ought to work since it should be added to cluster now
var peerData cTypes.ConfigAdditionResponseData
if err := json.Unmarshal(respData.Data, &peerData); err != nil {
return errors.Wrap(err, "Error unmarshaling peer addition response")
}
return errors.Wrap(rn.addPeersFromRemote(peer, &peerData.ConfigPeerData), "Error add peer from remote data")
}
}
if respData.Status == peerServiceStatusError {
return fmt.Errorf("Error %d - %s", resp.StatusCode, respData.Message)
}
return errors.New("No available nodey thingy")
}
func (rn *Node) requestSelfDeletion() error {
var resp *http.Response
var respData cTypes.ConfigServiceResponse
reqData := cTypes.ConfigDeletionRequest{
ID: rn.id,
}
for id, peerData := range rn.peerMap {
if id == rn.id {
continue
}
mar, err := json.Marshal(reqData)
if err != nil {
return errors.Wrap(err, "Error marshalling peer deletion request")
}
reader := bytes.NewReader(mar)
peerAPIURL := fmt.Sprintf("http://%s%s",
net.JoinHostPort(peerData.IP, strconv.Itoa(peerData.ConfigurationPort)),
peerEndpoint)
req, err := http.NewRequest("DELETE", peerAPIURL, reader)
if err != nil {
return errors.Wrap(err, "Error creating new request for deleting peer")
}
req.Header.Set("Content-Type", "application/json")
resp, err = (&http.Client{}).Do(req)
if err != nil {
return errors.Wrap(err, "Error sending request to delete myself")
}
defer resp.Body.Close()
if err = json.NewDecoder(resp.Body).Decode(&respData); err != nil {
return errors.Wrap(err, "Error decoding response for self deletion")
}
if respData.Status == peerServiceStatusSuccess {
return nil
}
}
if respData.Status == peerServiceStatusError {
return fmt.Errorf("Error %d - %s", resp.StatusCode, respData.Message)
}
return nil
}
var peerServiceStatusSuccess = "success"
var peerServiceStatusError = "error"
var peerServiceNodeNotReady = "Invalid Node"
func (rn *Node) writeSuccess(w http.ResponseWriter, body interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var respData []byte
var err error
if body != nil {
respData, err = json.Marshal(body)
if err != nil {
rn.logger.Errorf(err.Error())
}
}
if err = json.NewEncoder(w).Encode(cTypes.ConfigServiceResponse{Status: peerServiceStatusSuccess, Data: respData}); err != nil {
rn.logger.Errorf(err.Error())
}
}
func (rn *Node) writeError(w http.ResponseWriter, code int, err error) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(cTypes.ConfigServiceResponse{Status: peerServiceStatusError, Message: err.Error()}); err != nil {
rn.logger.Errorf(err.Error())
}
}
func (rn *Node) writeNodeNotReady(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
if err := json.NewEncoder(w).Encode(cTypes.ConfigServiceResponse{Status: peerServiceStatusError, Message: peerServiceNodeNotReady}); err != nil {
rn.logger.Errorf(err.Error())
}
}