Apache Kafka源码分析 - kafka controller

时间:2023-02-18 23:38:08

前面已经分析过kafka server的启动过程,以及server所能处理的所有的request,即KafkaApis
剩下的,其实关键就是controller,以及partition和replica的状态机
这里先看看controller在broker server的基础上,多做了哪些初始化和failover的工作

 

最关键的一句,

private val controllerElector = new ZookeeperLeaderElector(controllerContext, ZkUtils.ControllerPath, onControllerFailover,
onControllerResignation, config.brokerId)

 

kafka.server.ZookeeperLeaderElector

参数的含义比较明显,注意两个callback,是关键
class ZookeeperLeaderElector(controllerContext: ControllerContext,
electionPath: String,
onBecomingLeader: () => Unit,
onResigningAsLeader: () => Unit,
brokerId: Int)

做两件事,

1. 建立watcher,去listen “election path” in ZK, "/controller";

当controller发生变化是,可以做相应的处理

controllerContext.zkClient.subscribeDataChanges(electionPath, leaderChangeListener)

LeaderChangeListener

监听这个path的两个行为,
handleDataChange,即controller发生了变化,这个比较简单,只需要把local的leaderid更新一下就好
leaderId = KafkaController.parseControllerId(data.toString)
handleDataDeleted,这种情况即,controller被删除了,一般是挂了
挂了就重新做elect,但是多个判断,如果本来我就是leader,那先调用onResigningAsLeader,即onControllerResignation,做些清理的工作,比如deregister watcher,关闭各种状态机
if(amILeader)
onResigningAsLeader()
elect

 

2. elect, 试图去创建EphemeralPath,从而成为Controller

用createEphemeralPathExpectConflictHandleZKBug,试图去创建EphemeralNode,

如果不成功说明已经被别人抢占

成功就说明我成为了controller,调用onBecomingLeader(),即onControllerFailover

 

KafkaController.onControllerFailover

这个callback就是controller初始化的关键,

/**
* 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
* If it encounters any unexpected exception/error while becoming controller, it resigns as the current controller.
* This ensures another controller election will be triggered and there will always be an actively serving controller
*/
def onControllerFailover() {
if(isRunning) {
info("Broker %d starting become controller state transition".format(config.brokerId)) //开始日志
//read controller epoch from zk
readControllerEpochFromZookeeper()
// increment the controller epoch
incrementControllerEpoch(zkClient) //增加ControllerEpoch,以区分过期
// before reading source of truth from zookeeper, register the listeners to get broker/topic callbacks
registerReassignedPartitionsListener()
registerPreferredReplicaElectionListener()
partitionStateMachine.registerListeners()
replicaStateMachine.registerListeners()
initializeControllerContext() //从zk读出broker,topic的信息以初始化controllerContext
replicaStateMachine.startup() //启动状态机
partitionStateMachine.startup()
// register the partition change listeners for all existing topics on failover
controllerContext.allTopics.foreach(topic => partitionStateMachine.registerPartitionChangeListener(topic)) //为每个topic增加partition变化的watcher
info("Broker %d is ready to serve as the new controller with epoch %d".format(config.brokerId, epoch)) //完成日志
brokerState.newState(RunningAsController)
maybeTriggerPartitionReassignment()
maybeTriggerPreferredReplicaElection()
/* send partition leadership info to all live brokers */
sendUpdateMetadataRequest(controllerContext.liveOrShuttingDownBrokerIds.toSeq) //如注释说,用于成为controller,需要把partition leadership信息发到所有brokers,大家要以我为准
if (config.autoLeaderRebalanceEnable) { //如果打开outoLeaderRebalance,需要把partiton leader由于dead而发生迁徙的,重新迁徙回去
info("starting the partition rebalance scheduler")
autoRebalanceScheduler.startup()
autoRebalanceScheduler.schedule("partition-rebalance-thread", checkAndTriggerPartitionRebalance,
5, config.leaderImbalanceCheckIntervalSeconds, TimeUnit.SECONDS)
}
deleteTopicManager.start()
}
else
info("Controller has been shut down, aborting startup/failover")
}

 

这里最后再讨论一下createEphemeralPathExpectConflictHandleZKBug

这个函数看着比较诡异,handleZKBug,到底是zk的什么bug?

注释给出了,https://issues.apache.org/jira/browse/ZOOKEEPER-1740

这个问题在于“The current behavior of zookeeper for ephemeral nodes is that session expiration and ephemeral node deletion is not an atomic operation.”

即zk的session过期和ephemeral node删除并不是一个原子操作,所以带来的问题的过程如下,

1. client session超时,它会假设在zk,这个ephemeral node已经被删除,但是zk当前由于某种原因hang住了,比如very long fsync operations,所以其实这个ephemeral node并没有被删除

2. 但client是认为ephemeral node已经被删除,所以它会尝试重新创建这个ephemeral node,但得到的结果是NodeExists,因为这个node并没有被删除,那么client想既然有就算了

3. 这个时候,zk从very long fsync operations的hang中恢复,它会继续之前没有完成的操作,把ephemeral node删掉

4. 这样client就会发现ephemeral node不存在了,虽然session并没有超时

所以这个函数就是为了规避这个问题,

方法就是,当我发现NodeExists时,说明zk当前hang住了,这个时候我需要等待,并反复尝试,直到zk把这个node删除后,我再重新创建

