GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][client] Ignore superseded subscribe and producer attempts (#27081) · apache/pulsar@c6752fa

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • pulsar-broker/src/test/java/org/apache/pulsar/broker/service
    • ClusterMigrationTest.java
  • pulsar-client/src
    • main/java/org/apache/pulsar/client/impl
      • ConnectionHandler.java
      • ConsumerImpl.java
      • ProducerImpl.java
    • test/java/org/apache/pulsar/client/impl
      • ConsumerImplTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎pulsar-broker/src/test/java/org/apache/pulsar/broker/service/ClusterMigrationTest.java‎

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 numberDiff line numberDiff line change
@@ -52,6 +52,9 @@
5252
import org.apache.pulsar.client.api.PulsarClient;
5353
import org.apache.pulsar.client.api.Reader;
5454
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;
5558
import org.apache.pulsar.common.policies.data.ClusterData;
5659
import org.apache.pulsar.common.policies.data.ClusterPolicies.ClusterUrl;
5760
import org.apache.pulsar.common.policies.data.TenantInfoImpl;
@@ -459,6 +462,55 @@ public void testClusterMigration() throws Exception {
459462
log.info("Successfully consumed messages by migrated consumers");
460463
}
461464

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+
462514
@Test
463515
public void testClusterMigrationWithReplicationBacklog() throws Exception {
464516
log.info("--- Starting ReplicatorTest::testClusterMigrationWithReplicationBacklog ---");
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConnectionHandler.java‎

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 numberDiff line numberDiff line change
@@ -232,16 +232,36 @@ protected void setClientCnx(ClientCnx clientCnx) {
232232
}
233233

234234
/**
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}.
237237
* @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
239239
*/
240240
protected long switchClientCnx(ClientCnx clientCnx) {
241241
setClientCnx(clientCnx);
242242
return EPOCH_UPDATER.incrementAndGet(this);
243243
}
244244

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+
245265
@VisibleForTesting
246266
public boolean isValidStateForReconnection() {
247267
State state = this.state.getState();
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/ConsumerImpl.java‎

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 numberDiff line numberDiff line change
@@ -913,9 +913,11 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
913913
+ client.getConfiguration().getOperationTimeoutMs());
914914

915915
int currentSize;
916+
long cnxEpoch;
916917
synchronized (this) {
917918
currentSize = incomingMessages.size();
918919
setClientCnx(cnx);
920+
cnxEpoch = connectionHandler.getEpoch();
919921
clearReceiverQueue(true);
920922
if (possibleSendToDeadLetterTopicMessages != null) {
921923
possibleSendToDeadLetterTopicMessages.clear();
@@ -965,6 +967,13 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
965967

966968
cnx.sendRequestWithId(request, requestId).thenRun(() -> {
967969
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+
}
968977
if (changeToReadyState()) {
969978
// Send the acks that waited for the subscription before any other command on the new
970979
// connection, including the permits consumerIsReconnectedToBroker() sends for a zero-queue
@@ -1002,24 +1011,41 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
10021011
}
10031012
future.complete(null);
10041013
}).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+
}
10231049
}
10241050

10251051
final boolean retriable = PulsarClientException.isRetriableError(e.getCause());
@@ -3308,7 +3334,8 @@ public ClientCnx getClientCnx() {
33083334

33093335
void setClientCnx(ClientCnx clientCnx) {
33103336
if (clientCnx != null) {
3311-
this.connectionHandler.setClientCnx(clientCnx);
3337+
// Starts a new connection attempt, see ConnectionHandler#isSupersededAttempt
3338+
this.connectionHandler.switchClientCnx(clientCnx);
33123339
clientCnx.registerConsumer(consumerId, this);
33133340
if (conf.isAckReceiptEnabled()
33143341
&& !Commands.peerSupportsAckReceipt(clientCnx.getRemoteEndpointProtocolVersion())) {
Collapse file

‎pulsar-client/src/main/java/org/apache/pulsar/client/impl/ProducerImpl.java‎

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 numberDiff line numberDiff line change
@@ -2214,6 +2214,13 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
22142214
conf.getAccessMode(), topicEpoch, client.getConfiguration().isEnableTransaction(),
22152215
conf.getInitialSubscriptionName(), schema instanceof AutoProduceBytesSchema),
22162216
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+
}
22172224
String producerName = response.getProducerName();
22182225
long lastSequenceId = response.getLastSequenceId();
22192226
schemaVersion = Optional.ofNullable(response.getSchemaVersion());
@@ -2261,14 +2268,39 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
22612268
future.complete(null);
22622269
}).exceptionally((e) -> {
22632270
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+
}
22722304
}
22732305

22742306
if (cause instanceof PulsarClientException.IncompatibleSchemaException
@@ -2281,15 +2313,6 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
22812313
return null;
22822314
}
22832315

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-
22932316
// Close the producer since topic does not exist.
22942317
if (isUnrecoverableError(cause)) {
22952318
closeWhenReceivedUnrecoverableError(cause, cnx);
@@ -2310,7 +2333,7 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
23102333
PulsarClientException bqe = new PulsarClientException.ProducerBlockedQuotaExceededException(
23112334
format("The backlog quota of the topic %s that the producer %s produces to is exceeded",
23122335
topic, producerName));
2313-
failPendingMessages(cnx(), bqe);
2336+
failPendingMessages(cnx, bqe);
23142337
}
23152338
} else if (cause instanceof PulsarClientException.ProducerBlockedQuotaExceededError) {
23162339
log.warn("[{}] [{}] Producer is blocked on creation because backlog exceeded on topic.",
@@ -2324,15 +2347,15 @@ public CompletableFuture<Void> connectionOpened(final ClientCnx cnx) {
23242347
if (cause instanceof PulsarClientException.TopicTerminatedException) {
23252348
setState(State.Terminated);
23262349
synchronized (this) {
2327-
failPendingMessages(cnx(), (PulsarClientException) cause);
2350+
failPendingMessages(cnx, (PulsarClientException) cause);
23282351
}
23292352
producerCreatedFuture.completeExceptionally(cause);
23302353
closeProducerTasks();
23312354
client.cleanupProducer(this);
23322355
} else if (cause instanceof PulsarClientException.ProducerFencedException) {
23332356
setState(State.ProducerFenced);
23342357
synchronized (this) {
2335-
failPendingMessages(cnx(), (PulsarClientException) cause);
2358+
failPendingMessages(cnx, (PulsarClientException) cause);
23362359
}
23372360
producerCreatedFuture.completeExceptionally(cause);
23382361
closeProducerTasks();

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.