Kafkak中有多处涉及到选主和failover, 比如Controller, 比如Partition leader. 我们先来看下和选主有关的类;
This trait defines a leader elector If the existing leader is dead, this class will handle automatic re-election and if it succeeds, it invokes the leader state change callback
trait LeaderElector extends Logging {
def startup // 启动
def amILeader : Boolean //标识是否为主
def elect: Boolean //选主
def close //关闭
}startup方法: 先watch这个zk节点, 然后调用elect;def startup {
inLock(controllerContext.controllerLock) {
controllerContext.zkUtils.zkClient.subscribeDataChanges(electionPath, leaderChangeListener)
elect
}
}elect方法:
zookeeper_leader_elect.png
controllerContext.zkUtils.zkClient.subscribeDataChanges(electionPath, leaderChangeListener) 这个leaderChangeListener被触发时:handleDataChange: 如果改变前是leader, 改变后不是leader, 则回调onResigningAsLeader();handleDataDeleted: 如果当前是leader, 则回调onResigningAsLeader()并同次调用elect开始抢占式选主;ZookeeperLeaderElector作选主和Failoverprivate val controllerElector = new ZookeeperLeaderElector(controllerContext, ZkUtils.ControllerPath, onControllerFailover,
onControllerResignation, config.brokerId)ZkUtils.ControllerPath = /controller KafkaController::startup:def startup() = {
inLock(controllerContext.controllerLock) {
info("Controller starting up")
registerSessionExpirationListener()
isRunning = true
controllerElector.startup
info("Controller startup complete")
}
}其中
registerSessionExpirationListener() 注册zk连接的状态回调,处理SessionExpiration;
controllerElector.startup 开始选主和Failover;
onControllerFailover: 变为leader时被回调,
设置当前broker的状态为RunningAsController 作下面的事情:This callback is invoked by the zookeeper leader elector on electing the current broker as the new controller. It does the following things on the become-controller state change - 1. Register controller epoch changed listener 2. Increments the controller epoch 3. Initializes the controller's context object that holds cache objects for current topics, live brokers and leaders for all existing partitions. 4. Starts the controller's channel manager 5. Starts the replica state machine 6. Starts the partition state machine