GeezerVison is showing github.com — [fix][txn] Fix reuse of recycled pooled objects in transaction code p… · apache/pulsar@ba3d039
File treeExpand file treeCollapse file tree Open diff view settings main/java/org/apache/pulsar/broker/service/persistent test/java/org/apache/pulsar/broker/service
main/java/org/apache/pulsar/client/impl test/java/org/apache/pulsar/client/impl
pulsar-transaction/coordinator/src main/java/org/apache/pulsar/transaction/coordinator/impl test/java/org/apache/pulsar/transaction/coordinator/impl
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: pulsar-broker/src/main/java/org/apache/pulsar/broker/service/persistent/PersistentTopic.java +27-11Lines changed: 27 additions & 11 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5177,25 +5177,41 @@ public void publishTxnMessage(TxnID txnID, ByteBuf headersAndPayload, PublishCon | 5177 | 5177 | messageDeduplication.isDuplicate(publishContext, headersAndPayload); | 5178 | 5178 | switch (status) { | 5179 | 5179 | case NotDup: | | 5180 | + // Handle success and failure in a single stage so that an exception thrown while handling the | | 5181 | + // success can't complete the (recycled) publish context a second time as a failure. | 5180 | 5182 | transactionBuffer.appendBufferToTxn(txnID, publishContext.getSequenceId(), headersAndPayload) | 5181 | | - .thenAccept(position -> { | | 5183 | + .handle((position, throwable) -> { | | 5184 | + if (throwable != null) { | | 5185 | + throwable = FutureUtil.unwrapCompletionException(throwable); | | 5186 | + if (throwable instanceof NotAllowedException) { | | 5187 | + publishContext.completed((NotAllowedException) throwable, -1, -1); | | 5188 | + decrementPendingWriteOpsAndCheck(); | | 5189 | + } else { | | 5190 | + addFailed(ManagedLedgerException.getManagedLedgerException(throwable), | | 5191 | + publishContext); | | 5192 | + } | | 5193 | + return null; | | 5194 | + } | 5182 | 5195 | // Message has been successfully persisted | 5183 | | - messageDeduplication.recordMessagePersisted(publishContext, | 5184 | | - position); | 5185 | | - publishContext.setProperty("txn_id", txnID.toString()); | | 5196 | + try { | | 5197 | + messageDeduplication.recordMessagePersisted(publishContext, | | 5198 | + position); | | 5199 | + publishContext.setProperty("txn_id", txnID.toString()); | | 5200 | + } catch (Throwable t) { | | 5201 | + // The publish context hasn't been completed yet, so it can still be failed once | | 5202 | + addFailed(ManagedLedgerException.getManagedLedgerException(t), publishContext); | | 5203 | + return null; | | 5204 | + } | 5186 | 5205 | publishContext.completed(null, position.getLedgerId(), | 5187 | 5206 | position.getEntryId()); | 5188 | 5207 |
| 5189 | 5208 | decrementPendingWriteOpsAndCheck(); | | 5209 | + return null; | 5190 | 5210 | }) | 5191 | 5211 | .exceptionally(throwable -> { | 5192 | | - throwable = FutureUtil.unwrapCompletionException(throwable); | 5193 | | - if (throwable instanceof NotAllowedException) { | 5194 | | - publishContext.completed((NotAllowedException) throwable, -1, -1); | 5195 | | - decrementPendingWriteOpsAndCheck(); | 5196 | | - } else { | 5197 | | - addFailed(ManagedLedgerException.getManagedLedgerException(throwable), publishContext); | 5198 | | - } | | 5212 | + // Only reached when the handler above throws; the publish context is not completed again. | | 5213 | + log.warn("[{}] Failed to handle the result of appending a transactional message," | | 5214 | + + " txnId: {}", topic, txnID, throwable); | 5199 | 5215 | return null; | 5200 | 5216 | }); | 5201 | 5217 | break; | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-broker/src/test/java/org/apache/pulsar/broker/service/PersistentTopicTest.java +29Lines changed: 29 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 31 | 31 | import static org.mockito.Mockito.doAnswer; | 32 | 32 | import static org.mockito.Mockito.doNothing; | 33 | 33 | import static org.mockito.Mockito.doReturn; | | 34 | +import static org.mockito.Mockito.doThrow; | 34 | 35 | import static org.mockito.Mockito.eq; | 35 | 36 | import static org.mockito.Mockito.matches; | 36 | 37 | import static org.mockito.Mockito.mock; | | 74 | 75 | import java.util.concurrent.ExecutorService; | 75 | 76 | import java.util.concurrent.Executors; | 76 | 77 | import java.util.concurrent.Future; | | 78 | +import java.util.concurrent.RejectedExecutionException; | 77 | 79 | import java.util.concurrent.ScheduledFuture; | 78 | 80 | import java.util.concurrent.TimeUnit; | 79 | 81 | import java.util.concurrent.TimeoutException; | | 112 | 114 | import org.apache.pulsar.broker.service.persistent.PersistentTopic; | 113 | 115 | import org.apache.pulsar.broker.service.persistent.PulsarCompactorSubscription; | 114 | 116 | import org.apache.pulsar.broker.testcontext.PulsarTestContext; | | 117 | +import org.apache.pulsar.broker.transaction.buffer.TransactionBuffer; | | 118 | +import org.apache.pulsar.broker.transaction.buffer.TransactionBufferProvider; | 115 | 119 | import org.apache.pulsar.client.admin.PulsarAdmin; | 116 | 120 | import org.apache.pulsar.client.admin.Topics; | 117 | 121 | import org.apache.pulsar.client.api.MessageId; | @@ -359,6 +363,31 @@ public void setMetadataFromEntryData(ByteBuf entryData) { | 359 | 363 | "Topics without a replicated-subscription controller should not maintain the snapshot timestamp"); | 360 | 364 | } | 361 | 365 |
| | 366 | + @Test | | 367 | + public void testPublishTxnMessageCompletesPublishContextOnce() throws Exception { | | 368 | + pulsarTestContext.getConfig().setTransactionCoordinatorEnabled(true); | | 369 | + TransactionBuffer transactionBuffer = mock(TransactionBuffer.class); | | 370 | + doReturn(CompletableFuture.completedFuture(PositionFactory.create(1, 2))) | | 371 | + .when(transactionBuffer).appendBufferToTxn(any(), anyLong(), any()); | | 372 | + TransactionBufferProvider transactionBufferProvider = mock(TransactionBufferProvider.class); | | 373 | + doReturn(transactionBuffer).when(transactionBufferProvider).newTransactionBuffer(any()); | | 374 | + doReturn(transactionBufferProvider).when(pulsarTestContext.getPulsarService()).getTransactionBufferProvider(); | | 375 | + PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService); | | 376 | + assertThat(topic.getTransactionBuffer()).isSameAs(transactionBuffer); | | 377 | + | | 378 | + // Completing the publish context fails after it may have already handed itself over, e.g. when the | | 379 | + // connection's executor rejects the task. | | 380 | + Topic.PublishContext publishContext = mock(Topic.PublishContext.class); | | 381 | + doThrow(new RejectedExecutionException("rejected")) | | 382 | + .when(publishContext).completed(any(), anyLong(), anyLong()); | | 383 | + | | 384 | + topic.publishTxnMessage(new TxnID(1, 2), Unpooled.wrappedBuffer("content".getBytes()), publishContext); | | 385 | + | | 386 | + // The failure must not complete the publish context a second time. | | 387 | + verify(publishContext, times(1)).completed(any(), anyLong(), anyLong()); | | 388 | + verify(publishContext).completed(null, 1, 2); | | 389 | + } | | 390 | + | 362 | 391 | @Test | 363 | 392 | public void testDispatcherMultiConsumerReadFailed() { | 364 | 393 | PersistentTopic topic = | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-client/src/main/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandler.java +19-1Lines changed: 19 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 28 | 28 | import java.io.Closeable; | 29 | 29 | import java.io.IOException; | 30 | 30 | import java.time.Duration; | | 31 | +import java.util.ArrayList; | 31 | 32 | import java.util.List; | 32 | 33 | import java.util.concurrent.CompletableFuture; | 33 | 34 | import java.util.concurrent.ConcurrentLinkedQueue; | @@ -170,7 +171,7 @@ public CompletableFuture<Void> connectionOpened(ClientCnx cnx) { | 170 | 171 | LOG.info("Transaction coordinator client connect success! tcId : {}", transactionCoordinatorId); | 171 | 172 | if (registerToConnection(cnx)) { | 172 | 173 | this.connectionHandler.resetBackoff(); | 173 | | - pendingRequests.forEach((requestID, opBase) -> checkStateAndSendRequest(opBase)); | | 174 | + resendPendingRequests(); | 174 | 175 | } | 175 | 176 | future.complete(null); | 176 | 177 | }); | @@ -215,6 +216,18 @@ private boolean registerToConnection(ClientCnx cnx) { | 215 | 216 | } | 216 | 217 | } | 217 | 218 |
| | 219 | + private void resendPendingRequests() { | | 220 | + // this method is executed in internalPinnedExecutor. | | 221 | + List<Long> failedRequestIds = new ArrayList<>(); | | 222 | + pendingRequests.forEach((requestId, op) -> { | | 223 | + if (!checkStateAndSendRequest(op)) { | | 224 | + // The op has been completed and recycled, it must not stay in pendingRequests. | | 225 | + failedRequestIds.add(requestId); | | 226 | + } | | 227 | + }); | | 228 | + failedRequestIds.forEach(pendingRequests::remove); | | 229 | + } | | 230 | + | 218 | 231 | private void failPendingRequest() { | 219 | 232 | // this method is executed in internalPinnedExecutor. | 220 | 233 | pendingRequests.forEach((k, op) -> { | @@ -817,6 +830,11 @@ public void close() throws IOException { | 817 | 830 | this.setState(State.Closed); | 818 | 831 | } | 819 | 832 |
| | 833 | + @VisibleForTesting | | 834 | + int getPendingRequestsCount() { | | 835 | + return (int) pendingRequests.size(); | | 836 | + } | | 837 | + | 820 | 838 | @VisibleForTesting | 821 | 839 | public State getConnectHandleState() { | 822 | 840 | return getState(); | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-client/src/test/java/org/apache/pulsar/client/impl/TransactionMetaStoreHandlerTest.java +41Lines changed: 41 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 18 | 18 | */ | 19 | 19 | package org.apache.pulsar.client.impl; | 20 | 20 |
| | 21 | +import static org.assertj.core.api.Assertions.assertThat; | 21 | 22 | import static org.mockito.ArgumentMatchers.any; | 22 | 23 | import static org.mockito.ArgumentMatchers.anyLong; | | 24 | +import static org.mockito.Mockito.doAnswer; | 23 | 25 | import static org.mockito.Mockito.mock; | 24 | 26 | import static org.mockito.Mockito.times; | 25 | 27 | import static org.mockito.Mockito.verify; | | 29 | 31 | import io.netty.channel.Channel; | 30 | 32 | import java.time.Duration; | 31 | 33 | import java.util.concurrent.CompletableFuture; | | 34 | +import java.util.concurrent.ExecutionException; | | 35 | +import java.util.concurrent.TimeUnit; | | 36 | +import lombok.Cleanup; | 32 | 37 | import org.apache.pulsar.client.api.PulsarClient; | | 38 | +import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException; | | 39 | +import org.apache.pulsar.client.api.transaction.TxnID; | 33 | 40 | import org.awaitility.Awaitility; | 34 | 41 | import org.testng.annotations.Test; | 35 | 42 |
| @@ -62,4 +69,38 @@ public void testStateChangeFailure() throws Exception { | 62 | 69 |
| 63 | 70 | client.close(); | 64 | 71 | } | | 72 | + | | 73 | + @Test | | 74 | + public void testFailedResendOnReconnectRemovesPendingRequest() throws Exception { | | 75 | + @Cleanup | | 76 | + final PulsarClientImpl client = (PulsarClientImpl) PulsarClient.builder() | | 77 | + .serviceUrl("pulsar://localhost:6650").build(); | | 78 | + final CompletableFuture<Void> connectFuture = new CompletableFuture<>(); | | 79 | + final TransactionMetaStoreHandler handler = new TransactionMetaStoreHandler( | | 80 | + 0L, client, "topic", connectFuture); | | 81 | + | | 82 | + // Not connected yet: the request stays queued until the connection is opened. | | 83 | + handler.setState(HandlerState.State.Connecting); | | 84 | + final CompletableFuture<TxnID> txnFuture = handler.newTransactionAsync(1, TimeUnit.MINUTES); | | 85 | + Awaitility.await().untilAsserted(() -> assertEquals(handler.getPendingRequestsCount(), 1)); | | 86 | + | | 87 | + final ClientCnx cnx = mock(ClientCnx.class); | | 88 | + when(cnx.getRemoteEndpointProtocolVersion()).thenReturn(19); | | 89 | + when(cnx.sendRequestWithId(any(), anyLong())).thenReturn(CompletableFuture.completedFuture(null)); | | 90 | + when(cnx.channel()).thenReturn(mock(Channel.class)); | | 91 | + // The handler is closed concurrently after it switched to Ready, but before it resends the pending | | 92 | + // requests, so resending them fails. | | 93 | + doAnswer(invocation -> { | | 94 | + handler.close(); | | 95 | + return null; | | 96 | + }).when(cnx).registerTransactionMetaStoreHandler(anyLong(), any()); | | 97 | + | | 98 | + handler.connectionOpened(cnx).get(10, TimeUnit.SECONDS); | | 99 | + | | 100 | + assertThat(txnFuture).failsWithin(Duration.ofSeconds(10)) | | 101 | + .withThrowableOfType(ExecutionException.class) | | 102 | + .withCauseInstanceOf(TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException.class); | | 103 | + // The failed request has been completed and its op recycled, so it must not stay pending. | | 104 | + assertEquals(handler.getPendingRequestsCount(), 0); | | 105 | + } | 65 | 106 | } |
Collapse file Copy file name to clipboardExpand all lines: pulsar-transaction/coordinator/src/main/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriter.java +12-1Lines changed: 12 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 19 | 19 | package org.apache.pulsar.transaction.coordinator.impl; | 20 | 20 |
| 21 | 21 | import static org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerInterceptException; | | 22 | +import com.google.common.annotations.VisibleForTesting; | 22 | 23 | import io.netty.buffer.ByteBuf; | 23 | 24 | import io.netty.buffer.Unpooled; | 24 | 25 | import io.netty.util.Recycler; | @@ -271,9 +272,15 @@ private void internalAsyncAddData(T data, AddDataCallback callback, Object ctx){ | 271 | 272 | trigFlushIfReachMaxRecordsOrMaxSize(); | 272 | 273 | } | 273 | 274 |
| 274 | | - private void trigFlushByTimingTask(){ | | 275 | + @VisibleForTesting | | 276 | + void trigFlushByTimingTask(){ | 275 | 277 | CompletableFuture | 276 | 278 | .runAsync(() -> { | | 279 | + // A timing flush that was queued before "close()" may run after the close task has recycled the | | 280 | + // flush context, which may already be reused by another writer that shares this executor. | | 281 | + if (state == State.CLOSING || state == State.CLOSED) { | | 282 | + return; | | 283 | + } | 277 | 284 | if (flushContext.asyncAddArgsList.isEmpty()) { | 278 | 285 | return; | 279 | 286 | } | @@ -387,6 +394,10 @@ public CompletableFuture<Void> close() { | 387 | 394 | new ManagedLedgerException.ManagedLedgerFencedException( | 388 | 395 | new Exception("Transaction log buffered write has closed") | 389 | 396 | )); | | 397 | + // The recycled flush context may be reused by another writer, don't keep a reference to it. | | 398 | + flushContext = null; | | 399 | + dataArray.clear(); | | 400 | + bytesSize = 0; | 390 | 401 | // Cancel the timing task. | 391 | 402 | if (!timeout.isCancelled()) { | 392 | 403 | this.timeout.cancel(); | |
Collapse file Copy file name to clipboardExpand all lines: pulsar-transaction/coordinator/src/test/java/org/apache/pulsar/transaction/coordinator/impl/TxnLogBufferedWriterTest.java +63Lines changed: 63 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 40 | 40 | import java.util.concurrent.ConcurrentHashMap; | 41 | 41 | import java.util.concurrent.ExecutionException; | 42 | 42 | import java.util.concurrent.Executor; | | 43 | +import java.util.concurrent.ExecutorService; | | 44 | +import java.util.concurrent.Executors; | 43 | 45 | import java.util.concurrent.ScheduledExecutorService; | 44 | 46 | import java.util.concurrent.ThreadPoolExecutor; | 45 | 47 | import java.util.concurrent.TimeUnit; | @@ -540,6 +542,67 @@ public void testPendingScheduleTriggerTaskCount() throws Exception { | 540 | 542 | threadPoolExecutor.shutdown(); | 541 | 543 | } | 542 | 544 |
| | 545 | + /** | | 546 | + * A timing flush that runs after {@link TxnLogBufferedWriter#close()} must not touch the flush context that the | | 547 | + * close task recycled: writers share the executor thread, so another writer may already be using the recycled | | 548 | + * flush context. | | 549 | + */ | | 550 | + @Test | | 551 | + public void testTimingFlushAfterCloseDoesNotAffectOtherWriter() throws Exception { | | 552 | + ManagedLedger managedLedger = Mockito.mock(ManagedLedger.class); | | 553 | + Mockito.when(managedLedger.getName()).thenReturn(mlName); | | 554 | + Mockito.doAnswer(invocation -> { | | 555 | + AsyncCallbacks.AddEntryCallback callback = invocation.getArgument(1); | | 556 | + callback.addComplete(PositionFactory.create(1, 1), invocation.getArgument(0), | | 557 | + invocation.getArgument(2)); | | 558 | + return null; | | 559 | + }).when(managedLedger).asyncAddEntry(Mockito.any(ByteBuf.class), Mockito.any(), Mockito.any()); | | 560 | + // Both writers share the same single thread, like the writers of the topics that share a ML executor. | | 561 | + ExecutorService sharedExecutor = | | 562 | + Executors.newSingleThreadExecutor(new DefaultThreadFactory("txn-shared-executor")); | | 563 | + HashedWheelTimer transactionTimer = new HashedWheelTimer(new DefaultThreadFactory("transaction-timer"), | | 564 | + 1, TimeUnit.MILLISECONDS); | | 565 | + SumStrDataSerializer dataSerializer = new SumStrDataSerializer(); | | 566 | + TxnLogBufferedWriter.AddDataCallback callbackA = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class); | | 567 | + TxnLogBufferedWriter.AddDataCallback callbackB = Mockito.mock(TxnLogBufferedWriter.AddDataCallback.class); | | 568 | + try { | | 569 | + TxnLogBufferedWriter<Integer> writerA = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor, | | 570 | + transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true, | | 571 | + DISABLED_BUFFERED_WRITER_METRICS); | | 572 | + // Flush once, so that writer A's current flush context is obtained on the shared executor thread. | | 573 | + writerA.asyncAddData(1, callbackA, 1); | | 574 | + writerA.asyncAddData(1, callbackA, 2); | | 575 | + Awaitility.await().untilAsserted(() -> | | 576 | + Mockito.verify(callbackA, Mockito.times(2)).addComplete(Mockito.any(), Mockito.any())); | | 577 | + // Closing recycles writer A's current flush context on the shared executor thread. | | 578 | + writerA.close().get(); | | 579 | + | | 580 | + TxnLogBufferedWriter<Integer> writerB = new TxnLogBufferedWriter<>(managedLedger, sharedExecutor, | | 581 | + transactionTimer, dataSerializer, 2, Integer.MAX_VALUE, Integer.MAX_VALUE, true, | | 582 | + DISABLED_BUFFERED_WRITER_METRICS); | | 583 | + // The flush obtains a new flush context, which may be the one that writer A recycled. | | 584 | + writerB.asyncAddData(1, callbackB, 1); | | 585 | + writerB.asyncAddData(1, callbackB, 2); | | 586 | + // This request stays in writer B's current flush context. | | 587 | + writerB.asyncAddData(1, callbackB, 3); | | 588 | + sharedExecutor.submit(() -> { }).get(); | | 589 | + | | 590 | + // A timing flush of the closed writer A, e.g. one that was queued before the close task ran. | | 591 | + writerA.trigFlushByTimingTask(); | | 592 | + sharedExecutor.submit(() -> { }).get(); | | 593 | + Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any()); | | 594 | + | | 595 | + writerB.trigFlushByTimingTask(); | | 596 | + Awaitility.await().untilAsserted(() -> | | 597 | + Mockito.verify(callbackB, Mockito.times(3)).addComplete(Mockito.any(), Mockito.any())); | | 598 | + Mockito.verify(callbackB, Mockito.never()).addFailed(Mockito.any(), Mockito.any()); | | 599 | + writerB.close().get(); | | 600 | + } finally { | | 601 | + transactionTimer.stop(); | | 602 | + sharedExecutor.shutdownNow(); | | 603 | + } | | 604 | + } | | 605 | + | 543 | 606 | private static class JsonDataSerializer implements TxnLogBufferedWriter.DataSerializer<Integer>{ | 544 | 607 |
| 545 | 608 | private static ObjectMapper objectMapper = new ObjectMapper(); | |
|