-
Notifications
You must be signed in to change notification settings - Fork 1
/
election.go
178 lines (157 loc) · 4.93 KB
/
election.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
package raft
// example RequestVote RPC arguments structure.
// field names must start with capital letters!
type RequestVoteArgs struct {
// Your data here (2A, 2B).
Term int
CandidateId int
LastLogIndex int
LastLogTerm int
}
// example RequestVote RPC reply structure.
// field names must start with capital letters!
type RequestVoteReply struct {
// Your data here (2A).
Term int
VoteGranted bool
}
// example RequestVote RPC handler.
func (rf *Raft) RequestVoteHandler(args *RequestVoteArgs, reply *RequestVoteReply) {
// Your code here (2A, 2B).
DPrintf("Server %v get a RequestVote request, candidate is %v, term is %v", rf.me, args.CandidateId, args.Term)
rf.mu.Lock()
defer rf.mu.Unlock()
defer rf.persist()
reply.Term = rf.currentTerm
reply.VoteGranted = false
if args.Term < rf.currentTerm {
reply.VoteGranted = false
return
} else if args.Term == rf.currentTerm {
if rf.state == Leader {
return
}
if rf.votedFor == args.CandidateId {
reply.VoteGranted = true
return
} else if rf.votedFor != -1 && rf.votedFor != args.CandidateId {
reply.VoteGranted = false
return
}
}
if args.Term > rf.currentTerm {
rf.currentTerm = args.Term
rf.votedFor = -1
rf.changeState(Follower)
}
lastLogIndex := len(rf.logs) - 1
// Test 2B (5.4.1 election restriction)
if args.LastLogTerm < rf.logs[lastLogIndex].Term || (args.LastLogTerm == rf.logs[lastLogIndex].Term && args.LastLogIndex < rf.getAbsoluteLogIndex(lastLogIndex)){
DPrintf("Server %v refuse to vote for server %v because of 5.4.1(2B) election restriction", rf.me, args.CandidateId)
return
}
rf.currentTerm = args.Term
rf.votedFor = args.CandidateId
rf.changeState(Follower)
reply.VoteGranted = true
rf.resetElectionTimer()
DPrintf("Server %v vote for %d\n", rf.me, args.CandidateId)
return
}
//
// example code to send a RequestVote RPC to a server.
// server is the index of the target server in rf.peers[].
// expects RPC arguments in args.
// fills in *reply with RPC reply, so caller should
// pass &reply.
// the types of the args and reply passed to Call() must be
// the same as the types of the arguments declared in the
// handler function (including whether they are pointers).
//
// The labrpc package simulates a lossy network, in which servers
// may be unreachable, and in which requests and replies may be lost.
// Call() sends a request and waits for a reply. If a reply arrives
// within a timeout interval, Call() returns true; otherwise
// Call() returns false. Thus Call() may not return for a while.
// A false return can be caused by a dead server, a live server that
// can't be reached, a lost request, or a lost reply.
//
// Call() is guaranteed to return (perhaps after a delay) *except* if the
// handler function on the server side does not return. Thus there
// is no need to implement your own timeouts around Call().
//
// look at the comments in ../labrpc/labrpc.go for more details.
//
// if you're having trouble getting RPC to work, check that you've
// capitalized all field names in structs passed over RPC, and
// that the caller passes the address of the reply struct with &, not
// the struct itself.
//
func (rf *Raft) sendRequestVote(server int, args *RequestVoteArgs, reply *RequestVoteReply) (bool) {
DPrintf("Server %v send RequestVote request to %v on term %v", rf.me, server, args.Term)
ok := rf.peers[server].Call("Raft.RequestVoteHandler", args, reply)
if !ok {
DPrintf("Server %v Send request vote to server %v failed", rf.me, server)
}
return ok
}
func (rf *Raft) resetElectionTimer() {
rf.electionTimer.Stop()
rf.electionTimer.Reset(rf.randElectionTimeout())
}
func (rf *Raft) startElection() {
rf.lock("Election")
if rf.state == Leader {
rf.unlock("Election")
return
}
DPrintf("Server %v start Election\n", rf.me)
rf.changeState(Candidate)
rf.persist()
lastLogIndex := len(rf.logs) - 1
args := RequestVoteArgs{
Term: rf.currentTerm,
CandidateId: rf.me,
LastLogIndex: rf.getAbsoluteLogIndex(lastLogIndex),
LastLogTerm: rf.logs[lastLogIndex].Term,
}
rf.unlock("Election")
voteCount := 1
voteTrueNum := 1
voteChannel := make(chan bool, len(rf.peers))
for i,_ := range rf.peers {
if i == rf.me {
continue
}
go func(x int) {
reply := RequestVoteReply{}
rf.sendRequestVote(x, &args, &reply)
rf.lock("down to follower")
if reply.Term > rf.currentTerm {
rf.currentTerm = reply.Term
DPrintf("Server %v is args.Term > rf.currentTer, not leader, down to follower", rf.me)
rf.changeState(Follower)
rf.resetElectionTimer()
rf.persist()
}
rf.unlock("down to follower")
voteChannel <- reply.VoteGranted
}(i)
}
for {
vote := <- voteChannel
voteCount += 1
if vote == true {
voteTrueNum += 1
}
if voteCount == len(rf.peers) || voteTrueNum > len(rf.peers)/2 || (voteCount - voteTrueNum) > len(rf.peers)/2 {
break
}
}
if voteTrueNum > len(rf.peers)/2 {
rf.lock("switch to Leader")
rf.changeState(Leader)
rf.persist()
rf.unlock("switch to Leader")
}
}