-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft.go
377 lines (331 loc) · 7.49 KB
/
raft.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
package raft
import (
"context"
"errors"
"labrpc"
"sync"
"time"
)
// raft 节点的3种状态的管理
// 日志状态机的管理
//
//
const (
LeaderState = iota
FollowerState
CandicateState
)
const (
votedInitValue = -1
)
type RPCConn struct {
Id int
conns map[int]RPCConn
}
type Raft struct {
me int
peers []*labrpc.ClientEnd
currentTerm int
votedFor int
log *log
commitIndex int
lastApplied int
//follow two fields for leader
nextIndex []int
matchIndex []int
// buffered channel
// explain why using blockEventQ channel
// server is only in a single state, each state Concurrently handle different rpc request
// use channel we can decrease using the lock to protect state,logs etc
group sync.WaitGroup
blockEventQ chan *message
electionTimeout time.Duration // electionTimeout election timeout
mutex sync.Mutex
state int // state of the
applyNotice chan struct{}
exitFlag chan struct{} // stop signal channel, while stop, close(exitFlag)
updateStateFunc []func()
//debug
testIndex int
}
func init() {
}
func (rf *Raft) updateState(state int, callback ...bool) {
if state == rf.state {
return
}
rf.state = state
if state == LeaderState {
rf.nextIndex = make([]int, len(rf.peers))
rf.matchIndex = make([]int, len(rf.peers))
for i := 0; i < len(rf.peers); i++ {
rf.nextIndex[i] = rf.log.length
rf.matchIndex[i] = 0
}
} else if state == FollowerState {
rf.votedFor = -1
} else if state == CandicateState {
rf.votedFor = -1
}
if true {
if rf.state != LeaderState {
return
}
// todo 仅仅作为调试
// update state hook functions for debug
for _, f := range rf.updateStateFunc {
f()
}
}
}
func (rf *Raft) QuorumSize() int {
return len(rf.peers)/2 + 1
}
const (
HeartSt = int64(80)
HeartEnd = int64(100)
VoteSt = int64(200)
VoteEnd = int64(300)
)
func (rf *Raft) LeaderLoop() {
// todo leader state loop
timeout := randTime(HeartSt, HeartEnd)
heartbeat := true
//var num = 0
appResp := make(chan appendResp)
logCommit := make(map[int]bool)
ctx, _ := context.WithCancel(context.Background())
//go func() {
// // this goroutine mock the client sned log
// t := randTime(int64(700), int64(1500))
// for {
// select {
// case <-rf.exitFlag:
// return
// // operate log
// case <-t:
// index, _ := rf.log.lastInfo()
// rf.log.addEntry(EntryLog{
// Index: index + 1,
// Term: rf.currentTerm,
// })
//
// logMockChan <- struct{}{}
// return
// //t = randTime(int64(700), int64(1500))
// }
// }
//}()
for rf.state == LeaderState {
select {
case <-rf.exitFlag:
return
default:
}
if heartbeat {
heartbeat = false
for i := 0; i < len(rf.peers); i++ {
if i == rf.me {
continue
}
rf.makeAppendRequest(ctx, i, appResp)
}
}
select {
case reply := <-appResp:
if reply.resp.Term > rf.currentTerm {
rf.updateState(FollowerState)
rf.votedFor = -1
return
}
rf.handleAppendRequest(ctx, logCommit, reply, appResp)
case <-timeout:
heartbeat = true
timeout = randTime(HeartSt, HeartEnd)
case event := <-rf.blockEventQ:
switch event.args.(type) {
case *LogClientMessage:
index, _ := rf.log.lastInfo()
rf.log.addEntry(EntryLog{
Index: index + 1,
Term: rf.currentTerm,
})
rf.updateNextByClientLog()
// no network delay or any Network partition, leader will not receive
// vote and append log info
}
}
}
}
func (rf *Raft) State() int {
return rf.state
}
func (rf *Raft) FollowerLoop() {
// todo
var timeoutChan <-chan time.Time
if rf.me == 5 {
timeoutChan = randTime(VoteSt, VoteEnd)
} else {
timeoutChan = randTime(VoteSt, VoteEnd)
}
for rf.state == FollowerState {
select {
case <-rf.exitFlag:
return
default:
}
select {
case event := <-rf.blockEventQ:
var (
err error
update bool
)
switch args := event.args.(type) {
case requestVoteArgs:
var rp responseVoteArgs
rp, update = rf.RequestVoteResponse(&args)
//event.reply = rp
rpPtr := event.reply.(*responseVoteArgs)
*rpPtr = rp
case requestAppendEntries:
// todo handle append Entries
var resp responseAppendEntries
resp, update = rf.RequestAppendEntry(&args)
rpPtr := event.reply.(*responseAppendEntries)
*rpPtr = resp
default:
err = errors.New("follower receve unsupport message")
}
// rpc select the err chan to judge whether response over
event.err <- err
if update {
timeoutChan = randTime(int64(200), int64(300))
}
case <-timeoutChan:
rf.updateState(CandicateState)
return
}
}
}
func (rf *Raft) makeVote(ctx context.Context, in22 int, resp chan *responseVoteArgs) {
lastIndex, lastTerm := rf.log.lastInfo()
args := requestVoteArgs{
Term: rf.currentTerm,
CandicateId: rf.me,
LastLogoTerm: lastTerm,
LastLogIndex: lastIndex,
}
replay2 := &responseVoteArgs{}
if ok := rf.sendVoteRequest(ctx, in22, args, replay2); !ok {
return
}
select {
case <-ctx.Done():
return
default:
}
//if replay.VoteGranted {
// lock2.Lock()
// *voteMap = append(*voteMap, debug{me:in22, term:replay.Term})
// lock2.Unlock()
//}
resp <- replay2
}
func (rf *Raft) CandicateLoop() {
var (
ctx context.Context
)
timeChan := randTime(VoteSt, VoteEnd)
voteFor := true
var number int32 = 0
var resp2 chan *responseVoteArgs
for rf.state == CandicateState {
if voteFor {
//rf.blockEventQ = make(chan *message, 100)
resp2 = make(chan *responseVoteArgs, 100)
number = 1
voteFor = false
rf.currentTerm++
rf.votedFor = rf.me
ctx, _ = context.WithCancel(context.Background())
//lastIndex, lastTerm := rf.log.lastInfo()
for index := 0; index < len(rf.peers); index++ {
if index != rf.me {
go rf.makeVote(ctx, index, resp2)
}
}
}
if number >= int32(rf.QuorumSize()) {
rf.updateState(LeaderState)
//cancel()
return
}
select {
case <-rf.exitFlag:
return
case <-timeChan:
voteFor = true
timeChan = randTime(VoteSt, VoteEnd)
case res := <-resp2:
if res.Term > rf.currentTerm {
// rules for all servers
rf.updateCurrentTerm(res.Term)
// todo common => InitState(FollowerState)
rf.updateState(FollowerState)
rf.votedFor = -1
return
}
if res.VoteGranted && res.Term == rf.currentTerm {
number += 1
}
case event := <-rf.blockEventQ:
// just like followers, but never update timeChan
var err error = nil
switch args := event.args.(type) {
case requestVoteArgs:
//var rp responseVoteArgs
// candicate handle the vote args never success, because it vote it self
// and ignore the update field
rp, _ := rf.RequestVoteResponse(&args)
rpPtr := event.reply.(*responseVoteArgs)
*rpPtr = rp
case requestAppendEntries:
// receive the append log request, candicate => follower
// whill leader break down, costs less time to vote a leader
resp, _ := rf.RequestAppendEntry(&args)
rpPtr := event.reply.(*responseAppendEntries)
*rpPtr = resp
rf.updateState(FollowerState)
return
default:
err = errors.New("follower receve unsupport message")
}
event.err <- err
}
}
}
func (rf *Raft) Wait() {
select {
case <-rf.exitFlag:
}
}
// StateLoop
func (rf *Raft) StateLoop() {
for {
// exit the server
select {
case <-rf.exitFlag:
return
default:
}
// any time, server has only state
switch rf.state {
case LeaderState:
rf.LeaderLoop()
case FollowerState:
rf.FollowerLoop()
case CandicateState:
rf.CandicateLoop()
}
}
}