Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reduce chance of duelling leaders #86

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions raft.go
Original file line number Diff line number Diff line change
Expand Up @@ -838,13 +838,21 @@ func (r *raft) becomeFollower(term uint64, lead uint64) {
r.logger.Infof("%x became follower at term %d", r.id, r.Term)
}

func (r *raft) nextTerm() uint64 {
// Term = [epoch:48; rand:16]
var cepoch uint64 = (r.Term & 0xffff_ffff_ffff_0000) >> 16
var tepoch uint64 = (cepoch + 1) << 16
var trdm uint64 = uint64(globalRand.Intn(65536)) & 0xffff
return tepoch | trdm
}

func (r *raft) becomeCandidate() {
// TODO(xiangli) remove the panic when the raft implementation is stable
if r.state == StateLeader {
panic("invalid transition [leader -> candidate]")
}
r.step = stepCandidate
r.reset(r.Term + 1)
r.reset(r.nextTerm())
r.tick = r.tickElection
r.Vote = r.id
r.state = StateCandidate
Expand Down Expand Up @@ -943,7 +951,7 @@ func (r *raft) campaign(t CampaignType) {
r.becomePreCandidate()
voteMsg = pb.MsgPreVote
// PreVote RPCs are sent for the next term before we've incremented r.Term.
term = r.Term + 1
term = r.nextTerm()
} else {
r.becomeCandidate()
voteMsg = pb.MsgVote
Expand Down