每个节点都在后台持续运行:
如果主节点不存在,则进入主节点选举过程;
如果节点为主节点,则广播 declaration 消息,声明自己为主节点,如果收到别的节点发送的较低 节点 ID值,则成为从节点;
如果节点为从节点,并且在一定时间内(由 core.yaml 中的 leaderAliveThreshold 设置,默认 10 秒)没有收到其它节点发送的 declaration 消息,则设置主节点不存在。
主节点选举过程:
提交自己为主节点的提案;
收集其它节点发送的提案;
如果有其它节点声明为主节点,则放弃选举过程;
如果主节点不存在,则将自己的节点 ID 与其它节点的 ID 值进行比较,如果自己的 ID 值比其它任何一个节点 ID 值都小,则声明自己成为主节点,否则放弃选举过程。
详细过程图示:
主节点选举关键代码
// ref: https://github.com/hyperledger/fabric/blob/master/gossip/election/election.go
func (le *leaderElectionSvcImpl) run() {
defer le.stopWG.Done()
for !le.shouldStop() {
if !le.isLeaderExists() {
le.leaderElection()
}
// If we are yielding and some leader has been elected,
// stop yielding
if le.isLeaderExists() && le.isYielding() {
le.stopYielding()
}
if le.shouldStop() {
return
}
if le.IsLeader() {
le.leader()
} else {
le.follower()
}
}
}
func (le *leaderElectionSvcImpl) leaderElection() {
le.logger.Debug(le.id, ": Entering")
defer le.logger.Debug(le.id, ": Exiting")
// If we're yielding to other peers, do not participate
// in leader election
if le.isYielding() {
return
}
// Propose ourselves as a leader
le.propose()
// Collect other proposals
le.waitForInterrupt(getLeaderElectionDuration())
// If someone declared itself as a leader, give up
// on trying to become a leader too
if le.isLeaderExists() {
le.logger.Info(le.id, ": Some peer is already a leader")
return
}
if le.isYielding() {
le.logger.Debug(le.id, ": Aborting leader election because yielding")
return
}
// Leader doesn't exist, let's see if there is a better candidate than us
// for being a leader
for _, o := range le.proposals.ToArray() {
id := o.(string)
if bytes.Compare(peerID(id), le.id) < 0 {
return
}
}
// If we got here, there is no one that proposed being a leader
// that's a better candidate than us.
le.beLeader()
atomic.StoreInt32(&le.leaderExists, int32(1))
}