-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers.go
220 lines (203 loc) · 7.2 KB
/
handlers.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
package dinghy
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
)
const (
// RouteAppendEntries for append entries requests.
RouteAppendEntries = "/appendentries"
// RouteID for id requests.
RouteID = "/id"
// RouteRequestVote for request vote requests.
RouteRequestVote = "/requestvote"
// RouteStatus will render the current nodes full state.
RouteStatus = "/status"
// RouteStepDown to force a node to step down.
RouteStepDown = "/stepdown"
)
var (
emptyAppendEntriesResponse bytes.Buffer
emptyRequestVoteResponse bytes.Buffer
)
func init() {
if err := json.NewEncoder(&emptyAppendEntriesResponse).Encode(appendEntriesResponse{}); err != nil {
log.Fatalln("error encoding json:", err)
}
if err := json.NewEncoder(&emptyRequestVoteResponse).Encode(requestVoteResponse{}); err != nil {
log.Fatalln("error encoding json:", err)
}
}
// Route holds path and handler information.
type Route struct {
Path string
Handler func(http.ResponseWriter, *http.Request)
}
// Routes create the routes required for leader election.
func (d *Dinghy) Routes() []*Route {
routes := []*Route{
&Route{d.routePrefix + RouteID, d.IDHandler()},
&Route{d.routePrefix + RouteRequestVote, d.RequestVoteHandler()},
&Route{d.routePrefix + RouteAppendEntries, d.AppendEntriesHandler()},
&Route{d.routePrefix + RouteStatus, d.StatusHandler()},
&Route{d.routePrefix + RouteStepDown, d.StepDownHandler()},
}
return routes
}
// StepDownHandler (POST) will force the node to step down to a follower state.
func (d *Dinghy) StepDownHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
d.State.State(StateFollower)
fmt.Fprintln(w, d.State)
}
}
// StatusHandler (GET) returns the nodes full state.
func (d *Dinghy) StatusHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
fmt.Fprintln(w, d.State)
}
}
// IDHandler (GET) returns the nodes id.
func (d *Dinghy) IDHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
fmt.Fprintln(w, d.State.ID())
}
}
// RequestVoteHandler (POST) handles requests for votes
func (d *Dinghy) RequestVoteHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer r.Body.Close()
}
if r.Method != "POST" {
d.logger.Errorf("invalid method %s", r.Method)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var rv requestVoteRequest
if err := json.NewDecoder(r.Body).Decode(&rv); err != nil {
d.logger.Errorf("%s", err)
http.Error(w, emptyRequestVoteResponse.String(), http.StatusBadRequest)
return
}
switch {
case rv.Term < d.State.Term():
// The request is from an old term so reject
d.logger.Printf("got RequestVote request from older term, rejecting %+v %s", rv, d.State)
rvResp := requestVoteResponse{
Term: d.State.Term(),
VoteGranted: false,
Reason: fmt.Sprintf("term %d < %d", rv.Term, d.State.Term()),
}
if d.State.State() == StateLeader {
rvResp.Reason = "already leader"
}
if err := json.NewEncoder(w).Encode(rvResp); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
}
return
case (d.State.VotedFor() != NoVote) && (d.State.VotedFor() != rv.CandidateID):
// don't double vote if already voted for a term
d.logger.Printf("got RequestVote request but already voted, rejecting %+v %s", rv, d.State)
rvResp := requestVoteResponse{
Term: d.State.Term(),
VoteGranted: false,
Reason: fmt.Sprintf("already cast vote for %d", d.State.VotedFor()),
}
if err := json.NewEncoder(w).Encode(rvResp); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
}
return
case rv.Term > d.State.Term():
// Step down and reset state on newer term.
d.logger.Printf("got RequestVote request from newer term, stepping down %+v %s", rv, d.State)
d.State.StepDown(rv.Term)
d.State.LeaderID(UnknownLeaderID)
}
// ok and vote for candidate
// reset election timeout
d.logger.Printf("got RequestVote request, voting for candidate id %d %s", rv.CandidateID, d.State)
d.State.VotedFor(rv.CandidateID)
//defer d.State.HeartbeatReset(true)
rvResp := requestVoteResponse{
Term: d.State.Term(),
VoteGranted: true,
}
if err := json.NewEncoder(w).Encode(rvResp); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
}
return
}
}
// AppendEntriesHandler (POST) handles append entry requests
func (d *Dinghy) AppendEntriesHandler() func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.Body != nil {
defer r.Body.Close()
}
if r.Method != "POST" {
d.logger.Errorf("invalid method %s", r.Method)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var ae AppendEntriesRequest
if err := json.NewDecoder(r.Body).Decode(&ae); err != nil {
d.logger.Errorf("%s", err)
http.Error(w, emptyRequestVoteResponse.String(), http.StatusBadRequest)
return
}
// There are a few cases here:
// 1. The request is from an old term so reject
// 2. The request is from a newer term so step down
// 3. If we are a follower and get an append entries continue on with success
// 4. If we are not a follower and get an append entries, it means there is
// another leader already and we should step down.
switch {
case ae.Term < d.State.Term():
d.logger.Printf("got AppendEntries request from older term, rejecting %+v %s", ae, d.State)
aeResp := appendEntriesResponse{
Term: d.State.Term(),
Success: false,
Reason: fmt.Sprintf("term %d < %d", ae.Term, d.State.Term()),
}
if err := json.NewEncoder(w).Encode(aeResp); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
}
return
case ae.Term > d.State.Term():
d.logger.Printf("got AppendEntries request from newer term, stepping down %+v %s", ae, d.State)
d.State.StepDown(ae.Term)
case ae.Term == d.State.Term():
// ignore request to self and only step down if not in follower state.
if ae.LeaderID != d.State.ID() && d.State.State() != StateFollower {
d.logger.Printf("got AppendEntries request from another leader with the same term, stepping down %+v %s", ae, d.State)
d.State.StepDown(ae.Term)
}
}
// ok
d.State.LeaderID(ae.LeaderID)
d.State.AppendEntriesEvent(&ae)
aeResp := appendEntriesResponse{
Term: d.State.Term(),
Success: true,
}
if err := json.NewEncoder(w).Encode(aeResp); err != nil {
http.Error(w, emptyRequestVoteResponse.String(), http.StatusInternalServerError)
}
return
}
}