一、MsgHup消息
在raft協議中我們看到,Leader節點推動心跳計時器,而Follower節點會推動選舉計時器。源碼主要在etcd的github.com/etcd-io/etcd/tree/master/raft/node.go和raft.go中,raft結構體中有一個electionElapsed字段,該字段是選舉計時器的指針,邏輯時鐘每推進一次,該字段的值遞增1,邏輯時鐘是有上層模塊來推進的。當electionElapsed選舉計時器超時時,則該Follower節點會發送MsgHup消息。
1.選舉計時器邏輯時鐘的推動
選舉計時器及超時時間在raft結構體中爲以下兩個字段:
electionElapsed int //選舉計時器的指針,其單位是邏輯時鐘的刻度,邏輯時鐘每推進一次,該字段值就會增加1
randomizedElectionTimeout int //隨機生成的選舉計時器超時時間
選舉計時器是tickElection()函數來推動的,Node節點每收到一次邏輯時鐘推進,就會調用一次該函數來推動邏輯時鐘,並判斷邏輯時鐘是否超時,如果超時則發送MsgHup類型的消息。
//推動選舉計時器,如果超時則發送MsgHub消息
func (r *raft) tickElection() {
r.electionElapsed++
if r.promotable() && r.pastElectionTimeout() {
r.electionElapsed = 0
r.Step(pb.Message{From: r.id, Type: pb.MsgHup})
}
}
從以上方法我們看到,當選舉計時器超時,節點會調用Step方法發送MsgHup消息。
2.MsgHup消息流程
從tickElection方法中可以看到,當選舉計時器超時時,會將raft節點的electionElapsed心跳計時器置零,並且調用Step方法發送該MsgHup消息。Step方法處理各種消息類型的消息,我們這裏只看對MsgHup消息的處理。
如果當前節點是Leader,則忽略MsgHup類型的消息
如果當前節點不是Leader,
獲取raftLog中已提交但未應用的Entry記錄
檢測是否有未應用的EntryConfChange記錄,如果有就放棄發起選舉的機會
檢測當前集羣是否開啓了PreVote模式,如果開啓了則發起PreElection預選舉,沒有開啓則發起Election選舉
調用campaign()發起選舉
func (r *raft) Step(m pb.Message) error {
// ...... 其他類型消息處理略
switch m.Type { //根據Message的Type進行分類處理
case pb.MsgHup: //這裏針對MsgHup類型進行處理(Flower轉成PreCandidate發送的消息)
if r.state != StateLeader { //只有非Leader狀態的節點纔會處理MsgHup消息
//獲取raftLog中已提交但未應用的Entry記錄
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)
}
//檢測是否有未應用的EntryConfChange記錄,如果有就放棄發起選舉的機會
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 nil
}
r.logger.Infof("%x is starting a new election at term %d", r.id, r.Term)
if r.preVote { //檢測當前集羣是否開啓了PreVote模式,如果開啓了
//調用raft.campaign()方法切換當前節點的角色,發起PreVote
r.campaign(campaignPreElection)
} else {
r.campaign(campaignElection)
}
} else { //如果當前節點已經是Leader狀態,則僅僅輸出一條Debug日誌
r.logger.Debugf("%x ignoring MsgHup because already leader", r.id)
}
}
接下來我們看一下campaign方法
作用:發起選舉或者預選舉
預選舉 CampaignType爲 campaignPreElection
1.將當前節點切換成PreCandidate狀態
2.將voteMsg設置爲 pb.MsgPreVote
3.任期號自增1
選舉
1.將當前節點切換成Candidate狀態,該方法會增加raft.Term字段的值和重置相關狀態
2.將voteMsg設置爲 pb.MsgVote
3.確認term,爲當前Term值+1
統計當前節點收到的選票,並統計其得票數是否超過半數,這次檢測主要是爲單節點設置的,如果大於等於半數以上的投票,如果是PreElection則發起正式的選舉,如果是正式的選舉則該節點變成Leader。
如果不是單節點情況,則向集羣中其他節點發送voteMsg消息。
func (r *raft) campaign(t CampaignType) {
//在該方法的最後,會發送一條消息,這裏term和voteMsg分別用於確定該消息的Term值和類別
var term uint64
var voteMsg pb.MessageType
if t == campaignPreElection { //切換的目標狀態是PreCandidate
//將當前節點切換成PreCandidate狀態
r.becomePreCandidate()
//確定最後發送的消息是MsgPreVote類型
voteMsg = pb.MsgPreVote
// PreVote RPCs are sent for the next term before we've incremented r.Term.
//確定最後發送消息的Term值,並未增加raft.Term字段的值
term = r.Term + 1
} else { //切換目標狀態是Candidate
//將當前節點切換成Candidate狀態,該方法會增加raft.Term字段的值
r.becomeCandidate()
voteMsg = pb.MsgVote //確定最後發送消息的類型是MsgPreVote類型
term = r.Term //確定最後發送消息的Term值
}
//統計當前節點收到的選票,並統計其得票數是否超過半數,這次檢測主要是爲單節點設置的
if r.quorum() == r.poll(r.id, voteRespMsgType(voteMsg), true) {
// We won the election after voting for ourselves (which must mean that
// this is a single-node cluster). Advance to the next state.
//當得到足夠多的選票時,則將PreCandidate狀態的節點切換Candidate狀態
//Candidate狀態的節點則切換成Leader狀態
if t == campaignPreElection {
r.campaign(campaignElection)
} else {
r.becomeLeader()
}
return
}
for id := range r.prs { //狀態切換完成之後,當前節點會向集羣中其他所有節點發送指定類型(voteMsg)的消息
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
//在進行Leader節點轉移時,MsgPreVote或MsgVote消息會在Context字段中設置該特殊值
if t == campaignTransfer {
ctx = []byte(t)
}
//發送指定類型的消息,其中Index和LogTerm分別是當前節點的raftLog中
//最後一條消息的Index值和Term值
r.send(pb.Message{Term: term, To: id, Type: voteMsg, Index: r.raftLog.lastIndex(), LogTerm: r.raftLog.lastTerm(), Context: ctx})
}
}
二、MsgPreVote/MsgPreVoteResp和MsgVote/MsgVoteResp消息
當Follower的選舉計時器超時時,會把當前狀態切換成 StatePreCandidate(預選舉)或StateCandidate(候選人),並向集羣中其他節點發送MsgPreVote或MsgVote消息。當集羣中其他節點收到(預)選舉消息時,會先進行一些檢驗,符合相關條件會投同意,否則會投拒絕票,然後發送給該候選節點,發送的消息類型爲MsgPreVoteResp或MsgVoteResp類型。如果預選舉階段(StatePreCandidate)成功收到超過半數以上的同意票,那麼該節點會認爲選舉成功,會發起新一輪的正式選舉(節點狀態切換成SateCandidate(候選人),發送的消息類型爲MsgVote)。如果是正式選舉成功收到超過半數以上的同意票,那個該節點會成爲新的Leader。如果沒有收到超過半數的票則會將節點狀態切換成Follower。
注:是否有預選舉階段是根據初始化配置的參數,該字段保存在raft結構體的preVote字段中
預選舉流程如下圖
選舉階段流程如下圖
當Follower發起選舉向集羣中其他節點發送MsgPreVote和MsgVote消息時,也會將自己的狀態State切換成候選人(StatePreCandidate或StateCandidate)狀態。發送MsgPreVote或MsgVote消息前面已經講過,接下來我們主要看一下其他節點收到MsgPreVote或MsgVote消息時是如何處理的。
1.其他節點收到MsgVote/MsgPreVote類型的消息
處理MsgVote/MsgPreVote類型的消息流程在raft的Step方法中,看到當滿足一些條件,節點纔會投贊成票,負責會投拒絕票,投票發送的消息的類型爲MsgVoteResp或MsgPreVoteResp。
當前節點在參與預選時,會綜合下面幾個條件決定是否投票
1.當前節點是否已經投票
2.MsgPreVote消息發送者的任期號是否更大
3.當前節點投票給了對方節點
4.MsgPreVote消息發送者的raftLog中是否包含當前節點的全部Entry記錄
func (r *raft)Step(m pb.Message) error {
//其他類型的消息略
......
case pb.MsgVote, pb.MsgPreVote://投票,預投票消息處理
if r.isLearner {
// TODO: learner may need to vote, in case of node down when confchange.
r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] ignored %s from %x [logterm: %d, index: %d] at term %d: learner can not vote",
r.id, r.raftLog.lastTerm(), r.raftLog.lastIndex(), r.Vote, m.Type, m.From, m.LogTerm, m.Index, r.Term)
return nil
}
// We can vote if this is a repeat of a vote we've already cast...
canVote := r.Vote == m.From ||
// ...we haven't voted and we don't think there's a leader yet in this term...
(r.Vote == None && r.lead == None) ||
// ...or this is a PreVote for a future term...
(m.Type == pb.MsgPreVote && m.Term > r.Term)
// ...and we believe the candidate is up to date.
if canVote && r.raftLog.isUpToDate(m.Index, m.LogTerm) {
r.logger.Infof("%x [logterm: %d, index: %d, vote: %x] cast %s for %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)
// When responding to Msg{Pre,}Vote messages we include the term
// from the message, not the local term. To see why consider the
// case where a single node was previously partitioned away and
// it's local term is now of date. If we include the local term
// (recall that for pre-votes we don't update the local term), the
// (pre-)campaigning node on the other end will proceed to ignore
// the message (it ignores all out of date messages).
// The term in the original message and current local term are the
// same in the case of regular votes, but different for pre-votes.
//將票投給MsgPreVote消息的發送節點(包含選舉和預選舉)
r.send(pb.Message{To: m.From, Term: m.Term, Type: voteRespMsgType(m.Type)})
if m.Type == pb.MsgVote { //如果是MsgVote處理
// Only record real votes.
r.electionElapsed = 0
r.Vote = m.From
}
} else { //不滿足上述條件,當前節點會返回拒投票(Reject:true)
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: voteRespMsgType(m.Type), Reject: true})
}
}
2.候選節點會等待集羣中其他節點投票返回的消息
參與選舉的候選節點發送預選舉(MsgPreVote)或選舉(MsgVote)消息後,會等待集羣中其他節點返回的消息,如果是MsgPreVote消息,則返回MsgPreVoteResp消息,如果是MsgVote消息,則返回MsgVoteResp消息。處理流程主要在raft中的stepCandidate中。
從該方法中可以看到,處於候選人狀態的節點當收到MsgProp、MsgApp、MsgHeartbeat、MsgSnap類型的消息會切換成Follower角色。當收到MsgPreVoteResp或MsgVoteResp類型的消息會統計,如果超過半數則切換成Leader狀態。如果無法獲取半數以上的選票,則切換成Follower狀態。
func stepCandidate(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 myVoteRespType:
gr := r.poll(m.From, m.Type, !m.Reject) //記錄並統計某個節點投票結果
r.logger.Infof("%x [quorum:%d] has received %d %s votes and %d vote rejections", r.id, r.quorum(), gr, m.Type, len(r.votes)-gr)
switch r.quorum() { //得票數爲len(r.prs)/2 + 1,即超過半數
case gr: //得票數超過半數
if r.state == StatePreCandidate {
r.campaign(campaignElection) //當PreCandidate節點在預選中收到半數以上的選票之後,會發起正式的選舉
} else {
r.becomeLeader()
r.bcastAppend() //向集羣中其他節點廣播MsgApp消息
}
case len(r.votes) - gr: //無法獲取半數以上的選票,當前節點切換成跟隨者Follower狀態,等待下一輪的選舉
// 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)
}
return nil
}