-
Notifications
You must be signed in to change notification settings - Fork 3.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[fix][broker] Closed topics won't be removed from the cache #23884
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -20,12 +20,14 @@ | |
|
||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.Optional; | ||
import java.util.concurrent.CompletableFuture; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.apache.bookkeeper.mledger.Position; | ||
import org.apache.bookkeeper.mledger.PositionFactory; | ||
import org.apache.commons.collections4.map.LinkedMap; | ||
import org.apache.pulsar.broker.service.SystemTopicTxnBufferSnapshotService.ReferenceCountedWriter; | ||
import org.apache.pulsar.broker.service.Topic; | ||
import org.apache.pulsar.broker.service.persistent.PersistentTopic; | ||
import org.apache.pulsar.broker.transaction.buffer.AbortedTxnProcessor; | ||
import org.apache.pulsar.broker.transaction.buffer.metadata.AbortTxnMetadata; | ||
|
@@ -54,10 +56,20 @@ public SingleSnapshotAbortedTxnProcessorImpl(PersistentTopic topic) { | |
.getTransactionBufferSnapshotServiceFactory() | ||
.getTxnBufferSnapshotService().getReferenceWriter(TopicName.get(topic.getName()).getNamespaceObject()); | ||
this.takeSnapshotWriter.getFuture().exceptionally((ex) -> { | ||
log.error("{} Failed to create snapshot writer", topic.getName()); | ||
topic.close(); | ||
return null; | ||
}); | ||
log.error("{} Failed to create snapshot writer", topic.getName()); | ||
// Don't directly use the topic object to close, because the topicFuture might not | ||
// be completed at that time, which could leave closed topics in the cache(at BrokerService). | ||
CompletableFuture<Optional<Topic>> topicFuture = topic.getBrokerService().getTopics().get(topic.getName()); | ||
if (topicFuture != null) { | ||
topicFuture.thenAccept(t -> t.ifPresent(v -> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not sure why the value of |
||
v.close(true).exceptionally(ec -> { | ||
log.error("Close topic {} exception", v.getName(), ec); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If |
||
return null; | ||
}); | ||
})); | ||
} | ||
Comment on lines
+60
to
+70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This code is now duplicated in multiple locations. Instead of adding code duplication, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1 |
||
return null; | ||
}); | ||
} | ||
|
||
@Override | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -24,6 +24,7 @@ | |
import io.netty.util.Timer; | ||
import io.netty.util.TimerTask; | ||
import java.util.List; | ||
import java.util.Optional; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.ConcurrentHashMap; | ||
import java.util.concurrent.Semaphore; | ||
|
@@ -41,6 +42,7 @@ | |
import org.apache.commons.collections4.map.LinkedMap; | ||
import org.apache.pulsar.broker.service.BrokerServiceException; | ||
import org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException; | ||
import org.apache.pulsar.broker.service.Topic; | ||
import org.apache.pulsar.broker.service.persistent.PersistentTopic; | ||
import org.apache.pulsar.broker.systopic.SystemTopicClient; | ||
import org.apache.pulsar.broker.transaction.buffer.AbortedTxnProcessor; | ||
|
@@ -129,6 +131,23 @@ public TopicTransactionBuffer(PersistentTopic topic) { | |
this.recover(); | ||
} | ||
|
||
@VisibleForTesting | ||
TopicTransactionBuffer(PersistentTopic topic, AbortedTxnProcessor snapshotAbortedTxnProcessor, | ||
AbortedTxnProcessor.SnapshotType snapshotType) { | ||
super(State.None); | ||
this.topic = topic; | ||
this.timer = topic.getBrokerService().getPulsar().getTransactionTimer(); | ||
this.takeSnapshotIntervalNumber = topic.getBrokerService().getPulsar() | ||
.getConfiguration().getTransactionBufferSnapshotMaxTransactionCount(); | ||
this.takeSnapshotIntervalTime = topic.getBrokerService().getPulsar() | ||
.getConfiguration().getTransactionBufferSnapshotMinTimeInMillis(); | ||
this.maxReadPosition = topic.getManagedLedger().getLastConfirmedEntry(); | ||
this.snapshotAbortedTxnProcessor = snapshotAbortedTxnProcessor; | ||
this.snapshotType = snapshotType; | ||
this.maxReadPositionCallBack = topic.getMaxReadPositionCallBack(); | ||
this.recover(); | ||
} | ||
Comment on lines
+135
to
+149
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This new constructor overload has much duplicated code with the original constructor. Please reuse the code. It only just reduces duplicated code, but also simulate the real case more likely. Here is a bad example. Assuming there is a public Demo(Argument arg) {
this.field1 = arg.f();
this.field2 = arg.g();
} If you wanted to pass a mocked Demo(Argument arg, Field2 field2) {
this.field1 = arg.h();
this.field2 = field2;
} Then the new constructor will be meaningless. Because now |
||
|
||
private void recover() { | ||
recoverTime.setRecoverStartTime(System.currentTimeMillis()); | ||
this.topic.getBrokerService().getPulsar().getTransactionExecutorProvider().getExecutor(this) | ||
|
@@ -206,7 +225,18 @@ public void recoverExceptionally(Throwable e) { | |
getTransactionBufferFuture().completeExceptionally(e); | ||
} | ||
recoverTime.setRecoverEndTime(System.currentTimeMillis()); | ||
topic.close(true); | ||
// Don't directly use the topic object to close, because the topicFuture might not | ||
// be completed at that time, which could leave closed topics in the cache(at BrokerService). | ||
CompletableFuture<Optional<Topic>> topicFuture = | ||
topic.getBrokerService().getTopics().get(topic.getName()); | ||
if (topicFuture != null) { | ||
topicFuture.thenAccept(t -> t.ifPresent(v -> { | ||
v.close(true).exceptionally(ex -> { | ||
log.error("Close topic {} exception", v.getName(), ex); | ||
return null; | ||
}); | ||
})); | ||
} | ||
} | ||
}, this.topic, this, snapshotAbortedTxnProcessor)); | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,125 @@ | ||
/* | ||
* Licensed to the Apache Software Foundation (ASF) under one | ||
* or more contributor license agreements. See the NOTICE file | ||
* distributed with this work for additional information | ||
* regarding copyright ownership. The ASF licenses this file | ||
* to you under the Apache License, Version 2.0 (the | ||
* "License"); you may not use this file except in compliance | ||
* with the License. You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, | ||
* software distributed under the License is distributed on an | ||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
* KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations | ||
* under the License. | ||
*/ | ||
package org.apache.pulsar.broker.transaction.buffer.impl; | ||
|
||
import static org.mockito.ArgumentMatchers.any; | ||
import static org.mockito.ArgumentMatchers.eq; | ||
import static org.mockito.Mockito.doAnswer; | ||
import static org.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.spy; | ||
import static org.mockito.Mockito.when; | ||
import static org.testng.Assert.assertFalse; | ||
import static org.testng.Assert.assertTrue; | ||
import java.lang.reflect.Field; | ||
import java.util.Optional; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.CountDownLatch; | ||
import java.util.concurrent.TimeUnit; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.apache.pulsar.broker.BrokerTestUtil; | ||
import org.apache.pulsar.broker.service.BrokerService; | ||
import org.apache.pulsar.broker.service.PulsarStats; | ||
import org.apache.pulsar.broker.service.Topic; | ||
import org.apache.pulsar.broker.service.persistent.PersistentTopic; | ||
import org.apache.pulsar.broker.transaction.buffer.AbortedTxnProcessor; | ||
import org.apache.pulsar.broker.transaction.buffer.TransactionBuffer; | ||
import org.apache.pulsar.broker.transaction.buffer.TransactionBufferProvider; | ||
import org.apache.pulsar.client.api.ProducerConsumerBase; | ||
import org.awaitility.Awaitility; | ||
import org.testng.annotations.AfterClass; | ||
import org.testng.annotations.BeforeClass; | ||
import org.testng.annotations.Test; | ||
|
||
@Slf4j | ||
@Test(groups = "broker") | ||
public class TransactionPersistentTopicTest extends ProducerConsumerBase { | ||
|
||
@BeforeClass(alwaysRun = true) | ||
@Override | ||
protected void setup() throws Exception { | ||
conf.setTransactionCoordinatorEnabled(true); | ||
conf.setBrokerDeduplicationEnabled(false); | ||
super.internalSetup(); | ||
super.producerBaseSetup(); | ||
} | ||
|
||
@AfterClass(alwaysRun = true) | ||
@Override | ||
protected void cleanup() throws Exception { | ||
super.internalCleanup(); | ||
} | ||
|
||
@Test | ||
public void testNoOrphanClosedTopicIfTxnInternalFailed() throws Exception { | ||
String tpName = BrokerTestUtil.newUniqueName("persistent://public/default/tp2"); | ||
|
||
// 1. Intercept when the `topicFuture` is about to complete and wait until the topic close operation finishes. | ||
BrokerService brokerService = pulsar.getBrokerService(); | ||
Field pulsarStatsField = BrokerService.class.getDeclaredField("pulsarStats"); | ||
pulsarStatsField.setAccessible(true); | ||
PulsarStats pulsarStats = brokerService.getPulsarStats(); | ||
Comment on lines
+73
to
+76
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please avoid using reflection as much as possible in tests. It makes refactoring very hard. My experience refactoring some code of Pulsar is really terrible due to the reflection everywhere. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. +1 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I see you want to delay the But I think you can customize the |
||
PulsarStats spyPulsarStats = spy(pulsarStats); | ||
pulsarStatsField.set(brokerService, spyPulsarStats); | ||
CountDownLatch topicInitSuccessSignal = new CountDownLatch(1); | ||
doAnswer(invocation -> { | ||
topicInitSuccessSignal.countDown(); | ||
// Sleep 1s pending txn buffer recover failed and close topic | ||
Thread.sleep(1000); | ||
invocation.callRealMethod(); | ||
return null; | ||
}).when(spyPulsarStats).recordTopicLoadTimeValue(eq(tpName), any(Long.class)); | ||
|
||
// 2. Mock close topic when create transactionBuffer | ||
TransactionBufferProvider mockTransactionBufferProvider = new TransactionBufferProvider() { | ||
@Override | ||
public TransactionBuffer newTransactionBuffer(Topic originTopic) { | ||
AbortedTxnProcessor abortedTxnProcessor = mock(AbortedTxnProcessor.class); | ||
doAnswer(invocation -> { | ||
topicInitSuccessSignal.await(); | ||
return CompletableFuture.failedFuture(new RuntimeException("Mock recovery failed")); | ||
}).when(abortedTxnProcessor).recoverFromSnapshot(); | ||
when(abortedTxnProcessor.closeAsync()).thenReturn(CompletableFuture.completedFuture(null)); | ||
return new TopicTransactionBuffer( | ||
(PersistentTopic) originTopic, abortedTxnProcessor, AbortedTxnProcessor.SnapshotType.Single); | ||
} | ||
}; | ||
TransactionBufferProvider originalTransactionBufferProvider = pulsar.getTransactionBufferProvider(); | ||
pulsar.setTransactionBufferProvider(mockTransactionBufferProvider); | ||
|
||
// 3. Trigger create topic and assert topic load success. | ||
CompletableFuture<Optional<Topic>> firstLoad = brokerService.getTopic(tpName, true); | ||
Awaitility.await().ignoreExceptions().atMost(10, TimeUnit.SECONDS) | ||
.pollInterval(200, TimeUnit.MILLISECONDS) | ||
.untilAsserted(() -> { | ||
assertTrue(firstLoad.isDone()); | ||
assertFalse(firstLoad.isCompletedExceptionally()); | ||
}); | ||
|
||
// 4. Assert topic removed from cache | ||
Awaitility.await().ignoreExceptions().atMost(10, TimeUnit.SECONDS) | ||
.pollInterval(500, TimeUnit.MILLISECONDS) | ||
.untilAsserted(() -> { | ||
assertFalse(brokerService.getTopics().containsKey(tpName)); | ||
}); | ||
|
||
// 5. Set txn provider to back | ||
pulsar.setTransactionBufferProvider(originalTransactionBufferProvider); | ||
} | ||
|
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would be better to add
ex
to the log message here?