@@ -61,7 +61,7 @@ func NodeToString(role NodeRole) string {
61
61
type Raft struct {
62
62
mu sync.RWMutex
63
63
peers []* RaftClientEnd // rpc client end
64
- me_ int
64
+ id int64
65
65
dead int32
66
66
applyCh chan * pb.ApplyMsg
67
67
applyCond * sync.Cond
@@ -85,10 +85,10 @@ type Raft struct {
85
85
baseElecTimeout uint64
86
86
}
87
87
88
- func MakeRaft (peers []* RaftClientEnd , me int , newdbEng storage_eng.KvStore , applyCh chan * pb.ApplyMsg , heartbeatTimeOutMs uint64 , baseElectionTimeOutMs uint64 ) * Raft {
88
+ func MakeRaft (peers []* RaftClientEnd , me int64 , newdbEng storage_eng.KvStore , applyCh chan * pb.ApplyMsg , heartbeatTimeOutMs uint64 , baseElectionTimeOutMs uint64 ) * Raft {
89
89
rf := & Raft {
90
90
peers : peers ,
91
- me_ : me ,
91
+ id : me ,
92
92
dead : 0 ,
93
93
applyCh : applyCh ,
94
94
replicatorCond : make ([]* sync.Cond , len (peers )),
@@ -107,13 +107,12 @@ func MakeRaft(peers []*RaftClientEnd, me int, newdbEng storage_eng.KvStore, appl
107
107
heartBeatTimeout : heartbeatTimeOutMs ,
108
108
}
109
109
rf .curTerm , rf .votedFor = rf .persister .ReadRaftState ()
110
- rf .ReInitLog ()
111
110
rf .applyCond = sync .NewCond (& rf .mu )
112
111
last_log := rf .logs .GetLast ()
113
112
for _ , peer := range peers {
114
113
logger .ELogger ().Sugar ().Debugf ("peer addr %s id %d" , peer .addr , peer .id )
115
114
rf .matchIdx [peer .id ], rf .nextIdx [peer .id ] = 0 , int (last_log .Index + 1 )
116
- if int (peer .id ) != me {
115
+ if int64 (peer .id ) != me {
117
116
rf .replicatorCond [peer .id ] = sync .NewCond (& sync.Mutex {})
118
117
go rf .Replicator (peer )
119
118
}
@@ -156,7 +155,7 @@ func (rf *Raft) SwitchRaftNodeRole(role NodeRole) {
156
155
case NodeRoleLeader :
157
156
// become leader,set replica (matchIdx and nextIdx) processs table
158
157
lastLog := rf .logs .GetLast ()
159
- rf .leaderId = int64 (rf .me_ )
158
+ rf .leaderId = int64 (rf .id )
160
159
for i := 0 ; i < len (rf .peers ); i ++ {
161
160
rf .matchIdx [i ], rf .nextIdx [i ] = 0 , int (lastLog .Index + 1 )
162
161
}
@@ -201,7 +200,7 @@ func (rf *Raft) HandleRequestVote(req *pb.RequestVoteRequest, resp *pb.RequestVo
201
200
202
201
last_log := rf .logs .GetLast ()
203
202
204
- if ! ( req .LastLogTerm > int64 (last_log .Term ) || (req .LastLogTerm == int64 (last_log .Term ) && req .LastLogIndex >= last_log .Index ) ) {
203
+ if req .LastLogTerm < int64 (last_log .Term ) || (req .LastLogTerm == int64 (last_log .Term ) && req .LastLogIndex < last_log .Index ) {
205
204
resp .Term , resp .VoteGranted = rf .curTerm , false
206
205
return
207
206
}
@@ -244,7 +243,7 @@ func (rf *Raft) HandleAppendEntries(req *pb.AppendEntriesRequest, resp *pb.Appen
244
243
if req .PrevLogIndex < int64 (rf .logs .GetFirst ().Index ) {
245
244
resp .Term = 0
246
245
resp .Success = false
247
- logger .ELogger ().Sugar ().Debugf ("peer %d reject append entires request from %d" , rf .me_ , req .LeaderId )
246
+ logger .ELogger ().Sugar ().Debugf ("peer %d reject append entires request from %d" , rf .id , req .LeaderId )
248
247
return
249
248
}
250
249
@@ -295,7 +294,7 @@ func (rf *Raft) CondInstallSnapshot(lastIncluedTerm int, lastIncludedIndex int,
295
294
if lastIncludedIndex > int (rf .logs .GetLast ().Index ) {
296
295
rf .logs .ReInitLogs ()
297
296
} else {
298
- rf .logs .EraseBeforeWithDel (int64 (lastIncludedIndex ) - rf .logs .GetFirst ().Index )
297
+ rf .logs .EraseBefore (int64 (lastIncludedIndex )- rf .logs .GetFirst ().Index , true )
299
298
rf .logs .SetEntFirstData ([]byte {})
300
299
}
301
300
// update dummy entry with lastIncludedTerm and lastIncludedIndex
@@ -318,7 +317,7 @@ func (rf *Raft) Snapshot(index int, snapshot []byte) {
318
317
logger .ELogger ().Sugar ().Warnf ("reject snapshot, current snapshotIndex is larger in cur term" )
319
318
return
320
319
}
321
- rf .logs .EraseBeforeWithDel (int64 (index ) - int64 (snapshot_index ))
320
+ rf .logs .EraseBefore (int64 (index )- int64 (snapshot_index ), true )
322
321
rf .logs .SetEntFirstData ([]byte {})
323
322
logger .ELogger ().Sugar ().Debugf ("del log entry before idx %d" , index )
324
323
rf .isSnapshoting = false
@@ -377,10 +376,13 @@ func (rf *Raft) GetLogCount() int {
377
376
func (rf * Raft ) advanceCommitIndexForLeader () {
378
377
sort .Ints (rf .matchIdx )
379
378
n := len (rf .matchIdx )
379
+ // [18 18 '19 19 20] majority replicate log index 19
380
+ // [18 '18 19] majority replicate log index 18
381
+ // [18 '18 19 20] majority replicate log index 18
380
382
new_commit_index := rf .matchIdx [n - (n / 2 + 1 )]
381
383
if new_commit_index > int (rf .commitIdx ) {
382
384
if rf .MatchLog (rf .curTerm , int64 (new_commit_index )) {
383
- logger .ELogger ().Sugar ().Debugf ("peer %d advance commit index %d at term %d" , rf .me_ , rf .commitIdx , rf .curTerm )
385
+ logger .ELogger ().Sugar ().Debugf ("peer %d advance commit index %d at term %d" , rf .id , rf .commitIdx , rf .curTerm )
384
386
rf .commitIdx = int64 (new_commit_index )
385
387
rf .applyCond .Signal ()
386
388
}
@@ -390,7 +392,7 @@ func (rf *Raft) advanceCommitIndexForLeader() {
390
392
func (rf * Raft ) advanceCommitIndexForFollower (leaderCommit int ) {
391
393
new_commit_index := Min (leaderCommit , int (rf .logs .GetLast ().Index ))
392
394
if new_commit_index > int (rf .commitIdx ) {
393
- logger .ELogger ().Sugar ().Debugf ("peer %d advance commit index %d at term %d" , rf .me_ , rf .commitIdx , rf .curTerm )
395
+ logger .ELogger ().Sugar ().Debugf ("peer %d advance commit index %d at term %d" , rf .id , rf .commitIdx , rf .curTerm )
394
396
rf .commitIdx = int64 (new_commit_index )
395
397
rf .applyCond .Signal ()
396
398
}
@@ -403,19 +405,19 @@ func (rf *Raft) MatchLog(term, index int64) bool {
403
405
404
406
// Election make a new election
405
407
func (rf * Raft ) Election () {
406
- logger .ELogger ().Sugar ().Debugf ("%d start election " , rf .me_ )
408
+ logger .ELogger ().Sugar ().Debugf ("%d start election " , rf .id )
407
409
408
410
rf .IncrGrantedVotes ()
409
- rf .votedFor = int64 (rf .me_ )
411
+ rf .votedFor = int64 (rf .id )
410
412
vote_req := & pb.RequestVoteRequest {
411
413
Term : rf .curTerm ,
412
- CandidateId : int64 (rf .me_ ),
414
+ CandidateId : int64 (rf .id ),
413
415
LastLogIndex : int64 (rf .logs .GetLast ().Index ),
414
416
LastLogTerm : int64 (rf .logs .GetLast ().Term ),
415
417
}
416
418
rf .PersistRaftState ()
417
419
for _ , peer := range rf .peers {
418
- if int (peer .id ) == rf .me_ {
420
+ if int64 (peer .id ) == rf .id {
419
421
continue
420
422
}
421
423
go func (peer * RaftClientEnd ) {
@@ -434,7 +436,7 @@ func (rf *Raft) Election() {
434
436
// success granted the votes
435
437
rf .IncrGrantedVotes ()
436
438
if rf .grantedVotes > len (rf .peers )/ 2 {
437
- logger .ELogger ().Sugar ().Debugf ("I'm win this term, (node %d) get majority votes int term %d " , rf .me_ , rf .curTerm )
439
+ logger .ELogger ().Sugar ().Debugf ("I'm win this term, (node %d) get majority votes int term %d " , rf .id , rf .curTerm )
438
440
rf .SwitchRaftNodeRole (NodeRoleLeader )
439
441
rf .BroadcastHeartbeat ()
440
442
rf .grantedVotes = 0
@@ -457,7 +459,7 @@ func (rf *Raft) Election() {
457
459
458
460
func (rf * Raft ) BroadcastAppend () {
459
461
for _ , peer := range rf .peers {
460
- if peer .id == uint64 (rf .me_ ) {
462
+ if peer .id == uint64 (rf .id ) {
461
463
continue
462
464
}
463
465
rf .replicatorCond [peer .id ].Signal ()
@@ -467,7 +469,7 @@ func (rf *Raft) BroadcastAppend() {
467
469
// BroadcastHeartbeat broadcast heartbeat to peers
468
470
func (rf * Raft ) BroadcastHeartbeat () {
469
471
for _ , peer := range rf .peers {
470
- if int (peer .id ) == rf .me_ {
472
+ if int64 (peer .id ) == rf .id {
471
473
continue
472
474
}
473
475
logger .ELogger ().Sugar ().Debugf ("send heart beat to %s" , peer .addr )
@@ -529,8 +531,8 @@ func (rf *Raft) Append(command []byte) *pb.Entry {
529
531
Data : command ,
530
532
}
531
533
rf .logs .Append (newLog )
532
- rf .matchIdx [rf .me_ ] = int (newLog .Index )
533
- rf .nextIdx [rf .me_ ] = int (newLog .Index ) + 1
534
+ rf .matchIdx [rf .id ] = int (newLog .Index )
535
+ rf .nextIdx [rf .id ] = int (newLog .Index ) + 1
534
536
rf .PersistRaftState ()
535
537
return newLog
536
538
}
@@ -568,7 +570,7 @@ func (rf *Raft) replicateOneRound(peer *RaftClientEnd) {
568
570
first_log := rf .logs .GetFirst ()
569
571
snap_shot_req := & pb.InstallSnapshotRequest {
570
572
Term : rf .curTerm ,
571
- LeaderId : int64 (rf .me_ ),
573
+ LeaderId : int64 (rf .id ),
572
574
LastIncludedIndex : first_log .Index ,
573
575
LastIncludedTerm : int64 (first_log .Term ),
574
576
Data : rf .ReadSnapshot (),
@@ -604,11 +606,13 @@ func (rf *Raft) replicateOneRound(peer *RaftClientEnd) {
604
606
} else {
605
607
first_index := rf .logs .GetFirst ().Index
606
608
logger .ELogger ().Sugar ().Debugf ("first log index %d" , first_index )
607
- entries := make ([]* pb.Entry , len (rf .logs .EraseBefore (int64 (prev_log_index )+ 1 - first_index )))
608
- copy (entries , rf .logs .EraseBefore (int64 (prev_log_index )+ 1 - first_index ))
609
+ _ , new_ents := rf .logs .EraseBefore (int64 (prev_log_index )+ 1 - first_index , false )
610
+ entries := make ([]* pb.Entry , len (new_ents ))
611
+ copy (entries , new_ents )
612
+
609
613
append_ent_req := & pb.AppendEntriesRequest {
610
614
Term : rf .curTerm ,
611
- LeaderId : int64 (rf .me_ ),
615
+ LeaderId : int64 (rf .id ),
612
616
PrevLogIndex : int64 (prev_log_index ),
613
617
PrevLogTerm : int64 (rf .logs .GetEntry (int64 (prev_log_index ) - first_index ).Term ),
614
618
Entries : entries ,
@@ -666,7 +670,7 @@ func (rf *Raft) Applier() {
666
670
first_index , commit_index , last_applied := rf .logs .GetFirst ().Index , rf .commitIdx , rf .lastApplied
667
671
entries := make ([]* pb.Entry , commit_index - last_applied )
668
672
copy (entries , rf .logs .GetRange (last_applied + 1 - int64 (first_index ), commit_index + 1 - int64 (first_index )))
669
- logger .ELogger ().Sugar ().Debugf ("%d, applies entries %d-%d in term %d" , rf .me_ , rf .lastApplied , commit_index , rf .curTerm )
673
+ logger .ELogger ().Sugar ().Debugf ("%d, applies entries %d-%d in term %d" , rf .id , rf .lastApplied , commit_index , rf .curTerm )
670
674
671
675
rf .mu .Unlock ()
672
676
for _ , entry := range entries {
0 commit comments