Skip to content
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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
Copy link
Contributor

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?

// 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 -> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why the value of topics is an Optional. I just have a question that when could the value be Optional.empty()? If so, an empty Optional will be cached and never removed.

v.close(true).exceptionally(ec -> {
log.error("Close topic {} exception", v.getName(), ec);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If close failed, the topic will still be cached. Should you call BrokerService#removeTopicFromCache in this case?

return null;
});
}));
}
Comment on lines +60 to +70
Copy link
Member

Choose a reason for hiding this comment

The 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,
I'd suggest to create a new public method directly in BrokerService which called closeTopicForcefullyIfExists. The javadoc should describe the purpose.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

return null;
});
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
Expand All @@ -44,6 +45,7 @@
import org.apache.commons.lang3.tuple.Pair;
import org.apache.pulsar.broker.service.BrokerServiceException;
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.systopic.SystemTopicClient;
import org.apache.pulsar.broker.transaction.buffer.AbortedTxnProcessor;
Expand Down Expand Up @@ -491,19 +493,41 @@ public PersistentWorker(PersistentTopic topic) {
.getTxnBufferSnapshotSegmentService()
.getReferenceWriter(TopicName.get(topic.getName()).getNamespaceObject());
this.snapshotSegmentsWriter.getFuture().exceptionally(ex -> {
log.error("{} Failed to create snapshot index writer", topic.getName());
topic.close();
return null;
});
log.error("{} Failed to create snapshot index 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 -> {
v.close(true).exceptionally(ec -> {
log.error("Close topic {} exception", v.getName(), ec);
return null;
});
}));
}
return null;
});
this.snapshotIndexWriter = this.topic.getBrokerService().getPulsar()
.getTransactionBufferSnapshotServiceFactory()
.getTxnBufferSnapshotIndexService()
.getReferenceWriter(TopicName.get(topic.getName()).getNamespaceObject());
this.snapshotIndexWriter.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 -> {
v.close(true).exceptionally(ec -> {
log.error("Close topic {} exception", v.getName(), ec);
return null;
});
}));
}
return null;
});
}

public CompletableFuture<Void> appendTask(OperationType operationType,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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
Copy link
Contributor

Choose a reason for hiding this comment

The 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 Demo class whose constructor is:

public Demo(Argument arg) {
    this.field1 = arg.f();
    this.field2 = arg.g();
}

If you wanted to pass a mocked field2 and added a new constructor;

Demo(Argument arg, Field2 field2) {
    this.field1 = arg.h();
    this.field2 = field2;
}

Then the new constructor will be meaningless. Because now field is not arg.f() anymore.


private void recover() {
recoverTime.setRecoverStartTime(System.currentTimeMillis());
this.topic.getBrokerService().getPulsar().getTransactionExecutorProvider().getExecutor(this)
Expand Down Expand Up @@ -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));
}
Expand Down
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
Copy link
Contributor

@BewareMyPower BewareMyPower Jan 23, 2025

Choose a reason for hiding this comment

The 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.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see you want to delay the openLedgerComplete method by sleeping 1 second in recordTopicLoadTimeValue so that topicFuture.complete will happen after the transaction failure.

But I think you can customize the TopicFactory to achieve the same goal. You can override the create method to create a PersistentTopic's subclass whose initialize() method will be delayed for some time

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);
}

}
Loading