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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
| /**
* Processor - 网络I/O处理器
* 使用单线程NIO模型处理多个连接的I/O操作
*/
private[network] class Processor(val id: Int,
val requestChannel: RequestChannel,
val maxRequestSize: Int,
val listenerName: ListenerName,
val securityProtocol: SecurityProtocol,
val config: KafkaConfig,
val metrics: Metrics,
val time: Time,
val credentialProvider: CredentialProvider,
val memoryPool: MemoryPool,
val logContext: LogContext,
val connectionQuotas: ConnectionQuotas,
val apiVersionManager: ApiVersionManager)
extends AbstractServerThread(connectionQuotas) with KafkaMetricsGroup {
// NIO选择器和连接管理
private val selector = createSelector()
private val newConnections = new ConcurrentLinkedQueue[SocketChannel]()
private val inflightResponses = mutable.Map[String, RequestChannel.Response]()
// 性能指标
private val avgIdleMeter = newMeter("NetworkProcessorAvgIdlePercent", "percent", TimeUnit.NANOSECONDS)
/**
* Processor主循环
* 处理网络I/O事件的核心逻辑
*/
override def run(): Unit = {
startupComplete()
try {
while (isRunning) {
try {
// 记录空闲时间开始
val startSelectTime = time.nanoseconds()
// 1. 配置新连接
configureNewConnections()
// 2. 处理响应
processNewResponses()
// 3. NIO事件轮询
poll()
// 4. 处理已完成的接收
processCompletedReceives()
// 5. 处理已完成的发送
processCompletedSends()
// 6. 处理断开的连接
processDisconnected()
// 记录空闲时间
val endSelectTime = time.nanoseconds()
avgIdleMeter.mark(endSelectTime - startSelectTime)
} catch {
case e: ControlThrowable => throw e
case e: Throwable =>
error("Processor循环中发生未预期的错误", e)
}
}
} finally {
debug("关闭Processor {},清理资源", id)
closeAll()
shutdownComplete()
}
}
/**
* 配置新接受的连接
* 将新连接注册到Selector并设置认证
*/
private def configureNewConnections(): Unit = {
var connectionsProcessed = 0
while (connectionsProcessed < 20 && !newConnections.isEmpty) {
val socketChannel = newConnections.poll()
if (socketChannel != null) {
try {
debug(s"配置新连接:${socketChannel.socket().getRemoteSocketAddress}")
// 生成连接ID
val connectionId = generateConnectionId(socketChannel)
// 创建KafkaChannel包装SocketChannel
val kafkaChannel = buildKafkaChannel(connectionId, socketChannel)
// 注册到Selector
selector.register(connectionId, kafkaChannel)
connectionsProcessed += 1
} catch {
case e: Throwable =>
error("配置新连接时发生错误", e)
close(socketChannel)
}
}
}
}
/**
* 构建KafkaChannel
* 根据安全协议配置不同类型的通道
*/
private def buildKafkaChannel(connectionId: String,
socketChannel: SocketChannel): KafkaChannel = {
try {
val transportLayer = buildTransportLayer(connectionId, socketChannel)
val authenticator = buildAuthenticator(connectionId, transportLayer)
new KafkaChannel(
id = connectionId,
transportLayer = transportLayer,
authenticator = authenticator,
maxReceiveSize = maxRequestSize,
memoryPool = memoryPool,
metricGrpPrefix = listenerName.value
)
} catch {
case e: Exception =>
error(s"构建KafkaChannel失败,连接: $connectionId", e)
throw e
}
}
/**
* 构建传输层
* 根据安全协议选择不同的传输层实现
*/
private def buildTransportLayer(connectionId: String,
socketChannel: SocketChannel): TransportLayer = {
securityProtocol match {
case SecurityProtocol.PLAINTEXT =>
// 明文传输
new PlaintextTransportLayer(connectionId, socketChannel)
case SecurityProtocol.SSL =>
// SSL/TLS加密传输
buildSslTransportLayer(connectionId, socketChannel)
case SecurityProtocol.SASL_PLAINTEXT =>
// SASL认证 + 明文传输
buildSaslTransportLayer(connectionId, socketChannel, false)
case SecurityProtocol.SASL_SSL =>
// SASL认证 + SSL加密传输
buildSaslTransportLayer(connectionId, socketChannel, true)
case _ =>
throw new IllegalArgumentException(s"不支持的安全协议: $securityProtocol")
}
}
/**
* NIO事件轮询
* 处理就绪的I/O事件
*/
private def poll(): Unit = {
try {
// 轮询I/O事件,1000ms超时
selector.poll(1000)
} catch {
case e: IOException =>
error("NIO轮询发生I/O异常", e)
}
}
/**
* 处理已完成的数据接收
* 将完整的请求提交到RequestChannel
*/
private def processCompletedReceives(): Unit = {
selector.completedReceives().asScala.foreach { receive =>
try {
val connectionId = receive.source()
val channel = selector.channel(connectionId)
// 解析请求头
val requestHeader = RequestHeader.parse(receive.payload())
val apiKey = requestHeader.apiKey()
val apiVersion = requestHeader.apiVersion()
debug(s"接收到完整请求:连接={}, API={}, 版本={}, 大小={}字节",
connectionId, apiKey, apiVersion, receive.payload().limit())
// 验证API版本
if (!apiVersionManager.isApiEnabled(apiKey, apiVersion)) {
// 不支持的API版本,发送错误响应
val errorResponse = new ApiVersionsResponse(
new ApiVersionsResponseData()
.setErrorCode(Errors.UNSUPPORTED_VERSION.code())
)
sendResponse(RequestChannel.Response.fromRequest(receive, errorResponse))
} else {
// 创建请求对象
val request = new RequestChannel.Request(
processor = id,
context = new RequestContext(requestHeader, connectionId, channel.socketAddress,
channel.principal(), listenerName, securityProtocol),
startTimeNanos = time.nanoseconds(),
memoryPool = memoryPool,
buffer = receive.payload(),
metrics = metrics,
envelope = None
)
// 提交到请求通道
requestChannel.sendRequest(request)
}
} catch {
case e: InvalidRequestException =>
warn(s"接收到无效请求,连接: ${receive.source()}", e)
closeConnection(receive.source())
case e: Throwable =>
error(s"处理接收数据时发生异常,连接: ${receive.source()}", e)
closeConnection(receive.source())
}
}
}
/**
* 处理已完成的数据发送
* 清理已发送完成的响应
*/
private def processCompletedSends(): Unit = {
selector.completedSends().asScala.foreach { send =>
val connectionId = send.destination()
// 从in-flight响应中移除
inflightResponses.remove(connectionId) match {
case Some(response) =>
debug(s"响应发送完成:连接={}, 大小={}字节",
connectionId, response.responseSize())
// 更新发送指标
updateSendMetrics(response)
case None =>
warn(s"完成发送但未找到对应的响应:连接={}", connectionId)
}
}
}
/**
* 处理断开的连接
* 清理连接相关的资源和状态
*/
private def processDisconnected(): Unit = {
selector.disconnected().asScala.foreach { connectionId =>
info(s"连接断开:{}", connectionId)
// 清理in-flight响应
inflightResponses.remove(connectionId)
// 更新连接指标
connectionQuotas.dec(getConnectionAddress(connectionId))
// 清理认证状态
clearAuthenticationState(connectionId)
}
}
/**
* 处理新的响应
* 从RequestChannel获取响应并发送给客户端
*/
private def processNewResponses(): Unit = {
var currentResponse: RequestChannel.Response = null
while ({currentResponse = requestChannel.receiveResponse(id); currentResponse != null}) {
val connectionId = currentResponse.request.context.connectionId
try {
debug(s"处理新响应:连接={}, API={}",
connectionId, currentResponse.request.header.apiKey())
// 检查连接是否仍然有效
if (selector.channel(connectionId) != null) {
// 序列化响应
val responseBuffer = serializeResponse(currentResponse)
// 创建NetworkSend
val responseSend = new NetworkSend(connectionId, responseBuffer)
// 发送响应
selector.send(responseSend)
// 添加到in-flight响应跟踪
inflightResponses.put(connectionId, currentResponse)
} else {
warn(s"尝试向已断开的连接发送响应:{}", connectionId)
}
} catch {
case e: Throwable =>
error(s"处理响应时发生异常,连接: $connectionId", e)
closeConnection(connectionId)
}
}
}
/**
* 序列化响应
* 将响应对象转换为ByteBuffer
*/
private def serializeResponse(response: RequestChannel.Response): ByteBuffer = {
val responseHeader = response.responseHeader()
val responseBody = response.responseBody()
// 计算响应大小
val headerSize = responseHeader.sizeOf()
val bodySize = responseBody.sizeOf(response.request.header.apiVersion())
val totalSize = headerSize + bodySize
// 分配缓冲区
val buffer = ByteBuffer.allocate(4 + totalSize) // 4字节长度前缀
// 写入长度前缀
buffer.putInt(totalSize)
// 序列化响应头
responseHeader.writeTo(buffer)
// 序列化响应体
responseBody.writeTo(buffer, response.request.header.apiVersion())
buffer.flip()
trace(s"序列化响应完成:总大小={}字节", buffer.remaining())
return buffer
}
}
|