Skip to content

Commit c976ceb

Browse files
committed
Randomise lower bits of terms
Signed-off-by: cjen1 <[email protected]>
1 parent 177ef28 commit c976ceb

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

raft.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -838,13 +838,21 @@ func (r *raft) becomeFollower(term uint64, lead uint64) {
838838
r.logger.Infof("%x became follower at term %d", r.id, r.Term)
839839
}
840840

841+
func (r *raft) nextTerm() uint64 {
842+
// Term = [epoch:48; rand:16]
843+
var cepoch uint64 = (r.Term & 0xffff_ffff_ffff_0000) >> 16
844+
var tepoch uint64 = (cepoch + 1) << 16
845+
var trdm uint64 = uint64(globalRand.Intn(65536)) & 0xffff
846+
return tepoch | trdm
847+
}
848+
841849
func (r *raft) becomeCandidate() {
842850
// TODO(xiangli) remove the panic when the raft implementation is stable
843851
if r.state == StateLeader {
844852
panic("invalid transition [leader -> candidate]")
845853
}
846854
r.step = stepCandidate
847-
r.reset(r.Term + 1)
855+
r.reset(r.nextTerm())
848856
r.tick = r.tickElection
849857
r.Vote = r.id
850858
r.state = StateCandidate
@@ -943,7 +951,7 @@ func (r *raft) campaign(t CampaignType) {
943951
r.becomePreCandidate()
944952
voteMsg = pb.MsgPreVote
945953
// PreVote RPCs are sent for the next term before we've incremented r.Term.
946-
term = r.Term + 1
954+
term = r.nextTerm()
947955
} else {
948956
r.becomeCandidate()
949957
voteMsg = pb.MsgVote

0 commit comments

Comments
 (0)