目录 [−]
本文主要介绍了Kafka High level的代码架构和主要的类。
Boker 架构
network layer
Kafka使用NIO自己实现了网络层的代码, 而不是采用netty, mina等第三方的网络框架。从性能上来讲,这一块的代码不是性能的瓶颈。 它采用IO多路复用和多线程下的Reactor模式,主要实现类包括SocketServer
, Acceptor
, Processor
和RequestChannel
。
Kafka的服务器由SocketServer
实现,它是一个NIO的服务器,线程模型如下:
1个Acceptor线程负责处理新连接
N个Processor线程, 每个processor都有自己的selector,负责从socket中读取请求和发送response
M个Handler线程处理请求,并产生response给processor线程
可以从上面的图形中看到Acceptor, Processor和Handler的功能。
a. Boker在启动的时候会调用SocketServer的startup
方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def startup() {
......
for (i <- 0 until numProcessorThreads) {
processors(i) = new Processor(i,
time,
maxRequestSize,
aggregateIdleMeter,
newMeter("IdlePercent" , "percent" , TimeUnit.NANOSECONDS, Map("networkProcessor" -> i.toString)),
numProcessorThreads,
requestChannel,
quotas,
connectionsMaxIdleMs)
Utils.newThread("kafka-network-thread-%d-%d" .format(port, i), processors(i), false ).start()
}
......
this .acceptor = new Acceptor(host, port, processors, sendBufferSize, recvBufferSize, quotas)
Utils.newThread("kafka-socket-acceptor" , acceptor, false ).start()
acceptor.awaitStartup
......
}
b. 它为每个Processor生成一个线程并启动,然后启动一个Acceptor
线程。
Acceptor
是一个典型NIO 处理新连接的方法类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private [kafka] class Acceptor (...) extends AbstractServerThread (connectionQuotas) {
val serverChannel = openServerSocket(host, port)
def run() {
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
......
while (isRunning) {
val ready = selector.select(500 )
if (ready > 0 ) {
val keys = selector.selectedKeys()
val iter = keys.iterator()
while (iter.hasNext && isRunning) {
......
accept(key, processors(currentProcessor))
......
currentProcessor = (currentProcessor + 1 ) % processors.length
}
}
}
......
}
}
c. 它会将新的连接均匀地分配给一个Processor。通过accept
方法配置网络参数,并交给processor读写数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def accept(key: SelectionKey, processor: Processor) {
val serverSocketChannel = key.channel().asInstanceOf[ServerSocketChannel]
val socketChannel = serverSocketChannel.accept()
try {
connectionQuotas.inc(socketChannel.socket().getInetAddress)
socketChannel.configureBlocking(false )
socketChannel.socket().setTcpNoDelay(true )
socketChannel.socket().setSendBufferSize(sendBufferSize)
processor.accept(socketChannel)
} catch {
case e: TooManyConnectionsException =>
info("Rejected connection from %s, address already has the configured maximum of %d connections." .format(e.ip, e.count))
close(socketChannel)
}
}
d. Processor的accept
方法将新连接加入它的新连接待处理队列中
在configureNewConnections
方法中注册OP_READ
。
1
2
3
4
5
6
7
8
9
10
11
12
def accept(socketChannel: SocketChannel) {
newConnections.add(socketChannel)
wakeup()
}
private def configureNewConnections() {
while (newConnections.size() > 0 ) {
val channel = newConnections.poll()
debug("Processor " + id + " listening to new connection from " + channel.socket.getRemoteSocketAddress)
channel.register(selector, SelectionKey.OP_READ)
}
}
e. Processor线程的主处理逻辑如下, 这是一个死循环,会一直处理这些连接的读写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
override def run() {
......
while (isRunning) {
configureNewConnections()
processNewResponses()
val startSelectTime = SystemTime.nanoseconds
val ready = selector.select(300 )
if (ready > 0 ) {
val keys = selector.selectedKeys()
val iter = keys.iterator()
while (iter.hasNext && isRunning) {
var key: SelectionKey = null
try {
key = iter.next
iter.remove()
if (key.isReadable)
read(key)
else if (key.isWritable)
write(key)
else if (!key.isValid)
close(key)
else
throw new IllegalStateException("Unrecognized key state for processor thread." )
} catch {
......
}
}
}
......
}
......
}
这也是一个标准的NIO的处理代码。
f. 我们看看read
和write
是怎么实现的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def read(key: SelectionKey) {
......
val socketChannel = channelFor(key)
var receive = key.attachment.asInstanceOf[Receive]
if (key.attachment == null ) {
receive = new BoundedByteBufferReceive(maxRequestSize)
key.attach(receive)
}
val read = receive.readFrom(socketChannel)
val address = socketChannel.socket.getRemoteSocketAddress();
if (read < 0 ) {
close(key)
} else if (receive.complete) {
val req = RequestChannel.Request(processor = id, requestKey = key, buffer = receive.buffer, startTimeMs = time.milliseconds, remoteAddress = address)
requestChannel.sendRequest(req)
key.attach(null )
key.interestOps(key.interestOps & (~SelectionKey.OP_READ))
} else {
key.interestOps(SelectionKey.OP_READ)
wakeup()
}
}
因为Kafka的消息前四个字节代表(一个int)为后续消息的size,所以首先读取size,接着把一个完整的消息读取出来。 如果读取出来一个完整的Request,则将它放到requestChannel
中。 具体的Kafka消息的格式可以参考A Guide To The Kafka Protocol
我们再看看write
方法的实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def write(key: SelectionKey) {
val socketChannel = channelFor(key)
val response = key.attachment().asInstanceOf[RequestChannel.Response]
val responseSend = response.responseSend
if (responseSend == null )
throw new IllegalStateException("Registered for write interest but no response attached to key." )
val written = responseSend.writeTo(socketChannel)
if (responseSend.complete) {
response.request.updateRequestMetrics()
key.attach(null )
key.interestOps(SelectionKey.OP_READ)
} else {
key.interestOps(SelectionKey.OP_WRITE)
wakeup()
}
}
直到写完一个response,才讲Ops设为OP_READ
,否则一直尝试写。
以上是网络层的主要代码逻辑,主要负责Kafka消息的读写。
API layer
API层的主要功能是由KafkaApis
类实现的。 根据配置Kafka生成了一组KafkaRequestHandler线程,叫做KafkaRequestHandlerPool
:
1
2
3
4
5
6
7
8
9
10
11
class KafkaRequestHandlerPool (......) extends Logging with KafkaMetricsGroup {
......
val threads = new Array[Thread](numThreads)
val runnables = new Array[KafkaRequestHandler](numThreads)
for (i <- 0 until numThreads) {
runnables(i) = new KafkaRequestHandler(i, brokerId, aggregateIdleMeter, numThreads, requestChannel, apis)
threads(i) = Utils.daemonThread("kafka-request-handler-" + i, runnables(i))
threads(i).start()
}
.....
}
KafkaRequestHandler不断的从requestChannel
队列里面取出request交给apis
处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class KafkaRequestHandler (......) extends Runnable with Logging {
def run() {
while (true ) {
try {
var req : RequestChannel.Request = null
while (req == null ) {
req = requestChannel.receiveRequest(300 )
}
if (req eq RequestChannel.AllDone) {
return
}
......
apis.handle(req)
} catch {
......
}
}
}
}
apis
根据不同的请求类型调用不同的方法进行处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def handle(request: RequestChannel.Request) {
try {
request.requestId match {
case RequestKeys.ProduceKey => handleProducerRequest(request)
case RequestKeys.FetchKey => handleFetchRequest(request)
case RequestKeys.OffsetsKey => handleOffsetRequest(request)
case RequestKeys.MetadataKey => handleTopicMetadataRequest(request)
case RequestKeys.LeaderAndIsrKey => handleLeaderAndIsrRequest(request)
case RequestKeys.StopReplicaKey => handleStopReplicaRequest(request)
case RequestKeys.UpdateMetadataKey => handleUpdateMetadataRequest(request)
case RequestKeys.ControlledShutdownKey => handleControlledShutdownRequest(request)
case RequestKeys.OffsetCommitKey => handleOffsetCommitRequest(request)
case RequestKeys.OffsetFetchKey => handleOffsetFetchRequest(request)
case RequestKeys.ConsumerMetadataKey => handleConsumerMetadataRequest(request)
case RequestKeys.JoinGroupKey => handleJoinGroupRequest(request)
case RequestKeys.HeartbeatKey => handleHeartbeatRequest(request)
case requestId => throw new KafkaException("Unknown api code " + requestId)
}
} catch {
} finally
request.apiLocalCompleteTimeMs = SystemTime.milliseconds
}
显然,此处处理的速度影响Kafka整体的消息处理的速度。 这里我们分析一个处理方法handleProducerRequest
。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def handleProducerRequest(request: RequestChannel.Request) {
val produceRequest = request.requestObj.asInstanceOf[ProducerRequest]
def sendResponseCallback(responseStatus: Map[TopicAndPartition, ProducerResponseStatus]) {
var errorInResponse = false
responseStatus.foreach { case (topicAndPartition, status) =>
if (status.error != ErrorMapping.NoError && status.error != ErrorMapping.UnknownCode) {
errorInResponse = true
}
}
if (produceRequest.requiredAcks == 0 ) {
if (errorInResponse) {
requestChannel.closeConnection(request.processor, request)
} else {
requestChannel.noOperation(request.processor, request)
}
} else {
val response = ProducerResponse(produceRequest.correlationId, responseStatus)
requestChannel.sendResponse(new RequestChannel.Response(request, new BoundedByteBufferSend(response)))
}
}
val internalTopicsAllowed = produceRequest.clientId == AdminUtils.AdminClientId
replicaManager.appendMessages(
produceRequest.ackTimeoutMs.toLong,
produceRequest.requiredAcks,
internalTopicsAllowed,
produceRequest.data,
sendResponseCallback)
produceRequest.emptyData()
}
这里会调用replicaManager.appendMessages
处理Kafka message的保存和备份,也就是leader和备份节点上。
Replication subsystem
顺藤摸瓜,我们进入replicaManager.appendMessages
的代码。 这个方法会将消息放到leader分区上,并复制到备份分区上。在超时或者根据required acks的值及时返回response。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def appendMessages(......) {
if (isValidRequiredAcks(requiredAcks)) {
val localProduceResults = appendToLocalLog(internalTopicsAllowed, messagesPerPartition, requiredAcks)
val produceStatus = localProduceResults.map { case (topicAndPartition, result) =>
topicAndPartition ->
ProducePartitionStatus(
result.info.lastOffset + 1 ,
ProducerResponseStatus(result.errorCode, result.info.firstOffset))
}
if (delayedRequestRequired(requiredAcks, messagesPerPartition, localProduceResults)) {
val produceMetadata = ProduceMetadata(requiredAcks, produceStatus)
val delayedProduce = new DelayedProduce(timeout, produceMetadata, this , responseCallback)
val producerRequestKeys = messagesPerPartition.keys.map(new TopicPartitionOperationKey(_)).toSeq
delayedProducePurgatory.tryCompleteElseWatch(delayedProduce, producerRequestKeys)
} else {
val produceResponseStatus = produceStatus.mapValues(status => status.responseStatus)
responseCallback(produceResponseStatus)
}
} else {
val responseStatus = messagesPerPartition.map {
case (topicAndPartition, messageSet) =>
(topicAndPartition ->
ProducerResponseStatus(Errors.INVALID_REQUIRED_ACKS.code,
LogAppendInfo.UnknownLogAppendInfo.firstOffset))
}
responseCallback(responseStatus)
}
}
注意复制是ReplicaFetcherManager
通过ReplicaFetcherThread
线程完成的。
更详细的资源可以参考: kafka replication
To publish a message to a partition, the client first finds the leader of the partition from Zookeeper and sends the message to the leader. The leader writes the message to its local log. Each follower constantly pulls new messages from the leader using a single socket channel. That way, the follower receives all messages in the same order as written in the leader. The follower writes each received message to its own log and sends an acknowledgment back to the leader. Once the leader receives the acknowledgment from all replicas in ISR, the message is committed. The leader advances the HW and sends an acknowledgment to the client. For better performance, each follower sends an acknowledgment after the message is written to memory. So, for each committed message, we guarantee that the message is stored in multiple replicas in memory. However, there is no guarantee that any replica has persisted the commit message to disks though. Given that correlated failures are relatively rare, this approach gives us a good balance between response time and durability. In the future, we may consider adding options that provide even stronger guarantees. The leader also periodically broadcasts the HW to all followers. The broadcasting can be piggybacked on the return value of the fetch requests from the followers. From time to time, each replica checkpoints its HW to its disk.
Log subsystem
LogManager负责管理Kafka的Log(Kafka消息), 包括log/Log文件夹的创建,获取和清理。它也会通过定时器检查内存中的log是否要缓存到磁盘中。 重要的类包括LogManager
和Log
。
offsetManager
负责管理offset,提供offset的读写。
topicConfigManager
它负责动态改变Topic的配置属性。 如果某个topic的配置属性改变了,Kafka会在ZooKeeper上创建一个类似/brokers/config_changes/config_change_13321的节点, topicConfigManager会监控这些节点, 获得属性改变的topics并处理,实际上以新的LogConfig
替换老的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private def processConfigChanges(notifications: Seq[String]) {
if (notifications.size > 0 ) {
val now = time.milliseconds
val logs = logManager.logsByTopicPartition.toBuffer
val logsByTopic = logs.groupBy(_._1.topic).mapValues(_.map(_._2))
for (notification <- notifications) {
val changeId = changeNumber(notification)
if (changeId > lastExecutedChange) {
val changeZnode = ZkUtils.TopicConfigChangesPath + "/" + notification
val (jsonOpt, stat) = ZkUtils.readDataMaybeNull(zkClient, changeZnode)
if (jsonOpt.isDefined) {
val json = jsonOpt.get
val topic = json.substring(1 , json.length - 1 )
if (logsByTopic.contains(topic)) {
val props = new Properties(logManager.defaultConfig.toProps)
props.putAll(AdminUtils.fetchTopicConfig(zkClient, topic))
val logConfig = LogConfig.fromProps(props)
for (log <- logsByTopic(topic))
log.config = logConfig
info("Processed topic config change %d for topic %s, setting new config to %s." .format(changeId, topic, props))
purgeObsoleteNotifications(now, notifications)
}
}
lastExecutedChange = changeId
}
}
}
}
其它类
还有一些其它的重要的类, 包括KafkaController
, KafkaScheduler
,ConsumerCoordinator
,KafkaHealthcheck
等。
Metrics
Kafka使用metrics 进行性能的度量。原先是yammer metrics,现在独立成dropwizard metrics.目前这个框架的package名字比较乱,但是性能监控的功能却是非常的强大。 metrics提供了几种reporter,可以将性能报告显示在哪里, 比如控制台,JMX, Slf4j,Ganglia,Graphite等。 Kafka实现了一个CSV文件报告类KafkaCSVMetricsReporter
,它调用metrics的CsvReporter
生成报告。 如果你想生成这些报告,需要在server.properties加入:
1
2
kafka.metrics.reporters= kafka.metrics.KafkaCSVMetricsReporter
kafka.csv.metrics.reporter.enabled= true
默认它会在kafka的kafka_metrics文件夹下生成这些csv文件。
Producer
kafka.producer.Producer
定义了两种类型的Producer: sync和async。基本上都是通过 eventHandler.handle(messages)处理消息, 只不过async会通过一个线程, 以LinkedBlockingQueue为缓冲发送消息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def handle(events: Seq[KeyedMessage[K,V]]) {
val serializedData = serialize(events)
var outstandingProduceRequests = serializedData
var remainingRetries = config.messageSendMaxRetries + 1
val correlationIdStart = correlationId.get()
while (remainingRetries > 0 && outstandingProduceRequests.size > 0 ) {
topicMetadataToRefresh ++= outstandingProduceRequests.map(_.topic)
if (topicMetadataRefreshInterval >= 0 &&
SystemTime.milliseconds - lastTopicMetadataRefreshTime > topicMetadataRefreshInterval) {
Utils.swallowError(brokerPartitionInfo.updateInfo(topicMetadataToRefresh.toSet, correlationId.getAndIncrement))
sendPartitionPerTopicCache.clear()
topicMetadataToRefresh.clear
lastTopicMetadataRefreshTime = SystemTime.milliseconds
}
outstandingProduceRequests = dispatchSerializedData(outstandingProduceRequests)
if (outstandingProduceRequests.size > 0 ) {
Thread.sleep(config.retryBackoffMs)
Utils.swallowError(brokerPartitionInfo.updateInfo(outstandingProduceRequests.map(_.topic).toSet, correlationId.getAndIncrement))
sendPartitionPerTopicCache.clear()
remainingRetries -= 1
producerStats.resendRate.mark()
}
}
if (outstandingProduceRequests.size > 0 ) {
producerStats.failedSendRate.mark()
val correlationIdEnd = correlationId.get()
throw new FailedToSendMessageException("Failed to send messages after " + config.messageSendMaxRetries + " tries." , null )
}
}
首先通过Encoder序列化成标准的KeyedMessage[K,Message]
。然后通过dispatchSerializedData(outstandingProduceRequests)
将消息添加到计算出的broker上(通过send方法发送ProducerRequest),这里有尝试次数的限制。kafka.javaapi.producer.Producer
则提供了java接口。
Consumer
kafka.consumer.SimpleConsumer
提供了Simple Consumer API.它通过一个BlockingChannel发送消息,接收Response完成任务。kafka.javaapi.consumer.SimpleConsumer
则提供了java接口。
High level consumer实际由ZookeeperConsumerConnector
完成,它将consumer信息记录在zookeeper中,提供KafkaStream
获取Kafka消息。
参考文档
https://cwiki.apache.org/confluence/display/KAFKA/Kafka+Internals
本文中的例子中一些不必要的代码行已经去掉, 如log日志, metrics监控等