GeezerVison is showing github.com — [fix][client] Ignore superseded subscribe and producer attempts (#27081) · apache/pulsar@c6752fa
File treeExpand file treeCollapse file tree Open diff view settings pulsar-broker/src/test/java/org/apache/pulsar/broker/service main/java/org/apache/pulsar/client/impl test/java/org/apache/pulsar/client/impl
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ClusterMigrationTest.java +52Lines changed: 52 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 52 | 52 | import org.apache.pulsar.client.api.PulsarClient; | 53 | 53 | import org.apache.pulsar.client.api.Reader; | 54 | 54 | import org.apache.pulsar.client.api.SubscriptionType; | | 55 | +import org.apache.pulsar.client.impl.ClientCnx; | | 56 | +import org.apache.pulsar.client.impl.ConsumerImpl; | | 57 | +import org.apache.pulsar.client.impl.ProducerImpl; | 55 | 58 | import org.apache.pulsar.common.policies.data.ClusterData; | 56 | 59 | import org.apache.pulsar.common.policies.data.ClusterPolicies.ClusterUrl; | 57 | 60 | import org.apache.pulsar.common.policies.data.TenantInfoImpl; | @@ -459,6 +462,55 @@ public void testClusterMigration() throws Exception { | 459 | 462 | log.info("Successfully consumed messages by migrated consumers"); | 460 | 463 | } | 461 | 464 |
| | 465 | + /** | | 466 | + * A consumer and a producer created on a migrated cluster are redirected to the new cluster without an answer to | | 467 | + * their subscribe and producer requests, which stay pending on the connection to the old cluster. When that | | 468 | + * connection closes and fails those requests, the consumer and the producer, already connected to the new | | 469 | + * cluster, must stay connected: a consumer that subscribes again drops the messages in its receiver queue. | | 470 | + */ | | 471 | + @Test | | 472 | + public void testRedirectedConsumerAndProducerIgnoreTheirFirstAttempt() throws Exception { | | 473 | + final String topicName = BrokerTestUtil | | 474 | + .newUniqueName("persistent://" + namespace + "/migrationTopic"); | | 475 | + | | 476 | + @Cleanup | | 477 | + PulsarClient client1 = PulsarClient.builder().serviceUrl(url1.toString()).statsInterval(0, TimeUnit.SECONDS) | | 478 | + .build(); | | 479 | + // Load the topic on broker-1, through the connection that all of client1's handlers share | | 480 | + ProducerImpl<byte[]> producer1 = (ProducerImpl<byte[]>) client1.newProducer().topic(topicName).create(); | | 481 | + ClientCnx cnx1 = producer1.getClientCnx(); | | 482 | + AbstractTopic topic1 = (AbstractTopic) pulsar1.getBrokerService().getTopic(topicName, false).getNow(null).get(); | | 483 | + | | 484 | + ClusterUrl migratedUrl = new ClusterUrl(pulsar2.getWebServiceAddress(), pulsar2.getWebServiceAddressTls(), | | 485 | + pulsar2.getBrokerServiceUrl(), null); | | 486 | + admin1.clusters().updateClusterMigration("r1", true, migratedUrl); | | 487 | + Awaitility.await().ignoreExceptions().untilAsserted(() -> { | | 488 | + topic1.checkClusterMigration().get(); | | 489 | + assertTrue(topic1.isMigrated()); | | 490 | + }); | | 491 | + | | 492 | + Consumer<byte[]> consumer = client1.newConsumer().topic(topicName).subscriptionName("s1").subscribe(); | | 493 | + Producer<byte[]> producer = client1.newProducer().topic(topicName).create(); | | 494 | + int n = 5; | | 495 | + for (int i = 0; i < n; i++) { | | 496 | + producer.send(("msg-" + i).getBytes()); | | 497 | + } | | 498 | + Awaitility.await().untilAsserted( | | 499 | + () -> assertEquals(((ConsumerImpl<byte[]>) consumer).numMessagesInQueue(), n)); | | 500 | + | | 501 | + // Close cnx1 from its event loop, so that the task submitted next runs after the disconnection is handled | | 502 | + cnx1.ctx().executor().submit(() -> cnx1.ctx().channel().close()).get(); | | 503 | + cnx1.ctx().executor().submit(() -> { }).get(); | | 504 | + | | 505 | + assertTrue(consumer.isConnected(), "The consumer reconnected for its first subscribe attempt"); | | 506 | + assertTrue(producer.isConnected(), "The producer reconnected for its first attempt"); | | 507 | + for (int i = 0; i < n; i++) { | | 508 | + Message<byte[]> msg = consumer.receive(5, TimeUnit.SECONDS); | | 509 | + assertNotNull(msg, "Message " + i + " was dropped from the receiver queue"); | | 510 | + assertEquals(msg.getData(), ("msg-" + i).getBytes()); | | 511 | + } | | 512 | + } | | 513 | + | 462 | 514 | @Test | 463 | 515 | public void testClusterMigrationWithReplicationBacklog() throws Exception { | 464 | 516 | log.info("--- Starting ReplicatorTest::testClusterMigrationWithReplicationBacklog ---"); | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConnectionHandler.java +23-3Lines changed: 23 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -232,16 +232,36 @@ protected void setClientCnx(ClientCnx clientCnx) { | 232 | 232 | } | 233 | 233 |
| 234 | 234 | /** | 235 | | - * Update the {@link ClientCnx} for the class, then increment and get the epoch value. Note that the epoch value is | 236 | | - * currently only used by the {@link ProducerImpl}. | | 235 | + * Update the {@link ClientCnx} for the class, then increment and get the epoch value. The epoch identifies the | | 236 | + * connection attempt, see {@link #isSupersededAttempt}. | 237 | 237 | * @param clientCnx - the new {@link ClientCnx} | 238 | | - * @return the epoch value to use for this pair of {@link ClientCnx} and {@link ProducerImpl} | | 238 | + * @return the epoch value to use for this pair of {@link ClientCnx} and handler | 239 | 239 | */ | 240 | 240 | protected long switchClientCnx(ClientCnx clientCnx) { | 241 | 241 | setClientCnx(clientCnx); | 242 | 242 | return EPOCH_UPDATER.incrementAndGet(this); | 243 | 243 | } | 244 | 244 |
| | 245 | + /** | | 246 | + * Whether the connection attempt that {@link #switchClientCnx} started on {@code cnx} with {@code epoch} has been | | 247 | + * superseded: the handler has since been disconnected from {@code cnx}, or has started another attempt. The | | 248 | + * response to a superseded attempt can arrive after the handler is connected again, so it must not change the | | 249 | + * handler. | | 250 | + */ | | 251 | + boolean isSupersededAttempt(ClientCnx cnx, long epoch) { | | 252 | + return cnx() != cnx || getEpoch() != epoch; | | 253 | + } | | 254 | + | | 255 | + /** | | 256 | + * Ends the connection attempt that {@link #switchClientCnx} started on {@code cnx} with {@code epoch}, if it is | | 257 | + * still the current one, and tells whether it was. The handler is then left without a connection, so a | | 258 | + * disconnection from {@code cnx} no longer reconnects it: only completing the failed attempt does. The caller | | 259 | + * must hold the lock under which it calls {@link #switchClientCnx}. | | 260 | + */ | | 261 | + boolean endAttempt(ClientCnx cnx, long epoch) { | | 262 | + return getEpoch() == epoch && CLIENT_CNX_UPDATER.compareAndSet(this, cnx, null); | | 263 | + } | | 264 | + | 245 | 265 | @VisibleForTesting | 246 | 266 | public boolean isValidStateForReconnection() { | 247 | 267 | State state = this.state.getState(); | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java +46-19Lines changed: 46 additions & 19 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -913,9 +913,11 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 913 | 913 | + client.getConfiguration().getOperationTimeoutMs()); | 914 | 914 |
| 915 | 915 | int currentSize; | | 916 | + long cnxEpoch; | 916 | 917 | synchronized (this) { | 917 | 918 | currentSize = incomingMessages.size(); | 918 | 919 | setClientCnx(cnx); | | 920 | + cnxEpoch = connectionHandler.getEpoch(); | 919 | 921 | clearReceiverQueue(true); | 920 | 922 | if (possibleSendToDeadLetterTopicMessages != null) { | 921 | 923 | possibleSendToDeadLetterTopicMessages.clear(); | @@ -965,6 +967,13 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 965 | 967 |
| 966 | 968 | cnx.sendRequestWithId(request, requestId).thenRun(() -> { | 967 | 969 | synchronized (ConsumerImpl.this) { | | 970 | + if (connectionHandler.isSupersededAttempt(cnx, cnxEpoch)) { | | 971 | + if (log.isDebugEnabled()) { | | 972 | + log.debug("[{}][{}] Ignoring the response to a superseded subscribe attempt on {}", | | 973 | + topic, subscription, cnx.channel()); | | 974 | + } | | 975 | + return; | | 976 | + } | 968 | 977 | if (changeToReadyState()) { | 969 | 978 | // Send the acks that waited for the subscription before any other command on the new | 970 | 979 | // connection, including the permits consumerIsReconnectedToBroker() sends for a zero-queue | @@ -1002,24 +1011,41 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 1002 | 1011 | } | 1003 | 1012 | future.complete(null); | 1004 | 1013 | }).exceptionally((e) -> { | 1005 | | - deregisterFromClientCnx(); | 1006 | | - if (getState() == State.Closing || getState() == State.Closed) { | 1007 | | - // Consumer was closed while reconnecting, close the connection to make sure the broker | 1008 | | - // drops the consumer on its side | 1009 | | - cnx.channel().close(); | 1010 | | - future.complete(null); | 1011 | | - return null; | 1012 | | - } | 1013 | | - log.warn("[{}][{}] Failed to subscribe to topic on {}", topic, | 1014 | | - subscription, cnx.channel().remoteAddress()); | 1015 | | - | 1016 | | - if (e.getCause() instanceof PulsarClientException.TimeoutException) { | 1017 | | - // Creating the consumer has timed out. We need to ensure the broker closes the consumer | 1018 | | - // in case it was indeed created, otherwise it might prevent new create consumer operation, | 1019 | | - // since we are not necessarily closing the connection. | 1020 | | - long closeRequestId = client.newRequestId(); | 1021 | | - ByteBuf cmd = Commands.newCloseConsumer(consumerId, closeRequestId, null, null); | 1022 | | - cnx.sendRequestWithId(cmd, closeRequestId); | | 1014 | + // A timeout fails the attempt on another thread than the connection's. Holding the lock under which | | 1015 | + // a newer attempt registers on a connection, end this attempt and clean it up before a newer attempt | | 1016 | + // can register. Once ended, a disconnection no longer reconnects the consumer: completing this | | 1017 | + // attempt's future below does. | | 1018 | + synchronized (ConsumerImpl.this) { | | 1019 | + if (!connectionHandler.endAttempt(cnx, cnxEpoch)) { | | 1020 | + // The consumer was disconnected from cnx, or subscribed again, while this attempt was | | 1021 | + // pending. Its failure must neither unregister the consumer from its current connection nor | | 1022 | + // reconnect it, so the attempt's future is left incomplete. | | 1023 | + if (log.isDebugEnabled()) { | | 1024 | + log.debug("[{}][{}] Ignoring the failure of a superseded subscribe attempt on {}: {}", | | 1025 | + topic, subscription, cnx.channel(), | | 1026 | + e.getCause() != null ? e.getCause().getMessage() : e.getMessage()); | | 1027 | + } | | 1028 | + return null; | | 1029 | + } | | 1030 | + deregisterFromClientCnx(); | | 1031 | + if (getState() == State.Closing || getState() == State.Closed) { | | 1032 | + // Consumer was closed while reconnecting, close the connection to make sure the broker | | 1033 | + // drops the consumer on its side | | 1034 | + cnx.channel().close(); | | 1035 | + future.complete(null); | | 1036 | + return null; | | 1037 | + } | | 1038 | + log.warn("[{}][{}] Failed to subscribe to topic on {}", topic, | | 1039 | + subscription, cnx.channel().remoteAddress()); | | 1040 | + | | 1041 | + if (e.getCause() instanceof PulsarClientException.TimeoutException) { | | 1042 | + // Creating the consumer has timed out. We need to ensure the broker closes the consumer | | 1043 | + // in case it was indeed created, otherwise it might prevent new create consumer operation, | | 1044 | + // since we are not necessarily closing the connection. | | 1045 | + long closeRequestId = client.newRequestId(); | | 1046 | + ByteBuf cmd = Commands.newCloseConsumer(consumerId, closeRequestId, null, null); | | 1047 | + cnx.sendRequestWithId(cmd, closeRequestId); | | 1048 | + } | 1023 | 1049 | } | 1024 | 1050 |
| 1025 | 1051 | final boolean retriable = PulsarClientException.isRetriableError(e.getCause()); | @@ -3308,7 +3334,8 @@ public ClientCnx getClientCnx() { | 3308 | 3334 |
| 3309 | 3335 | void setClientCnx(ClientCnx clientCnx) { | 3310 | 3336 | if (clientCnx != null) { | 3311 | | - this.connectionHandler.setClientCnx(clientCnx); | | 3337 | + // Starts a new connection attempt, see ConnectionHandler#isSupersededAttempt | | 3338 | + this.connectionHandler.switchClientCnx(clientCnx); | 3312 | 3339 | clientCnx.registerConsumer(consumerId, this); | 3313 | 3340 | if (conf.isAckReceiptEnabled() | 3314 | 3341 | && !Commands.peerSupportsAckReceipt(clientCnx.getRemoteEndpointProtocolVersion())) { | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java +43-20Lines changed: 43 additions & 20 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -2214,6 +2214,13 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 2214 | 2214 | conf.getAccessMode(), topicEpoch, client.getConfiguration().isEnableTransaction(), | 2215 | 2215 | conf.getInitialSubscriptionName(), schema instanceof AutoProduceBytesSchema), | 2216 | 2216 | requestId).thenAccept(response -> { | | 2217 | + if (connectionHandler.isSupersededAttempt(cnx, epoch)) { | | 2218 | + if (log.isDebugEnabled()) { | | 2219 | + log.debug("[{}] [{}] Ignoring the response to a superseded create producer attempt on {}", topic, | | 2220 | + producerName, cnx.channel()); | | 2221 | + } | | 2222 | + return; | | 2223 | + } | 2217 | 2224 | String producerName = response.getProducerName(); | 2218 | 2225 | long lastSequenceId = response.getLastSequenceId(); | 2219 | 2226 | schemaVersion = Optional.ofNullable(response.getSchemaVersion()); | @@ -2261,14 +2268,39 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 2261 | 2268 | future.complete(null); | 2262 | 2269 | }).exceptionally((e) -> { | 2263 | 2270 | Throwable cause = e.getCause(); | 2264 | | - cnx.removeProducer(producerId); | 2265 | | - State state = getState(); | 2266 | | - if (state == State.Closing || state == State.Closed) { | 2267 | | - // Producer was closed while reconnecting, close the connection to make sure the broker | 2268 | | - // drops the producer on its side | 2269 | | - cnx.channel().close(); | 2270 | | - future.complete(null); | 2271 | | - return null; | | 2271 | + // A timeout fails the attempt on another thread than the connection's. Holding the lock under which a | | 2272 | + // newer attempt registers on a connection, end this attempt and clean it up before a newer attempt can | | 2273 | + // register. Once ended, a disconnection no longer reconnects the producer: completing this attempt's | | 2274 | + // future below does. | | 2275 | + synchronized (ProducerImpl.this) { | | 2276 | + if (!connectionHandler.endAttempt(cnx, epoch)) { | | 2277 | + // The producer was disconnected from cnx, or connected again, while this attempt was pending. | | 2278 | + // Its failure must neither unregister the producer from its current connection nor reconnect it, | | 2279 | + // so the attempt's future is left incomplete. | | 2280 | + if (log.isDebugEnabled()) { | | 2281 | + log.debug("[{}] [{}] Ignoring the failure of a superseded create producer attempt on {}: {}", | | 2282 | + topic, producerName, cnx.channel(), cause != null ? cause.getMessage() : null); | | 2283 | + } | | 2284 | + return null; | | 2285 | + } | | 2286 | + cnx.removeProducer(producerId); | | 2287 | + State state = getState(); | | 2288 | + if (state == State.Closing || state == State.Closed) { | | 2289 | + // Producer was closed while reconnecting, close the connection to make sure the broker | | 2290 | + // drops the producer on its side | | 2291 | + cnx.channel().close(); | | 2292 | + future.complete(null); | | 2293 | + return null; | | 2294 | + } | | 2295 | + | | 2296 | + if (cause instanceof TimeoutException) { | | 2297 | + // Creating the producer has timed out. We need to ensure the broker closes the producer | | 2298 | + // in case it was indeed created, otherwise it might prevent new create producer operation, | | 2299 | + // since we are not necessarily closing the connection. | | 2300 | + long closeRequestId = client.newRequestId(); | | 2301 | + ByteBuf cmd = Commands.newCloseProducer(producerId, closeRequestId); | | 2302 | + cnx.sendRequestWithId(cmd, closeRequestId); | | 2303 | + } | 2272 | 2304 | } | 2273 | 2305 |
| 2274 | 2306 | if (cause instanceof PulsarClientException.IncompatibleSchemaException | @@ -2281,15 +2313,6 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 2281 | 2313 | return null; | 2282 | 2314 | } | 2283 | 2315 |
| 2284 | | - if (cause instanceof TimeoutException) { | 2285 | | - // Creating the producer has timed out. We need to ensure the broker closes the producer | 2286 | | - // in case it was indeed created, otherwise it might prevent new create producer operation, | 2287 | | - // since we are not necessarily closing the connection. | 2288 | | - long closeRequestId = client.newRequestId(); | 2289 | | - ByteBuf cmd = Commands.newCloseProducer(producerId, closeRequestId); | 2290 | | - cnx.sendRequestWithId(cmd, closeRequestId); | 2291 | | - } | 2292 | | - | 2293 | 2316 | // Close the producer since topic does not exist. | 2294 | 2317 | if (isUnrecoverableError(cause)) { | 2295 | 2318 | closeWhenReceivedUnrecoverableError(cause, cnx); | @@ -2310,7 +2333,7 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 2310 | 2333 | PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException( | 2311 | 2334 | format("The backlog quota of the topic %s that the producer %s produces to is exceeded", | 2312 | 2335 | topic, producerName)); | 2313 | | - failPendingMessages(cnx(), bqe); | | 2336 | + failPendingMessages(cnx, bqe); | 2314 | 2337 | } | 2315 | 2338 | } else if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededError) { | 2316 | 2339 | log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.", | @@ -2324,15 +2347,15 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) { | 2324 | 2347 | if (cause instanceof PulsarClientException.TopicTerminatedException) { | 2325 | 2348 | setState(State.Terminated); | 2326 | 2349 | synchronized (this) { | 2327 | | - failPendingMessages(cnx(), (PulsarClientException) cause); | | 2350 | + failPendingMessages(cnx, (PulsarClientException) cause); | 2328 | 2351 | } | 2329 | 2352 | producerCreatedFuture.completeExceptionally(cause); | 2330 | 2353 | closeProducerTasks(); | 2331 | 2354 | client.cleanupProducer(this); | 2332 | 2355 | } else if (cause instanceof PulsarClientException.ProducerFencedException) { | 2333 | 2356 | setState(State.ProducerFenced); | 2334 | 2357 | synchronized (this) { | 2335 | | - failPendingMessages(cnx(), (PulsarClientException) cause); | | 2358 | + failPendingMessages(cnx, (PulsarClientException) cause); | 2336 | 2359 | } | 2337 | 2360 | producerCreatedFuture.completeExceptionally(cause); | 2338 | 2361 | closeProducerTasks(); | |
|