/
transport.go
252 lines (209 loc) · 6.2 KB
/
transport.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
package raft
import (
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
)
const (
PeerSetConfigurationPath = "/raft/setconfiguration"
PeerAppendEntriesPath = "/raft/appendentries"
PeerIDPath = "/raft/id"
PeerCommandPath = "/raft/command"
PeerRequestVotePath = "/raft/requestvote"
)
var (
emptyAppendEntriesResponse bytes.Buffer
emptyRequestVoteResponse bytes.Buffer
)
func init() {
json.NewEncoder(&emptyAppendEntriesResponse).Encode(appendEntriesResponse{})
json.NewEncoder(&emptyRequestVoteResponse).Encode(requestVoteResponse{})
gob.Register(&HTTPPeer{})
}
func idHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprint(s.id)))
}
}
func appendEntriesHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var ae appendEntries
if err := json.NewDecoder(r.Body).Decode(&ae); err != nil {
http.Error(w, emptyAppendEntriesResponse.String(), http.StatusBadRequest)
return
}
aer := s.appendEntries(ae)
if err := json.NewEncoder(w).Encode(aer); err != nil {
http.Error(w, emptyAppendEntriesResponse.String(), http.StatusInternalServerError)
return
}
}
}
func requestVoteHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var rv requestVote
if err := json.NewDecoder(r.Body).Decode(&rv); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusBadRequest)
return
}
rvr := s.requestVote(rv)
if err := json.NewEncoder(w).Encode(rvr); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
return
}
}
}
func commandHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
cmd, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "", http.StatusBadRequest)
return
}
response := make(chan []byte, 1)
if err := s.Command(cmd, response); err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
resp, ok := <-response
if !ok {
http.Error(w, "", http.StatusInternalServerError)
return
}
w.Write(resp)
}
}
func setConfigurationHandler(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var pm peerMap
if err := gob.NewDecoder(r.Body).Decode(&pm); err != nil {
errBuf, _ := json.Marshal(commaError{err.Error(), false})
http.Error(w, string(errBuf), http.StatusBadRequest)
return
}
if err := s.SetConfiguration(explodePeerMap(pm)...); err != nil {
errBuf, _ := json.Marshal(commaError{err.Error(), false})
http.Error(w, string(errBuf), http.StatusInternalServerError)
return
}
respBuf, _ := json.Marshal(commaError{"", true})
w.Write(respBuf)
}
}
type commaError struct {
Error string `json:"error,omitempty"`
Success bool `json:"success,omitempty"`
}
type HTTPPeer struct {
RemoteID uint64
URL *url.URL
}
func (p *HTTPPeer) id() uint64 { return p.RemoteID }
func (p *HTTPPeer) callAppendEntries(ae appendEntries) appendEntriesResponse {
var aer appendEntriesResponse
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(ae); err != nil {
log.Printf("Raft: HTTP Peer: AppendEntries: encode request: %s", err)
return aer
}
var resp bytes.Buffer
if err := p.rpc(&body, PeerAppendEntriesPath, &resp); err != nil {
log.Printf("Raft: HTTP Peer: AppendEntries: during RPC: %s", err)
return aer
}
if err := json.Unmarshal(resp.Bytes(), &aer); err != nil {
log.Printf("Raft: HTTP Peer: AppendEntries: decode response: %s", err)
return aer
}
return aer
}
func (p *HTTPPeer) callRequestVote(rv requestVote) requestVoteResponse {
var rvr requestVoteResponse
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(rv); err != nil {
log.Printf("Raft: HTTP Peer: RequestVote: encode request: %s", err)
return rvr
}
var resp bytes.Buffer
if err := p.rpc(&body, PeerRequestVotePath, &resp); err != nil {
log.Printf("Raft: HTTP Peer: RequestVote: during RPC: %s", err)
return rvr
}
if err := json.Unmarshal(resp.Bytes(), &rvr); err != nil {
log.Printf("Raft: HTTP Peer: RequestVote: decode response: %s", err)
return rvr
}
return rvr
}
func (p *HTTPPeer) callCommand(cmd []byte, response chan<- []byte) error {
errChan := make(chan error)
go func() {
var responseBuf bytes.Buffer
err := p.rpc(bytes.NewBuffer(cmd), PeerCommandPath, &responseBuf)
errChan <- err
if err != nil {
return
}
response <- responseBuf.Bytes()
}()
return <-errChan // TODO timeout?
}
func (p *HTTPPeer) callSetConfiguration(peers ...Peer) error {
buf := &bytes.Buffer{}
if err := gob.NewEncoder(buf).Encode(&peers); err != nil {
log.Printf("Raft: HTTP Peer: SetConfiguration: encode request: %s", err)
return err
}
var resp bytes.Buffer
if err := p.rpc(buf, PeerSetConfigurationPath, &resp); err != nil {
log.Printf("Raft: HTTP Peer: SetConfiguration: during RPC: %s", err)
return err
}
var commaErr commaError
if err := json.Unmarshal(resp.Bytes(), &commaErr); err != nil {
log.Printf("Raft: HTTP Peer: SetConfiguration: decode response: %s", err)
return err
}
if !commaErr.Success {
return fmt.Errorf(commaErr.Error)
}
return nil
}
func SetupServeMux(mux *http.ServeMux, s *Server) {
mux.HandleFunc(PeerIDPath, idHandler(s))
mux.HandleFunc(PeerAppendEntriesPath, appendEntriesHandler(s))
mux.HandleFunc(PeerRequestVotePath, requestVoteHandler(s))
mux.HandleFunc(PeerCommandPath, commandHandler(s))
mux.HandleFunc(PeerSetConfigurationPath, setConfigurationHandler(s))
}
func (p *HTTPPeer) rpc(request *bytes.Buffer, path string, response *bytes.Buffer) error {
url := *p.URL
url.Path = path
resp, err := http.Post(url.String(), "application/json", request)
if err != nil {
log.Printf("Raft: HTTP Peer: rpc POST: %s", err)
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP %d", resp.StatusCode)
}
n, err := io.Copy(response, resp.Body)
if err != nil {
return err
}
if l := response.Len(); n < int64(l) {
return fmt.Errorf("short read (%d < %d)", n, l)
}
return nil
}