|
23 | 23 | import io.netty.channel.ChannelHandlerContext; |
24 | 24 | import io.netty.util.ReferenceCountUtil; |
25 | 25 | import io.prometheus.client.Counter; |
| 26 | +import java.io.IOException; |
26 | 27 | import java.net.InetSocketAddress; |
27 | 28 | import java.net.SocketAddress; |
28 | 29 | import java.net.URI; |
29 | 30 | import java.net.URISyntaxException; |
30 | 31 | import java.util.Optional; |
31 | 32 | import java.util.concurrent.CompletableFuture; |
32 | 33 | import java.util.concurrent.Semaphore; |
| 34 | +import java.util.concurrent.TimeoutException; |
| 35 | +import java.util.function.BiConsumer; |
33 | 36 | import java.util.function.BooleanSupplier; |
34 | 37 | import org.apache.commons.lang3.StringUtils; |
35 | 38 | import org.apache.pulsar.broker.topiclistlimit.TopicListMemoryLimiter; |
36 | 39 | import org.apache.pulsar.broker.topiclistlimit.TopicListSizeResultCache; |
37 | 40 | import org.apache.pulsar.client.api.PulsarClientException; |
38 | 41 | import org.apache.pulsar.client.impl.BinaryProtoLookupService; |
39 | 42 | import org.apache.pulsar.client.impl.ClientCnx; |
| 43 | +import org.apache.pulsar.client.impl.ConnectionPool; |
40 | 44 | import org.apache.pulsar.common.api.proto.BaseCommand; |
41 | 45 | import org.apache.pulsar.common.api.proto.CommandGetSchema; |
42 | 46 | import org.apache.pulsar.common.api.proto.CommandGetTopicsOfNamespace; |
@@ -120,7 +124,7 @@ public void handleLookup(CommandLookupTopic lookup) { |
120 | 124 | if (lookupRequestSemaphore.tryAcquire()) { |
121 | 125 | try { |
122 | 126 | LOOKUP_REQUESTS.inc(); |
123 | | - String serviceUrl = getBrokerServiceUrl(clientRequestId); |
| 127 | + String serviceUrl = getBrokerServiceUrl(lookupErrorResponse(clientRequestId)); |
124 | 128 | if (serviceUrl != null) { |
125 | 129 | performLookup(clientRequestId, lookup.getTopic(), serviceUrl, false, 10); |
126 | 130 | } |
@@ -147,16 +151,10 @@ private void performLookup(long clientRequestId, String topic, String brokerServ |
147 | 151 | return; |
148 | 152 | } |
149 | 153 |
|
150 | | - URI brokerURI; |
151 | | - try { |
152 | | - brokerURI = new URI(brokerServiceUrl); |
153 | | - } catch (URISyntaxException e) { |
154 | | - writeAndFlush( |
155 | | - Commands.newLookupErrorResponse(ServerError.MetadataError, e.getMessage(), clientRequestId)); |
| 154 | + InetSocketAddress addr = getAddr(brokerServiceUrl, lookupErrorResponse(clientRequestId)); |
| 155 | + if (addr == null) { |
156 | 156 | return; |
157 | 157 | } |
158 | | - |
159 | | - InetSocketAddress addr = InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort()); |
160 | 158 | if (log.isDebugEnabled()) { |
161 | 159 | log.debug("Getting connections to '{}' for Looking up topic '{}' with clientReq Id '{}'", addr, topic, |
162 | 160 | clientRequestId); |
@@ -239,13 +237,15 @@ public void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata part |
239 | 237 | private void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata partitionMetadata, |
240 | 238 | long clientRequestId) { |
241 | 239 | String topicName = TopicName.toFullTopicName(partitionMetadata.getTopic()); |
| 240 | + boolean metadataAutoCreationEnabled = partitionMetadata.isMetadataAutoCreationEnabled(); |
| 241 | + BiConsumer<ServerError, String> onError = (error, message) -> |
| 242 | + writeAndFlush(Commands.newPartitionMetadataResponse(error, message, clientRequestId)); |
242 | 243 |
|
243 | | - String serviceUrl = getBrokerServiceUrl(clientRequestId); |
| 244 | + String serviceUrl = getBrokerServiceUrl(onError); |
244 | 245 | if (serviceUrl == null) { |
245 | | - log.warn("No available broker for {} to lookup partition metadata", topicName); |
246 | 246 | return; |
247 | 247 | } |
248 | | - InetSocketAddress addr = getAddr(serviceUrl, clientRequestId); |
| 248 | + InetSocketAddress addr = getAddr(serviceUrl, onError); |
249 | 249 | if (addr == null) { |
250 | 250 | return; |
251 | 251 | } |
@@ -254,33 +254,59 @@ private void handlePartitionMetadataResponse(CommandPartitionedTopicMetadata par |
254 | 254 | log.debug("Getting connections to '{}' for Looking up topic '{}' with clientReq Id '{}'", addr, |
255 | 255 | topicName, clientRequestId); |
256 | 256 | } |
257 | | - proxyConnection.getConnectionPool().getConnection(addr).thenAccept(clientCnx -> { |
258 | | - // Connected to backend broker |
259 | | - long requestId = proxyConnection.newRequestId(); |
260 | | - ByteBuf command; |
261 | | - command = Commands.newPartitionMetadataRequest(topicName.toString(), requestId, |
262 | | - partitionMetadata.isMetadataAutoCreationEnabled()); |
263 | | - clientCnx.newLookup(command, requestId).whenComplete((r, t) -> { |
264 | | - if (t != null) { |
265 | | - log.warn("[{}] failed to get Partitioned metadata : {}", topicName, |
266 | | - t.getMessage(), t); |
267 | | - PulsarClientException pce = PulsarClientException.unwrap(t); |
268 | | - writeAndFlush(Commands.newLookupErrorResponse(clientCnx.revertClientExToErrorCode(pce), |
269 | | - t.getMessage(), clientRequestId)); |
270 | | - } else { |
271 | | - writeAndFlush( |
272 | | - Commands.newPartitionMetadataResponse(r.partitions, clientRequestId)); |
273 | | - } |
274 | | - proxyConnection.getConnectionPool().releaseConnection(clientCnx); |
275 | | - }); |
276 | | - }).exceptionally(ex -> { |
277 | | - // Failed to connect to backend broker |
278 | | - writeAndFlush(Commands.newPartitionMetadataResponse(getServerError(ex), |
279 | | - ex.getMessage(), clientRequestId)); |
280 | | - return null; |
| 257 | + // The frontend connection can clear its pool while the backend request is pending. |
| 258 | + ConnectionPool connectionPool = proxyConnection.getConnectionPool(); |
| 259 | + FutureUtil.supplySafely(() -> connectionPool.getConnection(addr)).whenComplete((clientCnx, connectionError) -> { |
| 260 | + if (connectionError != null) { |
| 261 | + writePartitionMetadataError(connectionError, clientRequestId, ServerError.ServiceNotReady); |
| 262 | + return; |
| 263 | + } |
| 264 | + FutureUtil.supplySafely(() -> { |
| 265 | + long requestId = proxyConnection.newRequestId(); |
| 266 | + ByteBuf command = Commands.newPartitionMetadataRequest(topicName, requestId, |
| 267 | + metadataAutoCreationEnabled); |
| 268 | + return clientCnx.newLookup(command, requestId); |
| 269 | + }).whenComplete((result, error) -> connectionPool.releaseConnection(clientCnx)) |
| 270 | + .whenComplete((result, error) -> { |
| 271 | + if (error != null) { |
| 272 | + log.warn("[{}] failed to get Partitioned metadata : {}", topicName, |
| 273 | + error.getMessage(), error); |
| 274 | + writePartitionMetadataError(error, clientRequestId, ServerError.UnknownError); |
| 275 | + } else { |
| 276 | + writeAndFlush(Commands.newPartitionMetadataResponse(result.partitions, clientRequestId)); |
| 277 | + } |
| 278 | + }); |
281 | 279 | }); |
282 | 280 | } |
283 | 281 |
|
| 282 | + private BiConsumer<ServerError, String> lookupErrorResponse(long clientRequestId) { |
| 283 | + return (error, message) -> writeAndFlush(Commands.newLookupErrorResponse(error, message, clientRequestId)); |
| 284 | + } |
| 285 | + |
| 286 | + private void writePartitionMetadataError(Throwable error, long clientRequestId, ServerError fallbackError) { |
| 287 | + Throwable cause = FutureUtil.unwrapCompletionException(error); |
| 288 | + if (cause == null) { |
| 289 | + cause = error; |
| 290 | + } |
| 291 | + ServerError serverError; |
| 292 | + if (cause instanceof PulsarClientException.TimeoutException |
| 293 | + || cause instanceof PulsarClientException.ConnectException |
| 294 | + || cause instanceof PulsarClientException.NotConnectedException |
| 295 | + || cause instanceof PulsarClientException.AlreadyClosedException |
| 296 | + || cause instanceof TimeoutException |
| 297 | + || (cause instanceof IOException && !(cause instanceof PulsarClientException))) { |
| 298 | + serverError = ServerError.ServiceNotReady; |
| 299 | + } else if (cause instanceof PulsarClientException clientException) { |
| 300 | + serverError = ClientCnx.revertClientExToErrorCode(clientException); |
| 301 | + if (serverError == ServerError.UnknownError) { |
| 302 | + serverError = fallbackError; |
| 303 | + } |
| 304 | + } else { |
| 305 | + serverError = fallbackError; |
| 306 | + } |
| 307 | + writeAndFlush(Commands.newPartitionMetadataResponse(serverError, cause.getMessage(), clientRequestId)); |
| 308 | + } |
| 309 | + |
284 | 310 | public void handleGetTopicsOfNamespace(CommandGetTopicsOfNamespace commandGetTopicsOfNamespace) { |
285 | 311 | GET_TOPICS_OF_NAMESPACE_REQUESTS.inc(); |
286 | 312 | if (log.isDebugEnabled()) { |
@@ -523,6 +549,11 @@ public void handleGetSchema(CommandGetSchema commandGetSchema) { |
523 | 549 | * Get default broker service url or discovery an available broker. |
524 | 550 | **/ |
525 | 551 | private String getBrokerServiceUrl(long clientRequestId) { |
| 552 | + return getBrokerServiceUrl((error, message) -> |
| 553 | + writeAndFlush(Commands.newError(clientRequestId, error, message))); |
| 554 | + } |
| 555 | + |
| 556 | + private String getBrokerServiceUrl(BiConsumer<ServerError, String> onError) { |
526 | 557 | if (StringUtils.isNotBlank(brokerServiceURL)) { |
527 | 558 | return brokerServiceURL; |
528 | 559 | } |
@@ -531,24 +562,38 @@ private String getBrokerServiceUrl(long clientRequestId) { |
531 | 562 | availableBroker = discoveryProvider.nextBroker(); |
532 | 563 | } catch (Exception e) { |
533 | 564 | log.warn("[{}] Failed to get next active broker {}", clientAddress, e.getMessage(), e); |
534 | | - writeAndFlush(Commands.newError( |
535 | | - clientRequestId, ServerError.ServiceNotReady, e.getMessage() |
536 | | - )); |
| 565 | + onError.accept(ServerError.ServiceNotReady, e.getMessage()); |
537 | 566 | return null; |
538 | 567 | } |
539 | | - return this.connectWithTLS ? availableBroker.getPulsarServiceUrlTls() : availableBroker.getPulsarServiceUrl(); |
| 568 | + String serviceUrl = availableBroker == null ? null |
| 569 | + : (connectWithTLS ? availableBroker.getPulsarServiceUrlTls() : availableBroker.getPulsarServiceUrl()); |
| 570 | + if (StringUtils.isBlank(serviceUrl)) { |
| 571 | + onError.accept(ServerError.ServiceNotReady, "No broker service URL available"); |
| 572 | + return null; |
| 573 | + } |
| 574 | + return serviceUrl; |
540 | 575 | } |
541 | 576 |
|
542 | 577 | private InetSocketAddress getAddr(String brokerServiceUrl, long clientRequestId) { |
543 | | - URI brokerURI; |
| 578 | + return getAddr(brokerServiceUrl, (error, message) -> |
| 579 | + writeAndFlush(Commands.newError(clientRequestId, error, message))); |
| 580 | + } |
| 581 | + |
| 582 | + private InetSocketAddress getAddr(String brokerServiceUrl, BiConsumer<ServerError, String> onError) { |
| 583 | + if (StringUtils.isBlank(brokerServiceUrl)) { |
| 584 | + onError.accept(ServerError.ServiceNotReady, "No broker service URL available"); |
| 585 | + return null; |
| 586 | + } |
544 | 587 | try { |
545 | | - brokerURI = new URI(brokerServiceUrl); |
546 | | - } catch (URISyntaxException e) { |
547 | | - writeAndFlush( |
548 | | - Commands.newError(clientRequestId, ServerError.MetadataError, e.getMessage())); |
| 588 | + URI brokerURI = new URI(brokerServiceUrl); |
| 589 | + if (StringUtils.isBlank(brokerURI.getHost()) || brokerURI.getPort() <= 0) { |
| 590 | + throw new IllegalArgumentException("Invalid broker service URL: " + brokerServiceUrl); |
| 591 | + } |
| 592 | + return InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort()); |
| 593 | + } catch (URISyntaxException | IllegalArgumentException e) { |
| 594 | + onError.accept(ServerError.MetadataError, e.getMessage()); |
549 | 595 | return null; |
550 | 596 | } |
551 | | - return InetSocketAddress.createUnresolved(brokerURI.getHost(), brokerURI.getPort()); |
552 | 597 | } |
553 | 598 |
|
554 | 599 | private ServerError getServerError(Throwable error) { |
|