You are viewing a plain text version of this content. The canonical link for it is here.
Posted to jira@kafka.apache.org by "joshua2519 (via GitHub)" <gi...@apache.org> on 2026/01/07 07:16:22 UTC
[PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
joshua2519 opened a new pull request, #21261:
URL: https://github.com/apache/kafka/pull/21261
Migrates `NodeToControllerChannelManager` and related classes from Scala (core module) to Java (server module).
### New Java Classes (server module)
- `ControllerNodeProvider` - Interface for discovering active controller
- `ControllerInformation` - Controller connection details record
- `RaftControllerNodeProvider` - KRaft implementation finding controller via Raft metadata
- `NodeToControllerChannelManagerImpl` - Manages node-to-controller communication channel
- `NodeToControllerRequestThread` - Background thread handling request queue and retries
- `NodeToControllerQueueItem` - Queued request record with timeout tracking
### Updated
- `AbstractKafkaConfig` - Added `addReconfigurable()`/`removeReconfigurable()` methods to support migration
- `KafkaConfig` - Added `override` keywords for reconfigurable methods
- Updated imports and usages across core module classes and tests
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r3170041003
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerChannelManagerImpl.java:
##########
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.clients.MetadataRecoveryStrategy;
+import org.apache.kafka.clients.NetworkClient;
+import org.apache.kafka.clients.NodeApiVersions;
+import org.apache.kafka.common.Reconfigurable;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.network.ChannelBuilder;
+import org.apache.kafka.common.network.ChannelBuilders;
+import org.apache.kafka.common.network.NetworkReceive;
+import org.apache.kafka.common.network.Selectable;
+import org.apache.kafka.common.network.Selector;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.security.JaasContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.server.common.ControllerRequestCompletionHandler;
+import org.apache.kafka.server.common.NodeToControllerChannelManager;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.config.ServerConfigs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Supplier;
+
+/**
+ * Manages a communication channel from a node to the active KRaft controller.
+ * <p>
+ * Creates a network client with the appropriate security configuration and uses a background
+ * request thread to queue and send requests asynchronously. Supports dynamic reconfiguration
+ * of security settings when the controller listener configuration changes.
+ */
+public class NodeToControllerChannelManagerImpl implements NodeToControllerChannelManager {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerChannelManagerImpl.class);
+ private final Time time;
+ private final Metrics metrics;
+ private final AbstractKafkaConfig config;
+ private final String channelName;
+ private final Long retryTimeoutMs;
+
+ private final LogContext logContext;
+ private final ManualMetadataUpdater manualMetadataUpdater = new ManualMetadataUpdater();
+ private final ApiVersions apiVersions = new ApiVersions();
+ private final NodeToControllerRequestThread requestThread;
+
+ public NodeToControllerChannelManagerImpl(Supplier<ControllerInformation> controllerNodeProvider, Time time, Metrics metrics, AbstractKafkaConfig config, String channelName, String threadNamePrefix, Long retryTimeoutMs) {
+ this.time = time;
+ this.metrics = metrics;
+ this.config = config;
+ this.channelName = channelName;
+ this.retryTimeoutMs = retryTimeoutMs;
+ this.logContext = new LogContext(String.format("[NodeToControllerChannelManager id=%s name=%s] ",
+ config.getInt(KRaftConfigs.NODE_ID_CONFIG), channelName));
+ String threadName = String.format("%sto-controller-%s-channel-manager", threadNamePrefix, channelName);
+ ControllerInformation controllerInformation = controllerNodeProvider.get();
+ this.requestThread = new NodeToControllerRequestThread(
+ buildNetworkClient(controllerInformation),
+ manualMetadataUpdater,
+ controllerNodeProvider,
+ config,
+ time,
+ threadName,
+ retryTimeoutMs
+ );
+ }
+
+ private KafkaClient buildNetworkClient(ControllerInformation controllerInfo) {
+ ChannelBuilder channelBuilder = ChannelBuilders.clientChannelBuilder(
+ controllerInfo.securityProtocol(),
+ JaasContext.Type.SERVER,
+ config,
+ controllerInfo.listenerName(),
+ controllerInfo.saslMechanism(),
+ time,
+ logContext
+ );
+ if (channelBuilder instanceof Reconfigurable reconfigurable) {
+ config.addReconfigurable(reconfigurable);
+ }
+ Selector selector = new Selector(
+ NetworkReceive.UNLIMITED,
+ Selector.NO_IDLE_TIMEOUT_MS,
+ metrics,
+ time,
+ channelName,
+ Map.of("BrokerId", String.valueOf(config.brokerId())),
+ false,
+ channelBuilder,
+ logContext
+ );
+ return new NetworkClient(
+ selector,
+ manualMetadataUpdater,
+ String.valueOf(config.brokerId()),
+ 1,
+ 50,
+ 50,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), // request timeout should not exceed the provided retry timeout
Review Comment:
we should migrate `controllerSocketTimeoutMs` from `KafkaConfig` to `AbstractKafkaConfig`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2682333169
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerChannelManagerImpl.java:
##########
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.clients.MetadataRecoveryStrategy;
+import org.apache.kafka.clients.NetworkClient;
+import org.apache.kafka.clients.NodeApiVersions;
+import org.apache.kafka.common.Reconfigurable;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.network.ChannelBuilder;
+import org.apache.kafka.common.network.ChannelBuilders;
+import org.apache.kafka.common.network.NetworkReceive;
+import org.apache.kafka.common.network.Selectable;
+import org.apache.kafka.common.network.Selector;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.security.JaasContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.server.common.ControllerRequestCompletionHandler;
+import org.apache.kafka.server.common.NodeToControllerChannelManager;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.config.ServerConfigs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Manages a communication channel from a node to the active KRaft controller.
+ * <p>
+ * Creates a network client with the appropriate security configuration and uses a background
+ * request thread to queue and send requests asynchronously. Supports dynamic reconfiguration
+ * of security settings when the controller listener configuration changes.
+ */
+public class NodeToControllerChannelManagerImpl implements NodeToControllerChannelManager {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerChannelManagerImpl.class);
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final Time time;
+ private final Metrics metrics;
+ private final AbstractKafkaConfig config;
+ private final String channelName;
+ private final String threadNamePrefix;
+ private final Long retryTimeoutMs;
+
+ private final LogContext logContext;
+ private final ManualMetadataUpdater manualMetadataUpdater = new ManualMetadataUpdater();
+ private final ApiVersions apiVersions = new ApiVersions();
+ private final NodeToControllerRequestThread requestThread;
+
+ @SuppressWarnings("this-escape")
Review Comment:
Done.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2684665675
##########
server/src/main/java/org/apache/kafka/server/ControllerNodeProvider.java:
##########
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import java.util.function.Supplier;
+
+/**
+ * Discovers the active controller node and provides connection details for communicating with it.
+ */
+public interface ControllerNodeProvider extends Supplier<ControllerInformation> {
Review Comment:
Done. Replaced ControllerNodeProvider with Supplier<ControllerInformation> throughout the codebase since there's only one production implementation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 merged PR #21261:
URL: https://github.com/apache/kafka/pull/21261
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2682336182
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
+ time.milliseconds(),
+ controllerAddress.get(),
+ request.request(),
+ response -> handleResponse(request, response)
+ ));
+ }
+ }
+ }
+
+ return Collections.emptyList();
+ }
+
+ void handleResponse(NodeToControllerQueueItem queueItem, ClientResponse response) {
+ log.debug("Request {} received {}", queueItem.request(), response);
+ if (response.authenticationException() != null) {
+ log.error("Request {} failed due to authentication error with controller. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(), activeControllerAddress().map(Node::idString).orElse("null"),
+ response.authenticationException()
+ );
+ maybeDisconnectAndUpdateController();
+ queueItem.callback().onComplete(response);
+ } else if (response.versionMismatch() != null) {
+ log.error("Request {} failed due to unsupported version error", queueItem.request(),
+ response.versionMismatch());
+ queueItem.callback().onComplete(response);
+ } else if (response.wasDisconnected()) {
+ updateControllerAddress(null);
+ try {
+ requestQueue.putFirst(queueItem);
Review Comment:
Agreed. Since requestQueue is unbounded (LinkedBlockingDeque with no capacity limit), putFirst() will never block and the InterruptedException handling is unnecessary. Changed to addFirst() for simplicity.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2682325385
##########
server/src/main/java/org/apache/kafka/server/ControllerNodeProvider.java:
##########
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+/**
+ * Discovers the active controller node and provides connection details for communicating with it.
+ */
+public interface ControllerNodeProvider {
Review Comment:
Done. ControllerNodeProvider now extends Supplier<ControllerInformation> for better idiomatic Java usage.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2683128351
##########
server/src/main/java/org/apache/kafka/server/ControllerNodeProvider.java:
##########
@@ -0,0 +1,26 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import java.util.function.Supplier;
+
+/**
+ * Discovers the active controller node and provides connection details for communicating with it.
+ */
+public interface ControllerNodeProvider extends Supplier<ControllerInformation> {
Review Comment:
I meant that the standard `Supplier<ControllerInformation>` interface could simply replace `ControllerNodeProvider`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2683156628
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerChannelManagerImpl.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.clients.MetadataRecoveryStrategy;
+import org.apache.kafka.clients.NetworkClient;
+import org.apache.kafka.clients.NodeApiVersions;
+import org.apache.kafka.common.Reconfigurable;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.network.ChannelBuilder;
+import org.apache.kafka.common.network.ChannelBuilders;
+import org.apache.kafka.common.network.NetworkReceive;
+import org.apache.kafka.common.network.Selectable;
+import org.apache.kafka.common.network.Selector;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.security.JaasContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.server.common.ControllerRequestCompletionHandler;
+import org.apache.kafka.server.common.NodeToControllerChannelManager;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.config.ServerConfigs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Manages a communication channel from a node to the active KRaft controller.
+ * <p>
+ * Creates a network client with the appropriate security configuration and uses a background
+ * request thread to queue and send requests asynchronously. Supports dynamic reconfiguration
+ * of security settings when the controller listener configuration changes.
+ */
+public class NodeToControllerChannelManagerImpl implements NodeToControllerChannelManager {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerChannelManagerImpl.class);
+ private final Time time;
+ private final Metrics metrics;
+ private final AbstractKafkaConfig config;
+ private final String channelName;
+ private final Long retryTimeoutMs;
+
+ private final LogContext logContext;
+ private final ManualMetadataUpdater manualMetadataUpdater = new ManualMetadataUpdater();
+ private final ApiVersions apiVersions = new ApiVersions();
+ private final NodeToControllerRequestThread requestThread;
+
+ public NodeToControllerChannelManagerImpl(ControllerNodeProvider controllerNodeProvider, Time time, Metrics metrics, AbstractKafkaConfig config, String channelName, String threadNamePrefix, Long retryTimeoutMs) {
+ this.time = time;
+ this.metrics = metrics;
+ this.config = config;
+ this.channelName = channelName;
+ this.retryTimeoutMs = retryTimeoutMs;
+ this.logContext = new LogContext(String.format("[NodeToControllerChannelManager id=%s name=%s] ",
+ config.getInt(KRaftConfigs.NODE_ID_CONFIG), channelName));
+ String threadName = String.format("%sto-controller-%s-channel-manager", threadNamePrefix, channelName);
+ ControllerInformation controllerInformation = controllerNodeProvider.get();
+ this.requestThread = new NodeToControllerRequestThread(
+ buildNetworkClient(controllerInformation),
+ manualMetadataUpdater,
+ controllerNodeProvider,
+ config,
+ time,
+ threadName,
+ retryTimeoutMs
+ );
+ }
+
+ private KafkaClient buildNetworkClient(ControllerInformation controllerInfo) {
+ ChannelBuilder channelBuilder = ChannelBuilders.clientChannelBuilder(
+ controllerInfo.securityProtocol(),
+ JaasContext.Type.SERVER,
+ config,
+ controllerInfo.listenerName(),
+ controllerInfo.saslMechanism(),
+ time,
+ logContext
+ );
+ if (channelBuilder instanceof Reconfigurable reconfigurable) {
+ config.addReconfigurable(reconfigurable);
+ }
+ Selector selector = new Selector(
+ NetworkReceive.UNLIMITED,
+ Selector.NO_IDLE_TIMEOUT_MS,
+ metrics,
+ time,
+ channelName,
+ Map.of("BrokerId", String.valueOf(config.brokerId())),
+ false,
+ channelBuilder,
+ logContext
+ );
+ return new NetworkClient(
+ selector,
+ manualMetadataUpdater,
+ String.valueOf(config.brokerId()),
+ 1,
+ 50,
+ 50,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), // request timeout should not exceed the provided retry timeout
+ config.getLong(ServerConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG),
+ config.getLong(ServerConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG),
+ time,
+ true,
+ apiVersions,
+ logContext,
+ MetadataRecoveryStrategy.NONE
+ );
+ }
+
+ @Override
+ public void start() {
+ requestThread.start();
+ }
+
+ @Override
+ public void shutdown() {
Review Comment:
We should throw an exception here to align with the Scala implementation
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
Review Comment:
`List.of`
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
+ time.milliseconds(),
+ controllerAddress.get(),
+ request.request(),
+ response -> handleResponse(request, response)
+ ));
+ }
+ }
+ }
+
+ return Collections.emptyList();
+ }
+
+ void handleResponse(NodeToControllerQueueItem queueItem, ClientResponse response) {
+ log.debug("Request {} received {}", queueItem.request(), response);
+ if (response.authenticationException() != null) {
+ log.error("Request {} failed due to authentication error with controller. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(), activeControllerAddress().map(Node::idString).orElse("null"),
+ response.authenticationException()
+ );
+ maybeDisconnectAndUpdateController();
+ queueItem.callback().onComplete(response);
+ } else if (response.versionMismatch() != null) {
+ log.error("Request {} failed due to unsupported version error", queueItem.request(),
+ response.versionMismatch());
+ queueItem.callback().onComplete(response);
+ } else if (response.wasDisconnected()) {
+ updateControllerAddress(null);
+ requestQueue.addFirst(queueItem);
+ } else if (response.responseBody().errorCounts().containsKey(Errors.NOT_CONTROLLER)) {
+ log.debug("Request {} received NOT_CONTROLLER exception. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(),
+ activeControllerAddress().map(Node::idString).orElse("null"));
+ maybeDisconnectAndUpdateController();
+ try {
+ requestQueue.putFirst(queueItem);
Review Comment:
`addFirst`?
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
+ time.milliseconds(),
+ controllerAddress.get(),
+ request.request(),
+ response -> handleResponse(request, response)
+ ));
+ }
+ }
+ }
+
+ return Collections.emptyList();
Review Comment:
`List.of`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2684655217
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
+ time.milliseconds(),
+ controllerAddress.get(),
+ request.request(),
+ response -> handleResponse(request, response)
+ ));
+ }
+ }
+ }
+
+ return Collections.emptyList();
+ }
+
+ void handleResponse(NodeToControllerQueueItem queueItem, ClientResponse response) {
+ log.debug("Request {} received {}", queueItem.request(), response);
+ if (response.authenticationException() != null) {
+ log.error("Request {} failed due to authentication error with controller. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(), activeControllerAddress().map(Node::idString).orElse("null"),
+ response.authenticationException()
+ );
+ maybeDisconnectAndUpdateController();
+ queueItem.callback().onComplete(response);
+ } else if (response.versionMismatch() != null) {
+ log.error("Request {} failed due to unsupported version error", queueItem.request(),
+ response.versionMismatch());
+ queueItem.callback().onComplete(response);
+ } else if (response.wasDisconnected()) {
+ updateControllerAddress(null);
+ requestQueue.addFirst(queueItem);
+ } else if (response.responseBody().errorCounts().containsKey(Errors.NOT_CONTROLLER)) {
+ log.debug("Request {} received NOT_CONTROLLER exception. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(),
+ activeControllerAddress().map(Node::idString).orElse("null"));
+ maybeDisconnectAndUpdateController();
+ try {
+ requestQueue.putFirst(queueItem);
Review Comment:
Done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2693079687
##########
server/src/main/java/org/apache/kafka/server/RaftControllerNodeProvider.java:
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.network.ListenerName;
+import org.apache.kafka.common.security.auth.SecurityProtocol;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.raft.RaftManager;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.function.Supplier;
+
+/**
+ * Finds the controller node by checking the metadata log manager.
+ * This provider is used when we are using a Raft-based metadata quorum.
+ */
+public class RaftControllerNodeProvider implements Supplier<ControllerInformation> {
+
+ private final RaftManager<ApiMessageAndVersion> raftManager;
+ private final ListenerName listenerName;
+ private final SecurityProtocol securityProtocol;
+ private final String saslMechanism;
+
+ public static RaftControllerNodeProvider create(RaftManager<ApiMessageAndVersion> raftManager, AbstractKafkaConfig config) {
+ final ListenerName controllerListenerName = new ListenerName(config.controllerListenerNames().get(0));
+ final SecurityProtocol controllerSecurityProtocol = Optional.ofNullable(config.effectiveListenerSecurityProtocolMap().get(controllerListenerName))
+ .orElseGet(() -> SecurityProtocol.forName(controllerListenerName.value()));
+ final String controllerSaslMechanism = config.getString(KRaftConfigs.SASL_MECHANISM_CONTROLLER_PROTOCOL_CONFIG);
+ return new RaftControllerNodeProvider(raftManager, controllerListenerName, controllerSecurityProtocol, controllerSaslMechanism);
+ }
+
+ public RaftControllerNodeProvider(RaftManager<ApiMessageAndVersion> raftManager, ListenerName listenerName, SecurityProtocol securityProtocol, String saslMechanism) {
+ this.raftManager = raftManager;
+ this.listenerName = listenerName;
+ this.securityProtocol = securityProtocol;
+ this.saslMechanism = saslMechanism;
+ }
+
+ @SuppressWarnings("resource") // RaftClient lifecycle managed by RaftManager
+ private Optional<Node> idToNode(int id) {
Review Comment:
Agreed, I have inlined to get().
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2690329363
##########
server/src/main/java/org/apache/kafka/server/RaftControllerNodeProvider.java:
##########
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.network.ListenerName;
+import org.apache.kafka.common.security.auth.SecurityProtocol;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.raft.RaftManager;
+import org.apache.kafka.server.common.ApiMessageAndVersion;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.util.function.Supplier;
+
+/**
+ * Finds the controller node by checking the metadata log manager.
+ * This provider is used when we are using a Raft-based metadata quorum.
+ */
+public class RaftControllerNodeProvider implements Supplier<ControllerInformation> {
+
+ private final RaftManager<ApiMessageAndVersion> raftManager;
+ private final ListenerName listenerName;
+ private final SecurityProtocol securityProtocol;
+ private final String saslMechanism;
+
+ public static RaftControllerNodeProvider create(RaftManager<ApiMessageAndVersion> raftManager, AbstractKafkaConfig config) {
+ final ListenerName controllerListenerName = new ListenerName(config.controllerListenerNames().get(0));
+ final SecurityProtocol controllerSecurityProtocol = Optional.ofNullable(config.effectiveListenerSecurityProtocolMap().get(controllerListenerName))
+ .orElseGet(() -> SecurityProtocol.forName(controllerListenerName.value()));
+ final String controllerSaslMechanism = config.getString(KRaftConfigs.SASL_MECHANISM_CONTROLLER_PROTOCOL_CONFIG);
+ return new RaftControllerNodeProvider(raftManager, controllerListenerName, controllerSecurityProtocol, controllerSaslMechanism);
+ }
+
+ public RaftControllerNodeProvider(RaftManager<ApiMessageAndVersion> raftManager, ListenerName listenerName, SecurityProtocol securityProtocol, String saslMechanism) {
+ this.raftManager = raftManager;
+ this.listenerName = listenerName;
+ this.securityProtocol = securityProtocol;
+ this.saslMechanism = saslMechanism;
+ }
+
+ @SuppressWarnings("resource") // RaftClient lifecycle managed by RaftManager
+ private Optional<Node> idToNode(int id) {
Review Comment:
Do we really need this private method? Having two `@SuppressWarnings` seems to double the noise
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2684804401
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerChannelManagerImpl.java:
##########
@@ -0,0 +1,179 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.clients.MetadataRecoveryStrategy;
+import org.apache.kafka.clients.NetworkClient;
+import org.apache.kafka.clients.NodeApiVersions;
+import org.apache.kafka.common.Reconfigurable;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.network.ChannelBuilder;
+import org.apache.kafka.common.network.ChannelBuilders;
+import org.apache.kafka.common.network.NetworkReceive;
+import org.apache.kafka.common.network.Selectable;
+import org.apache.kafka.common.network.Selector;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.security.JaasContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.server.common.ControllerRequestCompletionHandler;
+import org.apache.kafka.server.common.NodeToControllerChannelManager;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.config.ServerConfigs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Manages a communication channel from a node to the active KRaft controller.
+ * <p>
+ * Creates a network client with the appropriate security configuration and uses a background
+ * request thread to queue and send requests asynchronously. Supports dynamic reconfiguration
+ * of security settings when the controller listener configuration changes.
+ */
+public class NodeToControllerChannelManagerImpl implements NodeToControllerChannelManager {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerChannelManagerImpl.class);
+ private final Time time;
+ private final Metrics metrics;
+ private final AbstractKafkaConfig config;
+ private final String channelName;
+ private final Long retryTimeoutMs;
+
+ private final LogContext logContext;
+ private final ManualMetadataUpdater manualMetadataUpdater = new ManualMetadataUpdater();
+ private final ApiVersions apiVersions = new ApiVersions();
+ private final NodeToControllerRequestThread requestThread;
+
+ public NodeToControllerChannelManagerImpl(ControllerNodeProvider controllerNodeProvider, Time time, Metrics metrics, AbstractKafkaConfig config, String channelName, String threadNamePrefix, Long retryTimeoutMs) {
+ this.time = time;
+ this.metrics = metrics;
+ this.config = config;
+ this.channelName = channelName;
+ this.retryTimeoutMs = retryTimeoutMs;
+ this.logContext = new LogContext(String.format("[NodeToControllerChannelManager id=%s name=%s] ",
+ config.getInt(KRaftConfigs.NODE_ID_CONFIG), channelName));
+ String threadName = String.format("%sto-controller-%s-channel-manager", threadNamePrefix, channelName);
+ ControllerInformation controllerInformation = controllerNodeProvider.get();
+ this.requestThread = new NodeToControllerRequestThread(
+ buildNetworkClient(controllerInformation),
+ manualMetadataUpdater,
+ controllerNodeProvider,
+ config,
+ time,
+ threadName,
+ retryTimeoutMs
+ );
+ }
+
+ private KafkaClient buildNetworkClient(ControllerInformation controllerInfo) {
+ ChannelBuilder channelBuilder = ChannelBuilders.clientChannelBuilder(
+ controllerInfo.securityProtocol(),
+ JaasContext.Type.SERVER,
+ config,
+ controllerInfo.listenerName(),
+ controllerInfo.saslMechanism(),
+ time,
+ logContext
+ );
+ if (channelBuilder instanceof Reconfigurable reconfigurable) {
+ config.addReconfigurable(reconfigurable);
+ }
+ Selector selector = new Selector(
+ NetworkReceive.UNLIMITED,
+ Selector.NO_IDLE_TIMEOUT_MS,
+ metrics,
+ time,
+ channelName,
+ Map.of("BrokerId", String.valueOf(config.brokerId())),
+ false,
+ channelBuilder,
+ logContext
+ );
+ return new NetworkClient(
+ selector,
+ manualMetadataUpdater,
+ String.valueOf(config.brokerId()),
+ 1,
+ 50,
+ 50,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Selectable.USE_DEFAULT_BUFFER_SIZE,
+ Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), // request timeout should not exceed the provided retry timeout
+ config.getLong(ServerConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG),
+ config.getLong(ServerConfigs.SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG),
+ time,
+ true,
+ apiVersions,
+ logContext,
+ MetadataRecoveryStrategy.NONE
+ );
+ }
+
+ @Override
+ public void start() {
+ requestThread.start();
+ }
+
+ @Override
+ public void shutdown() {
Review Comment:
Done. Updated shutdown() to declare `throws InterruptedException` allowing the exception to propagate instead of being swallowed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "joshua2519 (via GitHub)" <gi...@apache.org>.
joshua2519 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2682329821
##########
server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java:
##########
@@ -207,4 +208,30 @@ private static String parseListenerName(String connectionString) {
}
return connectionString.substring(0, firstColon).toUpperCase(Locale.ROOT);
}
+
+ /**
+ * Registers a component for dynamic reconfiguration notifications.
+ * <p>
+ * This method exists to support migration from kafka.server.KafkaConfig (Scala/core) to AbstractKafkaConfig (Java/server).
+ * When migrating code, replace KafkaConfig references with AbstractKafkaConfig. The default implementation is a no-op;
+ * KafkaConfig overrides this to manage the reconfigurable registry.
+ *
+ * @param reconfigurable the component to register for configuration updates
+ */
+ public void addReconfigurable(Reconfigurable reconfigurable) {
Review Comment:
Agreed and changed. Since all current implementations (KafkaConfig) already provide concrete implementations, making them abstract clarifies the contract and ensures future subclasses don't accidentally rely on no-op behavior.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] KAFKA-20012: Move NodeToControllerChannelManagerImpl to server module [kafka]
Posted by "chia7712 (via GitHub)" <gi...@apache.org>.
chia7712 commented on code in PR #21261:
URL: https://github.com/apache/kafka/pull/21261#discussion_r2678865866
##########
server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java:
##########
@@ -207,4 +208,30 @@ private static String parseListenerName(String connectionString) {
}
return connectionString.substring(0, firstColon).toUpperCase(Locale.ROOT);
}
+
+ /**
+ * Registers a component for dynamic reconfiguration notifications.
+ * <p>
+ * This method exists to support migration from kafka.server.KafkaConfig (Scala/core) to AbstractKafkaConfig (Java/server).
+ * When migrating code, replace KafkaConfig references with AbstractKafkaConfig. The default implementation is a no-op;
+ * KafkaConfig overrides this to manage the reconfigurable registry.
+ *
+ * @param reconfigurable the component to register for configuration updates
+ */
+ public void addReconfigurable(Reconfigurable reconfigurable) {
Review Comment:
why we don't set it as abstract method?
##########
server/src/main/java/org/apache/kafka/server/config/AbstractKafkaConfig.java:
##########
@@ -207,4 +208,30 @@ private static String parseListenerName(String connectionString) {
}
return connectionString.substring(0, firstColon).toUpperCase(Locale.ROOT);
}
+
+ /**
+ * Registers a component for dynamic reconfiguration notifications.
+ * <p>
+ * This method exists to support migration from kafka.server.KafkaConfig (Scala/core) to AbstractKafkaConfig (Java/server).
+ * When migrating code, replace KafkaConfig references with AbstractKafkaConfig. The default implementation is a no-op;
+ * KafkaConfig overrides this to manage the reconfigurable registry.
+ *
+ * @param reconfigurable the component to register for configuration updates
+ */
+ public void addReconfigurable(Reconfigurable reconfigurable) {
+ // Default no-op. Overridden by KafkaConfig to support dynamic configuration.
+ }
+
+ /**
+ * Unregisters a component from dynamic reconfiguration notifications.
+ * <p>
+ * This method exists to support migration from kafka.server.KafkaConfig (Scala/core) to AbstractKafkaConfig (Java/server).
+ * When migrating code, replace KafkaConfig references with AbstractKafkaConfig. The default implementation is a no-op;
+ * KafkaConfig overrides this to remove components from the registry.
+ *
+ * @param reconfigurable the component to unregister
+ */
+ public void removeReconfigurable(Reconfigurable reconfigurable) {
Review Comment:
ditto
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerChannelManagerImpl.java:
##########
@@ -0,0 +1,188 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ApiVersions;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.clients.MetadataRecoveryStrategy;
+import org.apache.kafka.clients.NetworkClient;
+import org.apache.kafka.clients.NodeApiVersions;
+import org.apache.kafka.common.Reconfigurable;
+import org.apache.kafka.common.metrics.Metrics;
+import org.apache.kafka.common.network.ChannelBuilder;
+import org.apache.kafka.common.network.ChannelBuilders;
+import org.apache.kafka.common.network.NetworkReceive;
+import org.apache.kafka.common.network.Selectable;
+import org.apache.kafka.common.network.Selector;
+import org.apache.kafka.common.requests.AbstractRequest;
+import org.apache.kafka.common.security.JaasContext;
+import org.apache.kafka.common.utils.LogContext;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.raft.KRaftConfigs;
+import org.apache.kafka.server.common.ControllerRequestCompletionHandler;
+import org.apache.kafka.server.common.NodeToControllerChannelManager;
+import org.apache.kafka.server.config.AbstractKafkaConfig;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.config.ServerConfigs;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Manages a communication channel from a node to the active KRaft controller.
+ * <p>
+ * Creates a network client with the appropriate security configuration and uses a background
+ * request thread to queue and send requests asynchronously. Supports dynamic reconfiguration
+ * of security settings when the controller listener configuration changes.
+ */
+public class NodeToControllerChannelManagerImpl implements NodeToControllerChannelManager {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerChannelManagerImpl.class);
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final Time time;
+ private final Metrics metrics;
+ private final AbstractKafkaConfig config;
+ private final String channelName;
+ private final String threadNamePrefix;
+ private final Long retryTimeoutMs;
+
+ private final LogContext logContext;
+ private final ManualMetadataUpdater manualMetadataUpdater = new ManualMetadataUpdater();
+ private final ApiVersions apiVersions = new ApiVersions();
+ private final NodeToControllerRequestThread requestThread;
+
+ @SuppressWarnings("this-escape")
Review Comment:
Would you mind inlining `newRequestThread` to get rid of this warning?
##########
server/src/main/java/org/apache/kafka/server/ControllerNodeProvider.java:
##########
@@ -0,0 +1,25 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+/**
+ * Discovers the active controller node and provides connection details for communicating with it.
+ */
+public interface ControllerNodeProvider {
Review Comment:
Could we use `Supplier<ControllerInformation>` instead?
##########
server/src/main/java/org/apache/kafka/server/NodeToControllerRequestThread.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.kafka.server;
+
+import org.apache.kafka.clients.ClientResponse;
+import org.apache.kafka.clients.KafkaClient;
+import org.apache.kafka.clients.ManualMetadataUpdater;
+import org.apache.kafka.common.Node;
+import org.apache.kafka.common.config.AbstractConfig;
+import org.apache.kafka.common.protocol.Errors;
+import org.apache.kafka.common.utils.Time;
+import org.apache.kafka.server.config.ReplicationConfigs;
+import org.apache.kafka.server.util.InterBrokerSendThread;
+import org.apache.kafka.server.util.RequestAndCompletionHandler;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Background thread that manages to send requests to the active controller.
+ * <p>
+ * Maintains a queue of pending requests and handles automatic retries on failures,
+ * controller failover, and timeout detection. Requests are re-queued when the controller
+ * changes or connections are lost.
+ */
+public class NodeToControllerRequestThread extends InterBrokerSendThread {
+ private static final Logger log = LoggerFactory.getLogger(NodeToControllerRequestThread.class);
+
+ private final LinkedBlockingDeque<NodeToControllerQueueItem> requestQueue = new LinkedBlockingDeque<>();
+ private final AtomicReference<Node> activeController = new AtomicReference<>(null);
+
+
+ private final Time time;
+ private final long retryTimeoutMs;
+ private final ControllerNodeProvider controllerNodeProvider;
+ private final ManualMetadataUpdater metadataUpdater;
+
+ // Used for testing
+ volatile boolean started = false;
+ public void setStarted(boolean started) {
+ this.started = started;
+ }
+
+ public NodeToControllerRequestThread(KafkaClient initialNetworkClient,
+ ManualMetadataUpdater metadataUpdater,
+ ControllerNodeProvider controllerNodeProvider,
+ AbstractConfig config,
+ Time time,
+ String threadName,
+ Long retryTimeoutMs) {
+ super(threadName, initialNetworkClient, Math.min(Integer.MAX_VALUE, (int) Math.min(config.getInt(ReplicationConfigs.CONTROLLER_SOCKET_TIMEOUT_MS_CONFIG), retryTimeoutMs)), time, false);
+ this.time = time;
+ this.controllerNodeProvider = controllerNodeProvider;
+ this.metadataUpdater = metadataUpdater;
+ this.retryTimeoutMs = retryTimeoutMs;
+ }
+
+ public Optional<Node> activeControllerAddress() {
+ return Optional.ofNullable(activeController.get());
+ }
+
+ private void updateControllerAddress(Node newActiveController) {
+ activeController.set(newActiveController);
+ }
+
+ public void enqueue(NodeToControllerQueueItem request) {
+ if (!started) {
+ throw new IllegalStateException("Cannot enqueue a request if the request thread is not running");
+ }
+ requestQueue.add(request);
+ if (activeControllerAddress().isPresent()) {
+ wakeup();
+ }
+ }
+
+ public int queueSize() {
+ return requestQueue.size();
+ }
+
+ @Override
+ public Collection<RequestAndCompletionHandler> generateRequests() {
+ final long currentTimeMs = time.milliseconds();
+ final Iterator<NodeToControllerQueueItem> requestIter = requestQueue.iterator();
+ while (requestIter.hasNext()) {
+ var request = requestIter.next();
+ if (currentTimeMs - request.createdTimeMs() >= retryTimeoutMs) {
+ requestIter.remove();
+ request.callback().onTimeout();
+ } else {
+ Optional<Node> controllerAddress = activeControllerAddress();
+ if (controllerAddress.isPresent()) {
+ requestIter.remove();
+ return Collections.singletonList(new RequestAndCompletionHandler(
+ time.milliseconds(),
+ controllerAddress.get(),
+ request.request(),
+ response -> handleResponse(request, response)
+ ));
+ }
+ }
+ }
+
+ return Collections.emptyList();
+ }
+
+ void handleResponse(NodeToControllerQueueItem queueItem, ClientResponse response) {
+ log.debug("Request {} received {}", queueItem.request(), response);
+ if (response.authenticationException() != null) {
+ log.error("Request {} failed due to authentication error with controller. Disconnecting the " +
+ "connection to the stale controller {}",
+ queueItem.request(), activeControllerAddress().map(Node::idString).orElse("null"),
+ response.authenticationException()
+ );
+ maybeDisconnectAndUpdateController();
+ queueItem.callback().onComplete(response);
+ } else if (response.versionMismatch() != null) {
+ log.error("Request {} failed due to unsupported version error", queueItem.request(),
+ response.versionMismatch());
+ queueItem.callback().onComplete(response);
+ } else if (response.wasDisconnected()) {
+ updateControllerAddress(null);
+ try {
+ requestQueue.putFirst(queueItem);
Review Comment:
We can substitute `addFirst` for `putFirst`, since `requestQueue` is an unbounded `LinkedBlockingDeque`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: jira-unsubscribe@kafka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org