Skip to content

Commit 81881de

Browse files
KAFKA-18760: Deprecate Optional<String> and return String from public Endpoint#listener (#19191)
* Deprecate org.apache.kafka.common.Endpoint#listenerName. * Add org.apache.kafka.common.Endpoint#listener to replace org.apache.kafka.common.Endpoint#listenerName. * Replace org.apache.kafka.network.EndPoint with org.apache.kafka.common.Endpoint. * Deprecate org.apache.kafka.clients.admin.RaftVoterEndpoint#name * Add org.apache.kafka.clients.admin.RaftVoterEndpoint#listener to replace org.apache.kafka.clients.admin.RaftVoterEndpoint#name Reviewers: Chia-Ping Tsai <chia7712@gmail.com>, TaiJuWu <tjwu1217@gmail.com>, Jhen-Yung Hsu <jhenyunghsu@gmail.com>, TengYao Chi <frankvicky@apache.org>, Ken Huang <s7133700@gmail.com>, Bagda Parth , Kuan-Po Tseng <brandboat@gmail.com> --------- Signed-off-by: PoAn Yang <payang@apache.org>
1 parent 676e0f2 commit 81881de

File tree

30 files changed

+179
-200
lines changed

30 files changed

+179
-200
lines changed

clients/src/main/java/org/apache/kafka/clients/admin/KafkaAdminClient.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4948,7 +4948,7 @@ AddRaftVoterRequest.Builder createRequest(int timeoutMs) {
49484948
new AddRaftVoterRequestData.ListenerCollection();
49494949
endpoints.forEach(endpoint ->
49504950
listeners.add(new AddRaftVoterRequestData.Listener().
4951-
setName(endpoint.name()).
4951+
setName(endpoint.listener()).
49524952
setHost(endpoint.host()).
49534953
setPort(endpoint.port())));
49544954
return new AddRaftVoterRequest.Builder(

clients/src/main/java/org/apache/kafka/clients/admin/RaftVoterEndpoint.java

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
*/
2727
@InterfaceStability.Stable
2828
public class RaftVoterEndpoint {
29-
private final String name;
29+
private final String listener;
3030
private final String host;
3131
private final int port;
3232

@@ -49,22 +49,33 @@ static String requireNonNullAllCapsNonEmpty(String input) {
4949
/**
5050
* Create an endpoint for a metadata quorum voter.
5151
*
52-
* @param name The human-readable name for this endpoint. For example, CONTROLLER.
52+
* @param listener The human-readable name for this endpoint. For example, CONTROLLER.
5353
* @param host The DNS hostname for this endpoint.
5454
* @param port The network port for this endpoint.
5555
*/
5656
public RaftVoterEndpoint(
57-
String name,
57+
String listener,
5858
String host,
5959
int port
6060
) {
61-
this.name = requireNonNullAllCapsNonEmpty(name);
61+
this.listener = requireNonNullAllCapsNonEmpty(listener);
6262
this.host = Objects.requireNonNull(host);
6363
this.port = port;
6464
}
6565

66+
/**
67+
* The listener name for this endpoint.
68+
*/
69+
public String listener() {
70+
return listener;
71+
}
72+
73+
/**
74+
* @deprecated Since 4.1. Use {@link #listener()} instead. This function will be removed in 5.0.
75+
*/
76+
@Deprecated(since = "4.1", forRemoval = true)
6677
public String name() {
67-
return name;
78+
return listener;
6879
}
6980

7081
public String host() {
@@ -79,20 +90,20 @@ public int port() {
7990
public boolean equals(Object o) {
8091
if (o == null || (!o.getClass().equals(getClass()))) return false;
8192
RaftVoterEndpoint other = (RaftVoterEndpoint) o;
82-
return name.equals(other.name) &&
93+
return listener.equals(other.listener) &&
8394
host.equals(other.host) &&
8495
port == other.port;
8596
}
8697

8798
@Override
8899
public int hashCode() {
89-
return Objects.hash(name, host, port);
100+
return Objects.hash(listener, host, port);
90101
}
91102

92103
@Override
93104
public String toString() {
94105
// enclose IPv6 hosts in square brackets for readability
95106
String hostString = host.contains(":") ? "[" + host + "]" : host;
96-
return name + "://" + hostString + ":" + port;
107+
return listener + "://" + hostString + ":" + port;
97108
}
98109
}

clients/src/main/java/org/apache/kafka/common/Endpoint.java

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
*/
1717
package org.apache.kafka.common;
1818

19-
import org.apache.kafka.common.annotation.InterfaceStability;
2019
import org.apache.kafka.common.security.auth.SecurityProtocol;
2120

2221
import java.util.Objects;
@@ -26,27 +25,35 @@
2625
* Represents a broker endpoint.
2726
*/
2827

29-
@InterfaceStability.Evolving
3028
public class Endpoint {
3129

32-
private final String listenerName;
30+
private final String listener;
3331
private final SecurityProtocol securityProtocol;
3432
private final String host;
3533
private final int port;
3634

37-
public Endpoint(String listenerName, SecurityProtocol securityProtocol, String host, int port) {
38-
this.listenerName = listenerName;
35+
public Endpoint(String listener, SecurityProtocol securityProtocol, String host, int port) {
36+
this.listener = listener;
3937
this.securityProtocol = securityProtocol;
4038
this.host = host;
4139
this.port = port;
4240
}
4341

42+
/**
43+
* Returns the listener name of this endpoint.
44+
*/
45+
public String listener() {
46+
return listener;
47+
}
48+
4449
/**
4550
* Returns the listener name of this endpoint. This is non-empty for endpoints provided
4651
* to broker plugins, but may be empty when used in clients.
52+
* @deprecated Since 4.1. Use {@link #listener()} instead. This function will be removed in 5.0.
4753
*/
54+
@Deprecated(since = "4.1", forRemoval = true)
4855
public Optional<String> listenerName() {
49-
return Optional.ofNullable(listenerName);
56+
return Optional.ofNullable(listener);
5057
}
5158

5259
/**
@@ -80,7 +87,7 @@ public boolean equals(Object o) {
8087
}
8188

8289
Endpoint that = (Endpoint) o;
83-
return Objects.equals(this.listenerName, that.listenerName) &&
90+
return Objects.equals(this.listener, that.listener) &&
8491
Objects.equals(this.securityProtocol, that.securityProtocol) &&
8592
Objects.equals(this.host, that.host) &&
8693
this.port == that.port;
@@ -89,13 +96,13 @@ public boolean equals(Object o) {
8996

9097
@Override
9198
public int hashCode() {
92-
return Objects.hash(listenerName, securityProtocol, host, port);
99+
return Objects.hash(listener, securityProtocol, host, port);
93100
}
94101

95102
@Override
96103
public String toString() {
97104
return "Endpoint(" +
98-
"listenerName='" + listenerName + '\'' +
105+
"listenerName='" + listener + '\'' +
99106
", securityProtocol=" + securityProtocol +
100107
", host='" + host + '\'' +
101108
", port=" + port +

core/src/main/scala/kafka/network/SocketServer.scala

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ import kafka.network.Processor._
2929
import kafka.network.RequestChannel.{CloseConnectionResponse, EndThrottlingResponse, NoOpResponse, SendResponse, StartThrottlingResponse}
3030
import kafka.network.SocketServer._
3131
import kafka.server.{BrokerReconfigurable, KafkaConfig}
32-
import org.apache.kafka.network.EndPoint
3332
import org.apache.kafka.common.message.ApiMessageType.ListenerType
3433
import kafka.utils._
3534
import org.apache.kafka.common.config.ConfigException
@@ -96,7 +95,7 @@ class SocketServer(
9695
memoryPoolSensor.add(new Meter(TimeUnit.MILLISECONDS, memoryPoolDepletedPercentMetricName, memoryPoolDepletedTimeMetricName))
9796
private val memoryPool = if (config.queuedMaxBytes > 0) new SimpleMemoryPool(config.queuedMaxBytes, config.socketRequestMaxBytes, false, memoryPoolSensor) else MemoryPool.NONE
9897
// data-plane
99-
private[network] val dataPlaneAcceptors = new ConcurrentHashMap[EndPoint, DataPlaneAcceptor]()
98+
private[network] val dataPlaneAcceptors = new ConcurrentHashMap[Endpoint, DataPlaneAcceptor]()
10099
val dataPlaneRequestChannel = new RequestChannel(maxQueuedRequests, time, apiVersionManager.newRequestMetrics)
101100

102101
private[this] val nextProcessorId: AtomicInteger = new AtomicInteger(0)
@@ -161,8 +160,8 @@ class SocketServer(
161160
* Therefore, we do not know that any particular request processor will be running by the end of
162161
* this function -- just that it might be running.
163162
*
164-
* @param authorizerFutures Future per [[EndPoint]] used to wait before starting the
165-
* processor corresponding to the [[EndPoint]]. Any endpoint
163+
* @param authorizerFutures Future per [[Endpoint]] used to wait before starting the
164+
* processor corresponding to the [[Endpoint]]. Any endpoint
166165
* that does not appear in this map will be started once all
167166
* authorizerFutures are complete.
168167
*
@@ -181,7 +180,7 @@ class SocketServer(
181180
// Because of ephemeral ports, we need to match acceptors to futures by looking at
182181
// the listener name, rather than the endpoint object.
183182
val authorizerFuture = authorizerFutures.find {
184-
case (endpoint, _) => acceptor.endPoint.listenerName.value().equals(endpoint.listenerName().get())
183+
case (endpoint, _) => acceptor.endPoint.listener.equals(endpoint.listener())
185184
} match {
186185
case None => allAuthorizerFuturesComplete
187186
case Some((_, future)) => future
@@ -210,23 +209,24 @@ class SocketServer(
210209
enableFuture
211210
}
212211

213-
private def createDataPlaneAcceptorAndProcessors(endpoint: EndPoint): Unit = synchronized {
212+
private def createDataPlaneAcceptorAndProcessors(endpoint: Endpoint): Unit = synchronized {
214213
if (stopped) {
215214
throw new RuntimeException("Can't create new data plane acceptor and processors: SocketServer is stopped.")
216215
}
217-
val parsedConfigs = config.valuesFromThisConfigWithPrefixOverride(endpoint.listenerName.configPrefix)
218-
connectionQuotas.addListener(config, endpoint.listenerName)
219-
val isPrivilegedListener = config.interBrokerListenerName == endpoint.listenerName
216+
val listenerName = ListenerName.normalised(endpoint.listener)
217+
val parsedConfigs = config.valuesFromThisConfigWithPrefixOverride(listenerName.configPrefix)
218+
connectionQuotas.addListener(config, listenerName)
219+
val isPrivilegedListener = config.interBrokerListenerName == listenerName
220220
val dataPlaneAcceptor = createDataPlaneAcceptor(endpoint, isPrivilegedListener, dataPlaneRequestChannel)
221221
config.addReconfigurable(dataPlaneAcceptor)
222222
dataPlaneAcceptor.configure(parsedConfigs)
223223
dataPlaneAcceptors.put(endpoint, dataPlaneAcceptor)
224-
info(s"Created data-plane acceptor and processors for endpoint : ${endpoint.listenerName}")
224+
info(s"Created data-plane acceptor and processors for endpoint : ${listenerName}")
225225
}
226226

227-
private def endpoints = config.listeners.map(l => l.listenerName -> l).toMap
227+
private def endpoints = config.listeners.map(l => ListenerName.normalised(l.listener) -> l).toMap
228228

229-
protected def createDataPlaneAcceptor(endPoint: EndPoint, isPrivilegedListener: Boolean, requestChannel: RequestChannel): DataPlaneAcceptor = {
229+
protected def createDataPlaneAcceptor(endPoint: Endpoint, isPrivilegedListener: Boolean, requestChannel: RequestChannel): DataPlaneAcceptor = {
230230
new DataPlaneAcceptor(this, endPoint, config, nodeId, connectionQuotas, time, isPrivilegedListener, requestChannel, metrics, credentialProvider, logContext, memoryPool, apiVersionManager)
231231
}
232232

@@ -277,7 +277,7 @@ class SocketServer(
277277
/**
278278
* This method is called to dynamically add listeners.
279279
*/
280-
def addListeners(listenersAdded: Seq[EndPoint]): Unit = synchronized {
280+
def addListeners(listenersAdded: Seq[Endpoint]): Unit = synchronized {
281281
if (stopped) {
282282
throw new RuntimeException("can't add new listeners: SocketServer is stopped.")
283283
}
@@ -297,10 +297,10 @@ class SocketServer(
297297
}
298298
}
299299

300-
def removeListeners(listenersRemoved: Seq[EndPoint]): Unit = synchronized {
300+
def removeListeners(listenersRemoved: Seq[Endpoint]): Unit = synchronized {
301301
info(s"Removing data-plane listeners for endpoints $listenersRemoved")
302302
listenersRemoved.foreach { endpoint =>
303-
connectionQuotas.removeListener(config, endpoint.listenerName)
303+
connectionQuotas.removeListener(config, ListenerName.normalised(endpoint.listener))
304304
dataPlaneAcceptors.asScala.remove(endpoint).foreach { acceptor =>
305305
acceptor.beginShutdown()
306306
acceptor.close()
@@ -345,7 +345,7 @@ class SocketServer(
345345
// For test usage
346346
def dataPlaneAcceptor(listenerName: String): Option[DataPlaneAcceptor] = {
347347
dataPlaneAcceptors.asScala.foreach { case (endPoint, acceptor) =>
348-
if (endPoint.listenerName.value() == listenerName)
348+
if (endPoint.listener == listenerName)
349349
return Some(acceptor)
350350
}
351351
None
@@ -374,7 +374,7 @@ object DataPlaneAcceptor {
374374
}
375375

376376
class DataPlaneAcceptor(socketServer: SocketServer,
377-
endPoint: EndPoint,
377+
endPoint: Endpoint,
378378
config: KafkaConfig,
379379
nodeId: Int,
380380
connectionQuotas: ConnectionQuotas,
@@ -404,7 +404,7 @@ class DataPlaneAcceptor(socketServer: SocketServer,
404404
* Returns the listener name associated with this reconfigurable. Listener-specific
405405
* configs corresponding to this listener name are provided for reconfiguration.
406406
*/
407-
override def listenerName(): ListenerName = endPoint.listenerName
407+
override def listenerName(): ListenerName = ListenerName.normalised(endPoint.listener)
408408

409409
/**
410410
* Returns the names of configs that may be reconfigured.
@@ -451,7 +451,7 @@ class DataPlaneAcceptor(socketServer: SocketServer,
451451
val newNumNetworkThreads = configs.get(SocketServerConfigs.NUM_NETWORK_THREADS_CONFIG).asInstanceOf[Int]
452452

453453
if (newNumNetworkThreads != processors.length) {
454-
info(s"Resizing network thread pool size for ${endPoint.listenerName} listener from ${processors.length} to $newNumNetworkThreads")
454+
info(s"Resizing network thread pool size for ${endPoint.listener} listener from ${processors.length} to $newNumNetworkThreads")
455455
if (newNumNetworkThreads > processors.length) {
456456
addProcessors(newNumNetworkThreads - processors.length)
457457
} else if (newNumNetworkThreads < processors.length) {
@@ -472,7 +472,7 @@ class DataPlaneAcceptor(socketServer: SocketServer,
472472
* Thread that accepts and configures new connections. There is one of these per endpoint.
473473
*/
474474
private[kafka] abstract class Acceptor(val socketServer: SocketServer,
475-
val endPoint: EndPoint,
475+
val endPoint: Endpoint,
476476
var config: KafkaConfig,
477477
nodeId: Int,
478478
val connectionQuotas: ConnectionQuotas,
@@ -515,15 +515,15 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
515515
private val backwardCompatibilityMetricGroup = new KafkaMetricsGroup("kafka.network", "Acceptor")
516516
private val blockedPercentMeterMetricName = backwardCompatibilityMetricGroup.metricName(
517517
"AcceptorBlockedPercent",
518-
Map(ListenerMetricTag -> endPoint.listenerName.value).asJava)
518+
Map(ListenerMetricTag -> endPoint.listener).asJava)
519519
private val blockedPercentMeter = metricsGroup.newMeter(blockedPercentMeterMetricName,"blocked time", TimeUnit.NANOSECONDS)
520520
private var currentProcessorIndex = 0
521521
private[network] val throttledSockets = new mutable.PriorityQueue[DelayedCloseSocket]()
522522
private val started = new AtomicBoolean()
523523
private[network] val startedFuture = new CompletableFuture[Void]()
524524

525525
val thread: KafkaThread = KafkaThread.nonDaemon(
526-
s"data-plane-kafka-socket-acceptor-${endPoint.listenerName}-${endPoint.securityProtocol}-${endPoint.port}",
526+
s"data-plane-kafka-socket-acceptor-${endPoint.listener}-${endPoint.securityProtocol}-${endPoint.port}",
527527
this)
528528

529529
def start(): Unit = synchronized {
@@ -535,19 +535,19 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
535535
serverChannel = openServerSocket(endPoint.host, endPoint.port, listenBacklogSize)
536536
debug(s"Opened endpoint ${endPoint.host}:${endPoint.port}")
537537
}
538-
debug(s"Starting processors for listener ${endPoint.listenerName}")
538+
debug(s"Starting processors for listener ${endPoint.listener}")
539539
processors.foreach(_.start())
540-
debug(s"Starting acceptor thread for listener ${endPoint.listenerName}")
540+
debug(s"Starting acceptor thread for listener ${endPoint.listener}")
541541
thread.start()
542542
startedFuture.complete(null)
543543
started.set(true)
544544
} catch {
545545
case e: ClosedChannelException =>
546-
debug(s"Refusing to start acceptor for ${endPoint.listenerName} since the acceptor has already been shut down.")
546+
debug(s"Refusing to start acceptor for ${endPoint.listener} since the acceptor has already been shut down.")
547547
startedFuture.completeExceptionally(e)
548548
case t: Throwable =>
549-
error(s"Unable to start acceptor for ${endPoint.listenerName}", t)
550-
startedFuture.completeExceptionally(new RuntimeException(s"Unable to start acceptor for ${endPoint.listenerName}", t))
549+
error(s"Unable to start acceptor for ${endPoint.listener}", t)
550+
startedFuture.completeExceptionally(new RuntimeException(s"Unable to start acceptor for ${endPoint.listener}", t))
551551
}
552552
}
553553

@@ -628,7 +628,7 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
628628
new InetSocketAddress(host, port)
629629
}
630630
val serverChannel = socketServer.socketFactory.openServerSocket(
631-
endPoint.listenerName.value(),
631+
endPoint.listener,
632632
socketAddress,
633633
listenBacklogSize,
634634
recvBufferSize)
@@ -682,14 +682,15 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
682682
private def accept(key: SelectionKey): Option[SocketChannel] = {
683683
val serverSocketChannel = key.channel().asInstanceOf[ServerSocketChannel]
684684
val socketChannel = serverSocketChannel.accept()
685+
val listenerName = ListenerName.normalised(endPoint.listener)
685686
try {
686-
connectionQuotas.inc(endPoint.listenerName, socketChannel.socket.getInetAddress, blockedPercentMeter)
687+
connectionQuotas.inc(listenerName, socketChannel.socket.getInetAddress, blockedPercentMeter)
687688
configureAcceptedSocketChannel(socketChannel)
688689
Some(socketChannel)
689690
} catch {
690691
case e: TooManyConnectionsException =>
691692
info(s"Rejected connection from ${e.ip}, address already has the configured maximum of ${e.count} connections.")
692-
connectionQuotas.closeChannel(this, endPoint.listenerName, socketChannel)
693+
connectionQuotas.closeChannel(this, listenerName, socketChannel)
693694
None
694695
case e: ConnectionThrottledException =>
695696
val ip = socketChannel.socket.getInetAddress
@@ -699,7 +700,7 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
699700
None
700701
case e: IOException =>
701702
error(s"Encountered an error while configuring the connection, closing it.", e)
702-
connectionQuotas.closeChannel(this, endPoint.listenerName, socketChannel)
703+
connectionQuotas.closeChannel(this, listenerName, socketChannel)
703704
None
704705
}
705706
}
@@ -741,7 +742,7 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
741742
def wakeup(): Unit = nioSelector.wakeup()
742743

743744
def addProcessors(toCreate: Int): Unit = synchronized {
744-
val listenerName = endPoint.listenerName
745+
val listenerName = ListenerName.normalised(endPoint.listener)
745746
val securityProtocol = endPoint.securityProtocol
746747
val listenerProcessors = new ArrayBuffer[Processor]()
747748

@@ -761,7 +762,7 @@ private[kafka] abstract class Acceptor(val socketServer: SocketServer,
761762
listenerName: ListenerName,
762763
securityProtocol: SecurityProtocol,
763764
connectionDisconnectListeners: Seq[ConnectionDisconnectListener]): Processor = {
764-
val name = s"data-plane-kafka-network-thread-$nodeId-${endPoint.listenerName}-${endPoint.securityProtocol}-$id"
765+
val name = s"data-plane-kafka-network-thread-$nodeId-${endPoint.listener}-${endPoint.securityProtocol}-$id"
765766
new Processor(id,
766767
time,
767768
config.socketRequestMaxBytes,

core/src/main/scala/kafka/server/BrokerServer.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ class BrokerServer(
274274
clientQuotaMetadataManager = new ClientQuotaMetadataManager(quotaManagers, socketServer.connectionQuotas)
275275

276276
val listenerInfo = ListenerInfo.create(Optional.of(config.interBrokerListenerName.value()),
277-
config.effectiveAdvertisedBrokerListeners.map(_.toPublic()).asJava).
277+
config.effectiveAdvertisedBrokerListeners.asJava).
278278
withWildcardHostnamesResolved().
279279
withEphemeralPortsCorrected(name => socketServer.boundPort(new ListenerName(name)))
280280

0 commit comments

Comments
 (0)