def createEphemeralPathExpectConflictHandleZKBug(zkClient: ZkClient, path: String, data: String, expectedCallerData: Any, checker: (String, Any) => Boolean, backoffTime: Int): Unit = {
while (true) {
try {
createEphemeralPathExpectConflict(zkClient, path, data)
return
} catch {
case e: ZkNodeExistsException => {
// An ephemeral node may still exist even after its corresponding session has expired
// due to a Zookeeper bug, in this case we need to retry writing until the previous node is deleted
// and hence the write succeeds without ZkNodeExistsException
ZkUtils.readDataMaybeNull(zkClient, path)._1 match {
case Some(writtenData) => {
if (checker(writtenData, expectedCallerData)) {
info("I wrote this conflicted ephemeral node [%s] at %s a while back in a different session, ".format(data, path)
+ "hence I will backoff for this node to be deleted by Zookeeper and retry") Thread.sleep(backoffTime)
} else {
throw e
}
}
case None => // the node disappeared; retry creating the ephemeral node immediately
}
}
case e2: Throwable => throw e2
}
}
}

这个方式有个问题就是,如果zk hang住,这里的逻辑是while true,这个函数也会一直hang住

Apache Kafka源码分析 - kafka controller的更多相关文章

  1. Apache Kafka源码分析 – Broker Server

    1. Kafka.scala 在Kafka的main入口中startup KafkaServerStartable, 而KafkaServerStartable这是对KafkaServer的封装 1: ...

  2. Kafka源码分析(一) - 概述

    系列文章目录 https://zhuanlan.zhihu.com/p/367683572 目录 系列文章目录 一. 实际问题 二. 什么是Kafka, 如何解决这些问题的 三. 基本原理 1. 基本 ...

  3. Kafka源码分析系列-目录(收藏不迷路)

    持续更新中,敬请关注! 目录 <Kafka源码分析>系列文章计划按"数据传递"的顺序写作,即:先分析生产者,其次分析Server端的数据处理,然后分析消费者,最后再补充 ...

  4. Kafka源码分析&lpar;三&rpar; - Server端 - 消息存储

    系列文章目录 https://zhuanlan.zhihu.com/p/367683572 目录 系列文章目录 一. 业务模型 1.1 概念梳理 1.2 文件分析 1.2.1 数据目录 1.2.2 . ...

  5. apache kafka源码分析-Producer分析---转载

    原文地址:http://www.aboutyun.com/thread-9938-1-1.html 问题导读1.Kafka提供了Producer类作为java producer的api,此类有几种发送 ...

  6. kafka源码分析之一server启动分析

    0. 关键概念 关键概念 Concepts Function Topic 用于划分Message的逻辑概念,一个Topic可以分布在多个Broker上. Partition 是Kafka中横向扩展和一 ...

  7. Kafka源码分析及图解原理之Producer端

    一.前言 任何消息队列都是万变不离其宗都是3部分,消息生产者(Producer).消息消费者(Consumer)和服务载体(在Kafka中用Broker指代).那么本篇主要讲解Producer端,会有 ...

  8. Kafka源码分析&lpar;二&rpar; - 生产者

    系列文章目录 https://zhuanlan.zhihu.com/p/367683572 目录 系列文章目录 一. 使用方式 step 1: 设置必要参数 step 2: 创建KafkaProduc ...

  9. 源码分析 Kafka 消息发送流程&lpar;文末附流程图&rpar;

    温馨提示:本文基于 Kafka 2.2.1 版本.本文主要是以源码的手段一步一步探究消息发送流程,如果对源码不感兴趣,可以直接跳到文末查看消息发送流程图与消息发送本地缓存存储结构. 从上文 初识 Ka ...

随机推荐

  1. ubuntu 运行android sdk 下的工具adb报bash&colon; &period;&sol;adb&colon; No such file or directory

    运行adb出现这种错误: bash: ./adb: No such file or directory   但adb确实存在. 可能1:你用的是64位的Linux,没装32位运行时库,安装 $ sud ...

  2. UINavigationBar-使用总结

    多视图应用程序中,我们常常使用到自定义UINavigationBar来完成导航条的设置.   1.获取导航条   UINavigationBar *navBar = self.navigationCo ...

  3. POJ-3468-A Simple Problem with Integers&lpar;区间更新,求和&rpar;-splay或线段树

    区间更新求和 主要用来练习splay树区间更新问题 //splay树的题解 // File Name: 3468-splay.cpp // Author: Zlbing // Created Time ...

  4. MySQL Join 的实现原理

    在寻找Join 语句的优化思路之前,我们首先要理解在MySQL 中是如何来实现Join 的,只要理解了实现原理之后,优化就比较简单了.下面我们先分析一下MySQL 中Join 的实现原理.在MySQL ...

  5. vs2005设置打开文件和保存文件编码

    一般vs2005打开文件时会自动侦测文件编码,自动以相应的编码格式打开.但是如果不认识的编码,就会出现乱码. Set VS2005 to use without BOM UTF-8 encoding ...

  6. 8&period; 利用反射机制, ListArray,intent来实现多Activity的切换

    package com.example.thenewboston; import android.app.ListActivity; import android.content.Intent; im ...

  7. Struts2 第一个入门小案例

    1.加载类库 2 配置web.xml文件 3.开发视图层 4.开发控制层Action 5.配置struts.xml 6.部署运行

  8. Go语言之并发编程(一)

    轻量级线程(goroutine) 在编写socket网络程序时,需要提前准备一个线程池为每一个socket的收发包分配一个线程.开发人员需要在线程数量和CPU数量间建立一个对应关系,以保证每个任务能及 ...

  9. MyBatist庖丁解牛(二)

    站在巨人的肩膀上 https://blog.csdn.net/xiaokang123456kao/article/details/76228684 一.概述 我们知道,Mybatis实现增删改查需要进 ...

  10. DCOS之Mesos-DNS介绍

    DCOS的Mesos-DNS它主要提供域名解析服务,Mesos-DNS 在DCOS框架中支持服务发现,同意应用程序和服务通过域名系统(DNS)来相互定位.DCOS中的 Mesos-DNS充当的角色和在 ...