-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
352 lines (318 loc) · 7.53 KB
/
main.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
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"net/rpc"
"strings"
"time"
)
type State int
const (
Leader = iota + 1
Candidate
Follower
)
type node struct {
id int
connect bool
address string
}
type LogEntry struct {
LogTerm int
LogIndex int
LogCmd any
}
type Raft struct {
id int
nodes map[int]*node
state State
currentTerm int
voteFor int
voteCount int
log []LogEntry
// 被提交的最大索引
commitIndex int
// 被应用到状态机的最大索引
lastApplied int
// 保存需要发送给每个节点的下一个条目索引
nextIndex []int
// 保存已经复制给每个节点日志的最高索引
matchIndex []int
heartbeat chan bool
toLeaderC chan bool
}
type VoteArgs struct {
Term, Index, Candidate int
}
type VoteReply struct {
Term int
VoteGrant bool
}
type HeartbeatArgs struct {
Term int
Leader int
//新日志之前的索引值
PrevLogIndex int
//新日志之前的任期
PrevLogTerm int
Entries []LogEntry
//leader 已经commit的索引值
LeaderCommit int
}
type HeartbeatReply struct {
Success bool
Term int
//如果 Follower Index小于Leader Index ,会告诉Leader下一次发送的索引位置
NextIndex int
}
func newNode(address string, id int) *node {
n := &node{
id: id,
address: address,
}
return n
}
// RequestVote This is the RPC method that is called by other nodes when they want to vote for this node.
func (r *Raft) RequestVote(args VoteArgs, reply *VoteReply) error {
log.Printf("接受到请求选票调用,节点为:%v,Term为: %v", args.Candidate, args.Term)
if r.currentTerm > args.Term {
reply.Term = r.currentTerm
reply.VoteGrant = false
return nil
}
if r.voteFor == -1 {
r.currentTerm = args.Term
r.voteFor = args.Candidate
reply.Term = r.currentTerm
reply.VoteGrant = true
}
return nil
}
// HeartBeat The above code is handling the heartbeat message from the leader.
func (r *Raft) HeartBeat(args HeartbeatArgs, reply *HeartbeatReply) error {
log.Printf("接受到心跳调用,节点为:%v,Term为: %v\n", args.Leader, args.Term)
if r.currentTerm > args.Term {
reply.Success = false
reply.Term = r.currentTerm
return nil
}
r.heartbeat <- true
//处理日志
if len(args.Entries) == 0 {
reply.Success = false
reply.Term = r.currentTerm
return nil
}
//如果当前的日志参数小于心跳中之前的日志索引的话
//说明断连过 通知leader需要进行日志的回溯
if r.lastIndex() < args.PrevLogIndex {
reply.Success = false
reply.Term = r.currentTerm
reply.NextIndex = r.lastIndex() + 1
return nil
}
r.log = append(r.log, args.Entries...)
r.commitIndex = r.lastIndex()
reply.Success = true
reply.Term = r.currentTerm
reply.NextIndex = r.commitIndex + 1
return nil
}
func (r *Raft) rpc(port string) {
err := rpc.Register(r)
if err != nil {
log.Fatal("rpc enable failed: ", err)
}
rpc.HandleHTTP()
go func() {
err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal("listen failed: ", err)
}
}()
}
func (r *Raft) start() {
r.state = Follower
r.currentTerm = 0
r.voteFor = -1
r.heartbeat = make(chan bool)
r.toLeaderC = make(chan bool)
go func() {
rand.Seed(time.Now().UnixNano())
for {
switch r.state {
case Follower:
select {
case <-r.heartbeat:
log.Printf("follower-%d recived heartbeat\n", r.id)
case <-time.After(time.Duration(rand.Intn(500-300)+3000) * time.Millisecond):
log.Printf("followe-%d not receive leader beat because timeout\n", r.id)
r.state = Candidate
}
case Candidate:
log.Printf("Node %d current change to Candidate", r.id)
r.currentTerm++
r.voteFor = r.id
r.voteCount = 1
go r.broadcastVote()
select {
case <-time.After(time.Duration(rand.Intn(500-300)+3000) * time.Millisecond):
r.state = Follower
case <-r.toLeaderC:
log.Printf("Node: %v become Leader \n", r.id)
r.state = Leader
r.nextIndex = make([]int, len(r.nodes))
r.matchIndex = make([]int, len(r.nodes))
for i := range r.nodes {
r.nextIndex[i] = 1
r.matchIndex[i] = 0
}
go func() {
i := 0
for {
i++
r.log = append(r.log, LogEntry{r.currentTerm, i, fmt.Sprintf("user send : %d", i)})
time.Sleep(3 * time.Second)
}
}()
}
case Leader:
//broadcast heartbeat
r.broadcastHeartbeat()
time.Sleep(100 * time.Millisecond)
}
}
}()
}
func (r *Raft) broadcastVote() {
var voteArgs VoteArgs
if size := len(r.log); size == 0 {
voteArgs = VoteArgs{
Term: r.currentTerm,
Index: 0,
Candidate: r.id,
}
} else {
voteArgs = VoteArgs{
Term: r.currentTerm,
Index: r.log[len(r.log)-1].LogIndex,
Candidate: r.id,
}
}
for _, n := range r.nodes {
go func() {
r.sendRequestVote(voteArgs, n.address, &VoteReply{})
}()
}
}
func (r *Raft) sendRequestVote(args VoteArgs, address string, reply *VoteReply) {
client, err := rpc.DialHTTP("tcp", address)
if err != nil {
log.Print("dialing: ", err)
return
}
defer func(client *rpc.Client) {
err := client.Close()
if err != nil {
log.Print("close client failed:", err)
}
}(client)
err = client.Call("Raft.RequestVote", args, reply)
if err != nil {
log.Printf("node: %v send requrest vote to node: %v failed ", r.id, address)
return
}
if reply.Term > r.currentTerm {
log.Printf("接收到的reply大于当前的任期 %v", reply)
r.currentTerm = reply.Term
r.state = Follower
r.voteFor = -1
}
if reply.VoteGrant {
r.voteCount++
}
if r.voteCount >= len(r.nodes)/2+1 {
//超过半数成为leader
r.toLeaderC <- true
}
}
func (r *Raft) broadcastHeartbeat() {
log.Printf("当前的nodes列表:%v", r.nodes)
for i, n := range r.nodes {
log.Printf("需要广播心跳 index:%v node: %v", i, n.address)
if r.id == n.id {
continue
}
//log.Printf("broadcast to %v", n)
args := HeartbeatArgs{
Term: r.currentTerm,
Leader: r.id,
LeaderCommit: r.commitIndex,
}
//也就是当前所在的日志索引
preLogIndex := r.nextIndex[i] - 1
if r.lastIndex() > preLogIndex {
args.PrevLogIndex = preLogIndex
args.PrevLogTerm = r.log[preLogIndex].LogTerm
args.Entries = r.log[preLogIndex:]
}
go func() {
r.sendHeartBeat(n, args, &HeartbeatReply{})
}()
}
}
func (r *Raft) sendHeartBeat(n *node, args HeartbeatArgs, reply *HeartbeatReply) {
log.Printf("send heartbeat to :%v", n.address)
client, err := rpc.DialHTTP("tcp", n.address)
if err != nil {
log.Printf("Connect to Node %v failed: %v ", n.address, err)
return
}
err = client.Call("Raft.HeartBeat", args, reply)
if err != nil {
log.Printf("Remote call [Node %v] raft.Heartbeat failed: %v", n.address, err)
}
if reply.Success {
if reply.NextIndex > 0 {
r.nextIndex[n.id] = reply.NextIndex
r.matchIndex[n.id] = reply.NextIndex - 1
}
} else {
// 如果leader的term小于follower 需要重新选举
if reply.Term > r.currentTerm {
r.currentTerm = reply.Term
r.state = Follower
r.voteFor = -1
return
}
}
}
func (r *Raft) lastIndex() int {
index := len(r.log)
if index == 0 {
return 0
}
return r.log[index-1].LogIndex
}
func main() {
port := flag.String("port", ":9091", "rpc listen port")
cluster := flag.String("cluster", "127.0.0.1:9091", "comma sep")
id := flag.Int("id", 0, "node ID")
flag.Parse()
clusters := strings.Split(*cluster, ",")
ns := make(map[int]*node)
for k, v := range clusters {
ns[k] = newNode(v, k)
log.Printf("Node created: %v", ns[k])
}
raft := &Raft{
id: *id,
nodes: ns,
}
raft.rpc(*port)
raft.start()
select {}
}