func(r *raft) hup(t CampaignType) { if r.state == StateLeader { r.logger.Debugf("%x ignoring MsgHup because already leader", r.id) return }
if !r.promotable() { r.logger.Warningf("%x is unpromotable and can not campaign", r.id) return } ents, err := r.raftLog.slice(r.raftLog.applied+1, r.raftLog.committed+1, noLimit) if err != nil { r.logger.Panicf("unexpected error getting unapplied entries (%v)", err) } if n := numOfPendingConf(ents); n != 0 && r.raftLog.committed > r.raftLog.applied { r.logger.Warningf("%x cannot campaign at term %d since there are still %d pending configuration changes to apply", r.id, r.Term, n) return }
r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term) r.campaign(t) }
// promotable indicates whether state machine can be promoted to leader, // which is true when its own id is in progress list. func(r *raft) promotable() bool { pr := r.prs.Progress[r.id] return pr != nil && !pr.IsLearner && !r.raftLog.hasPendingSnapshot() }
/ campaign transitions the raft instance to candidate state. This must only be // called after verifying that this is a legitimate transition. func(r *raft) campaign(t CampaignType) { if !r.promotable() { // This path should not be hit (callers are supposed to check), but // better safe than sorry. r.logger.Warningf("%x is unpromotable; campaign() should have been called", r.id) } var term uint64 var voteMsg pb.MessageType if t == campaignPreElection { r.becomePreCandidate() voteMsg = pb.MsgPreVote // PreVote RPCs are sent for the next term before we've incremented r.Term. term = r.Term + 1 } else { r.becomeCandidate() voteMsg = pb.MsgVote term = r.Term } if _, _, res := r.poll(r.id, voteRespMsgType(voteMsg), true); res == quorum.VoteWon { // We won the election after voting for ourselves (which must mean that // this is a single-node cluster). Advance to the next state. if t == campaignPreElection { r.campaign(campaignElection) } else { r.becomeLeader() } return } var ids []uint64 { idMap := r.prs.Voters.IDs() ids = make([]uint64, 0, len(idMap)) for id := range idMap { ids = append(ids, id) } sort.Slice(ids, func(i, j int)bool { return ids[i] < ids[j] }) } for _, id := range ids { if id == r.id { continue } r.logger.Infof("%x [logterm: %d, index: %d] sent %s request to %x at term %d", r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), voteMsg, id, r.Term)
var ctx []byte if t == campaignTransfer { ctx = []byte(t) } r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx}) } }
if t == campaignPreElection { r.becomePreCandidate() voteMsg = pb.MsgPreVote // PreVote RPCs are sent for the next term before we've incremented r.Term. term = r.Term + 1 } else { r.becomeCandidate() voteMsg = pb.MsgVote term = r.Term }
if _, _, res := r.poll(r.id, voteRespMsgType(voteMsg), true); res == quorum.VoteWon { // We won the election after voting for ourselves (which must mean that // this is a single-node cluster). Advance to the next state. if t == campaignPreElection { r.campaign(campaignElection) } else { r.becomeLeader() } return }
case m.Term > r.Term: if m.Type == pb.MsgVote || m.Type == pb.MsgPreVote { force := bytes.Equal(m.Context, []byte(campaignTransfer)) inLease := r.checkQuorum && r.lead != None && r.electionElapsed < r.electionTimeout if !force && inLease { // If a server receives a RequestVote request within the minimum election timeout // of hearing from a current leader, it does not update its term or grant its vote r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: lease is not expired (remaining ticks: %d)", r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term, r.electionTimeout-r.electionElapsed) returnnil } } switch { case m.Type == pb.MsgPreVote: // Never change our term in response to a PreVote case m.Type == pb.MsgPreVoteResp && !m.Reject: // We send pre-vote requests with a term in our future. If the // pre-vote is granted, we will increment our term when we get a // quorum. If it is not, the term comes from the node that // rejected our vote so we should become a follower at the new // term. default: r.logger.Infof("%x [term: %d] received a %s message with higher term from %x [term: %d]", r.id, r.Term, m.Type, m.From, m.Term) if m.Type == pb.MsgApp || m.Type == pb.MsgHeartbeat || m.Type == pb.MsgSnap { r.becomeFollower(m.Term, m.From) } else { r.becomeFollower(m.Term, None) } }
case m.Term < r.Term: if (r.checkQuorum || r.preVote) && (m.Type == pb.MsgHeartbeat || m.Type == pb.MsgApp) { // We have received messages from a leader at a lower term. It is possible // that these messages were simply delayed in the network, but this could // also mean that this node has advanced its term number during a network // partition, and it is now unable to either win an election or to rejoin // the majority on the old term. If checkQuorum is false, this will be // handled by incrementing term numbers in response to MsgVote with a // higher term, but if checkQuorum is true we may not advance the term on // MsgVote and must generate other messages to advance the term. The net // result of these two features is to minimize the disruption caused by // nodes that have been removed from the cluster's configuration: a // removed node will send MsgVotes (or MsgPreVotes) which will be ignored, // but it will not receive MsgApp or MsgHeartbeat, so it will not create // disruptive term increases, by notifying leader of this node's activeness. // The above comments also true for Pre-Vote // // When follower gets isolated, it soon starts an election ending // up with a higher term than leader, although it won't receive enough // votes to win the election. When it regains connectivity, this response // with "pb.MsgAppResp" of higher term would force leader to step down. // However, this disruption is inevitable to free this stuck node with // fresh election. This can be prevented with Pre-Vote phase. r.send(pb.Message{To: m.From, Type: pb.MsgAppResp}) } elseif m.Type == pb.MsgPreVote { // Before Pre-Vote enable, there may have candidate with higher term, // but less log. After update to Pre-Vote, the cluster may deadlock if // we drop messages with a lower term. r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] rejected %s from %x [logterm: %d, index: %d] at term %d", r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term) r.send(pb.Message{To: m.From, Term: r.Term, Type: pb.MsgPreVoteResp, Reject: true}) } else { // ignore other cases r.logger.Infof("%x [term: %d] ignored a %s message with lower term from %x [term: %d]", r.id, r.Term, m.Type, m.From, m.Term) } returnnil }
这里对应了[1.4](###1.4 引入的新问题和解决方案)中提出的问题:
如果集群开启了Check Quorum / Leader Lease或Pre-Vote,通过一条消息term为当前Term的消息令term低的节点成为follower;
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.tick = r.tickElection r.Vote = r.id r.state = StateCandidate r.logger.Infof("%x became candidate at term %d", r.id, r.Term) }
func(r *raft) becomePreCandidate() { // TODO(xiangli) remove the panic when the raft implementation is stable if r.state == StateLeader { panic("invalid transition [leader -> pre-candidate]") } // Becoming a pre-candidate changes our step functions and state, // but doesn't change anything else. In particular it does not increase // r.Term or change r.Vote. r.step = stepCandidate r.prs.ResetVotes() r.tick = r.tickElection r.lead = None r.state = StatePreCandidate r.logger.Infof("%x became pre-candidate at term %d", r.id, r.Term) }
func(r *raft) reset(term uint64) { if r.Term != term { r.Term = term r.Vote = None } r.lead = None
// stepCandidate is shared by StateCandidate and StatePreCandidate; the difference is // whether they respond to MsgVoteResp or MsgPreVoteResp. funcstepCandidate(r *raft, m pb.Message)error { // Only handle vote responses corresponding to our candidacy (while in // StateCandidate, we may get stale MsgPreVoteResp messages in this term from // our pre-candidate state). var myVoteRespType pb.MessageType if r.state == StatePreCandidate { myVoteRespType = pb.MsgPreVoteResp } else { myVoteRespType = pb.MsgVoteResp } switch m.Type { case pb.MsgProp: r.logger.Infof("%x no leader at term %d; dropping proposal", r.id, r.Term) return ErrProposalDropped case pb.MsgApp: r.becomeFollower(m.Term, m.From) // always m.Term == r.Term r.handleAppendEntries(m) case pb.MsgHeartbeat: r.becomeFollower(m.Term, m.From) // always m.Term == r.Term r.handleHeartbeat(m) case pb.MsgSnap: r.becomeFollower(m.Term, m.From) // always m.Term == r.Term r.handleSnapshot(m) case myVoteRespType: gr, rj, res := r.poll(m.From, m.Type, !m.Reject) r.logger.Infof("%x has received %d %s votes and %d vote rejections", r.id, gr, m.Type, rj) switch res { case quorum.VoteWon: if r.state == StatePreCandidate { r.campaign(campaignElection) } else { r.becomeLeader() r.bcastAppend() } case quorum.VoteLost: // pb.MsgPreVoteResp contains future term of pre-candidate // m.Term > r.Term; reuse r.Term r.becomeFollower(r.Term, None) } case pb.MsgTimeoutNow: r.logger.Debugf("%x [term %d state %v] ignored MsgTimeoutNow from %x", r.id, r.Term, r.state, m.From) } returnnil }
funcstepLeader(r *raft, m pb.Message)error { // These message types do not require any progress for m.From. switch m.Type { case pb.MsgBeat: r.bcastHeartbeat() returnnil case pb.MsgCheckQuorum: // The leader should always see itself as active. As a precaution, handle // the case in which the leader isn't in the configuration any more (for // example if it just removed itself). // // TODO(tbg): I added a TODO in removeNode, it doesn't seem that the // leader steps down when removing itself. I might be missing something. if pr := r.prs.Progress[r.id]; pr != nil { pr.RecentActive = true } if !r.prs.QuorumActive() { r.logger.Warningf("%x stepped down to follower since quorum is not active", r.id) r.becomeFollower(r.Term, None) } // Mark everyone (but ourselves) as inactive in preparation for the next // CheckQuorum. r.prs.Visit(func(id uint64, pr *tracker.Progress) { if id != r.id { pr.RecentActive = false } }) returnnil case pb.MsgProp: iflen(m.Entries) == 0 { r.logger.Panicf("%x stepped empty MsgProp", r.id) } if r.prs.Progress[r.id] == nil { // If we are not currently a member of the range (i.e. this node // was removed from the configuration while serving as leader), // drop any new proposals. return ErrProposalDropped } if r.leadTransferee != None { r.logger.Debugf("%x [term %d] transfer leadership to %x is in progress; dropping proposal", r.id, r.Term, r.leadTransferee) return ErrProposalDropped }
for i := range m.Entries { e := &m.Entries[i] var cc pb.ConfChangeI if e.Type == pb.EntryConfChange { var ccc pb.ConfChange if err := ccc.Unmarshal(e.Data); err != nil { panic(err) } cc = ccc } elseif e.Type == pb.EntryConfChangeV2 { var ccc pb.ConfChangeV2 if err := ccc.Unmarshal(e.Data); err != nil { panic(err) } cc = ccc } if cc != nil { alreadyPending := r.pendingConfIndex > r.raftLog.applied alreadyJoint := len(r.prs.Config.Voters[1]) > 0 wantsLeaveJoint := len(cc.AsV2().Changes) == 0
var refused string if alreadyPending { refused = fmt.Sprintf("possible unapplied conf change at index %d (applied to %d)", r.pendingConfIndex, r.raftLog.applied) } elseif alreadyJoint && !wantsLeaveJoint { refused = "must transition out of joint config first" } elseif !alreadyJoint && wantsLeaveJoint { refused = "not in joint state; refusing empty conf change" }
if !r.appendEntry(m.Entries...) { return ErrProposalDropped } r.bcastAppend() returnnil case pb.MsgReadIndex: // only one voting member (the leader) in the cluster if r.prs.IsSingleton() { if resp := r.responseToReadIndexReq(m, r.raftLog.committed); resp.To != None { r.send(resp) } returnnil }
// Postpone read only request when this leader has not committed // any log entry at its term. if !r.committedEntryInCurrentTerm() { r.pendingReadIndexMessages = append(r.pendingReadIndexMessages, m) returnnil }
sendMsgReadIndexResponse(r, m)
returnnil }
// All other message types require a progress for m.From (pr). pr := r.prs.Progress[m.From] if pr == nil { r.logger.Debugf("%x no progress available for %x", r.id, m.From) returnnil } switch m.Type { case pb.MsgAppResp: pr.RecentActive = true
if m.Reject { // RejectHint is the suggested next base entry for appending (i.e. // we try to append entry RejectHint+1 next), and LogTerm is the // term that the follower has at index RejectHint. Older versions // of this library did not populate LogTerm for rejections and it // is zero for followers with an empty log. // // Under normal circumstances, the leader's log is longer than the // follower's and the follower's log is a prefix of the leader's // (i.e. there is no divergent uncommitted suffix of the log on the // follower). In that case, the first probe reveals where the // follower's log ends (RejectHint=follower's last index) and the // subsequent probe succeeds. // // However, when networks are partitioned or systems overloaded, // large divergent log tails can occur. The naive attempt, probing // entry by entry in decreasing order, will be the product of the // length of the diverging tails and the network round-trip latency, // which can easily result in hours of time spent probing and can // even cause outright outages. The probes are thus optimized as // described below. r.logger.Debugf("%x received MsgAppResp(rejected, hint: (index %d, term %d)) from %x for index %d", r.id, m.RejectHint, m.LogTerm, m.From, m.Index) nextProbeIdx := m.RejectHint if m.LogTerm > 0 { // If the follower has an uncommitted log tail, we would end up // probing one by one until we hit the common prefix. // // For example, if the leader has: // // idx 1 2 3 4 5 6 7 8 9 // ----------------- // term (L) 1 3 3 3 5 5 5 5 5 // term (F) 1 1 1 1 2 2 // // Then, after sending an append anchored at (idx=9,term=5) we // would receive a RejectHint of 6 and LogTerm of 2. Without the // code below, we would try an append at index 6, which would // fail again. // // However, looking only at what the leader knows about its own // log and the rejection hint, it is clear that a probe at index // 6, 5, 4, 3, and 2 must fail as well: // // For all of these indexes, the leader's log term is larger than // the rejection's log term. If a probe at one of these indexes // succeeded, its log term at that index would match the leader's, // i.e. 3 or 5 in this example. But the follower already told the // leader that it is still at term 2 at index 6, and since the // log term only ever goes up (within a log), this is a contradiction. // // At index 1, however, the leader can draw no such conclusion, // as its term 1 is not larger than the term 2 from the // follower's rejection. We thus probe at 1, which will succeed // in this example. In general, with this approach we probe at // most once per term found in the leader's log. // // There is a similar mechanism on the follower (implemented in // handleAppendEntries via a call to findConflictByTerm) that is // useful if the follower has a large divergent uncommitted log // tail[1], as in this example: // // idx 1 2 3 4 5 6 7 8 9 // ----------------- // term (L) 1 3 3 3 3 3 3 3 7 // term (F) 1 3 3 4 4 5 5 5 6 // // Naively, the leader would probe at idx=9, receive a rejection // revealing the log term of 6 at the follower. Since the leader's // term at the previous index is already smaller than 6, the leader- // side optimization discussed above is ineffective. The leader thus // probes at index 8 and, naively, receives a rejection for the same // index and log term 5. Again, the leader optimization does not improve // over linear probing as term 5 is above the leader's term 3 for that // and many preceding indexes; the leader would have to probe linearly // until it would finally hit index 3, where the probe would succeed. // // Instead, we apply a similar optimization on the follower. When the // follower receives the probe at index 8 (log term 3), it concludes // that all of the leader's log preceding that index has log terms of // 3 or below. The largest index in the follower's log with a log term // of 3 or below is index 3. The follower will thus return a rejection // for index=3, log term=3 instead. The leader's next probe will then // succeed at that index. // // [1]: more precisely, if the log terms in the large uncommitted // tail on the follower are larger than the leader's. At first, // it may seem unintuitive that a follower could even have such // a large tail, but it can happen: // // 1. Leader appends (but does not commit) entries 2 and 3, crashes. // idx 1 2 3 4 5 6 7 8 9 // ----------------- // term (L) 1 2 2 [crashes] // term (F) 1 // term (F) 1 // // 2. a follower becomes leader and appends entries at term 3. // ----------------- // term (x) 1 2 2 [down] // term (F) 1 3 3 3 3 // term (F) 1 // // 3. term 3 leader goes down, term 2 leader returns as term 4 // leader. It commits the log & entries at term 4. // // ----------------- // term (L) 1 2 2 2 // term (x) 1 3 3 3 3 [down] // term (F) 1 // ----------------- // term (L) 1 2 2 2 4 4 4 // term (F) 1 3 3 3 3 [gets probed] // term (F) 1 2 2 2 4 4 4 // // 4. the leader will now probe the returning follower at index // 7, the rejection points it at the end of the follower's log // which is at a higher log term than the actually committed // log. nextProbeIdx = r.raftLog.findConflictByTerm(m.RejectHint, m.LogTerm) } if pr.MaybeDecrTo(m.Index, nextProbeIdx) { r.logger.Debugf("%x decreased progress of %x to [%s]", r.id, m.From, pr) if pr.State == tracker.StateReplicate { pr.BecomeProbe() } r.sendAppend(m.From) } } else { oldPaused := pr.IsPaused() if pr.MaybeUpdate(m.Index) { switch { case pr.State == tracker.StateProbe: pr.BecomeReplicate() case pr.State == tracker.StateSnapshot && pr.Match >= pr.PendingSnapshot: // TODO(tbg): we should also enter this branch if a snapshot is // received that is below pr.PendingSnapshot but which makes it // possible to use the log again. r.logger.Debugf("%x recovered from needing snapshot, resumed sending replication messages to %x [%s]", r.id, m.From, pr) // Transition back to replicating state via probing state // (which takes the snapshot into account). If we didn't // move to replicating state, that would only happen with // the next round of appends (but there may not be a next // round for a while, exposing an inconsistent RaftStatus). pr.BecomeProbe() pr.BecomeReplicate() case pr.State == tracker.StateReplicate: pr.Inflights.FreeLE(m.Index) }
if r.maybeCommit() { // committed index has progressed for the term, so it is safe // to respond to pending read index requests releasePendingReadIndexMessages(r) r.bcastAppend() } elseif oldPaused { // If we were paused before, this node may be missing the // latest commit index, so send it. r.sendAppend(m.From) } // We've updated flow control information above, which may // allow us to send multiple (size-limited) in-flight messages // at once (such as when transitioning from probe to // replicate, or when freeTo() covers multiple messages). If // we have more entries to send, send as many messages as we // can (without sending empty messages for the commit index) for r.maybeSendAppend(m.From, false) { } // Transfer leadership is in progress. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() { r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From) r.sendTimeoutNow(m.From) } } } case pb.MsgHeartbeatResp: pr.RecentActive = true pr.ProbeSent = false
// free one slot for the full inflights window to allow progress. if pr.State == tracker.StateReplicate && pr.Inflights.Full() { pr.Inflights.FreeFirstOne() } if pr.Match < r.raftLog.lastIndex() { r.sendAppend(m.From) }
if r.prs.Voters.VoteResult(r.readOnly.recvAck(m.From, m.Context)) != quorum.VoteWon { returnnil }
rss := r.readOnly.advance(m) for _, rs := range rss { if resp := r.responseToReadIndexReq(rs.req, rs.index); resp.To != None { r.send(resp) } } case pb.MsgSnapStatus: if pr.State != tracker.StateSnapshot { returnnil } // TODO(tbg): this code is very similar to the snapshot handling in // MsgAppResp above. In fact, the code there is more correct than the // code here and should likely be updated to match (or even better, the // logic pulled into a newly created Progress state machine handler). if !m.Reject { pr.BecomeProbe() r.logger.Debugf("%x snapshot succeeded, resumed sending replication messages to %x [%s]", r.id, m.From, pr) } else { // NB: the order here matters or we'll be probing erroneously from // the snapshot index, but the snapshot never applied. pr.PendingSnapshot = 0 pr.BecomeProbe() r.logger.Debugf("%x snapshot failed, resumed sending replication messages to %x [%s]", r.id, m.From, pr) } // If snapshot finish, wait for the MsgAppResp from the remote node before sending // out the next MsgApp. // If snapshot failure, wait for a heartbeat interval before next try pr.ProbeSent = true case pb.MsgUnreachable: // During optimistic replication, if the remote becomes unreachable, // there is huge probability that a MsgApp is lost. if pr.State == tracker.StateReplicate { pr.BecomeProbe() } r.logger.Debugf("%x failed to send message to %x because it is unreachable [%s]", r.id, m.From, pr) case pb.MsgTransferLeader: if pr.IsLearner { r.logger.Debugf("%x is learner. Ignored transferring leadership", r.id) returnnil } leadTransferee := m.From lastLeadTransferee := r.leadTransferee if lastLeadTransferee != None { if lastLeadTransferee == leadTransferee { r.logger.Infof("%x [term %d] transfer leadership to %x is in progress, ignores request to same node %x", r.id, r.Term, leadTransferee, leadTransferee) returnnil } r.abortLeaderTransfer() r.logger.Infof("%x [term %d] abort previous transferring leadership to %x", r.id, r.Term, lastLeadTransferee) } if leadTransferee == r.id { r.logger.Debugf("%x is already leader. Ignored transferring leadership to self", r.id) returnnil } // Transfer leadership to third party. r.logger.Infof("%x [term %d] starts to transfer leadership to %x", r.id, r.Term, leadTransferee) // Transfer leadership should be finished in one electionTimeout, so reset r.electionElapsed. r.electionElapsed = 0 r.leadTransferee = leadTransferee if pr.Match == r.raftLog.lastIndex() { r.sendTimeoutNow(leadTransferee) r.logger.Infof("%x sends MsgTimeoutNow to %x immediately as %x already has up-to-date log", r.id, leadTransferee, leadTransferee) } else { r.sendAppend(leadTransferee) } } returnnil }
// Transfer leadership is in progress. if m.From == r.leadTransferee && pr.Match == r.raftLog.lastIndex() { r.logger.Infof("%x sent MsgTimeoutNow to %x after received MsgAppResp", r.id, m.From) r.sendTimeoutNow(m.From) }
此处代码只会在follower跟上了其match index才会执行,详情请见本系列后续文章。
2.4.3 Follower
follower中与选举相关的逻辑不是很多。
首先,还是对becomeFollower中对与选举相关的逻辑进行分析:
1 2 3 4 5 6 7 8
func(r *raft) becomeFollower(term uint64, lead uint64) { r.step = stepFollower r.reset(term) r.tick = r.tickElection r.lead = lead r.state = StateFollower r.logger.Infof("%x became follower at term %d", r.id, r.Term) }
funcstepFollower(r *raft, m pb.Message)error { switch m.Type { // ... ... case pb.MsgApp: r.electionElapsed = 0 r.lead = m.From // ... ... case pb.MsgHeartbeat: r.electionElapsed = 0 r.lead = m.From // ... ... case pb.MsgSnap: r.electionElapsed = 0 r.lead = m.From // ... ... case pb.MsgTransferLeader: if r.lead == None { r.logger.Infof("%x no leader at term %d; dropping leader transfer msg", r.id, r.Term) returnnil } m.To = r.lead r.send(m) case pb.MsgTimeoutNow: r.logger.Infof("%x [term %d] received MsgTimeoutNow from %x and starts an election to get leadership.", r.id, r.Term, m.From) // Leadership transfers never use pre-vote even if r.preVote is true; we // know we are not recovering from a partition so there is no need for the // extra round trip. r.hup(campaignTransfer) // ... ... returnnil }