This is an automated email from the ASF dual-hosted git repository.
Caideyipi pushed a commit to branch dev/1.3
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/dev/1.3 by this push:
new f08040270c8 [Backport] Prevent WAL loss during IoTConsensus recovery
(#19373)
f08040270c8 is described below
commit f08040270c801ac36f0d79cd327418ab21400e61
Author: Caideyipi <[email protected]>
AuthorDate: Tue Nov 24 09:50:02 2026 +0800
[Backport] Prevent WAL loss during IoTConsensus recovery (#19373)
Backports non-subscription recovery changes from
45cb9959f16bb5350c136b0e5ca6847cde853d2b (PR #19348) and WAL retention fix from
a739debb950b1623bb5891347a518bca91fb0121 (PR #19268) to dev/1.3.
---
.../pass/commit/IoTDBRegionReconstructWALIT.java | 208 +++++++++++++++++++++
.../apache/iotdb/consensus/iot/IoTConsensus.java | 64 +++++--
.../consensus/iot/IoTConsensusServerImpl.java | 68 +++++--
.../consensus/iot/logdispatcher/LogDispatcher.java | 74 ++++++--
.../consensus/iot/IoTConsensusRecoveryTest.java | 120 ++++++++++++
.../consensus/iot/IoTConsensusServerImplTest.java | 189 +++++++++++++++++++
.../storageengine/dataregion/wal/node/WALNode.java | 45 +++--
.../dataregion/wal/node/WALNodeTest.java | 43 +++++
8 files changed, 741 insertions(+), 70 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/confignode/it/regionmigration/pass/commit/IoTDBRegionReconstructWALIT.java
b/integration-test/src/test/java/org/apache/iotdb/confignode/it/regionmigration/pass/commit/IoTDBRegionReconstructWALIT.java
new file mode 100644
index 00000000000..548c6741cfb
--- /dev/null
+++
b/integration-test/src/test/java/org/apache/iotdb/confignode/it/regionmigration/pass/commit/IoTDBRegionReconstructWALIT.java
@@ -0,0 +1,208 @@
+/*
+ * 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.iotdb.confignode.it.regionmigration.pass.commit;
+
+import org.apache.iotdb.commons.cluster.NodeStatus;
+import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.db.it.utils.NodeDebugger;
+import org.apache.iotdb.it.env.EnvFactory;
+import org.apache.iotdb.it.env.cluster.config.MppCommonConfig;
+import org.apache.iotdb.it.env.cluster.config.MppDataNodeConfig;
+import org.apache.iotdb.it.env.cluster.config.MppJVMConfig;
+import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper;
+import org.apache.iotdb.it.framework.IoTDBTestRunner;
+import org.apache.iotdb.itbase.category.ClusterIT;
+
+import com.sun.jdi.ObjectReference;
+import com.sun.jdi.StackFrame;
+import com.sun.jdi.ThreadReference;
+import org.apache.tsfile.utils.Pair;
+import org.awaitility.Awaitility;
+import org.junit.After;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import java.net.ServerSocket;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import static
org.apache.iotdb.confignode.it.regionmigration.IoTDBRegionOperationReliabilityITFramework.getDataRegionMapWithLeader;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(IoTDBTestRunner.class)
+@Category(ClusterIT.class)
+public class IoTDBRegionReconstructWALIT {
+ private static final String SERVER =
"org.apache.iotdb.consensus.iot.IoTConsensusServerImpl";
+ private static final int ROWS = 12000;
+
+ @After
+ public void tearDown() {
+ EnvFactory.getEnv().cleanClusterEnvironment();
+ }
+
+ @Test
+ public void testReconstructRetainsIncrementalsDuringSnapshot() throws
Exception {
+ EnvFactory.getEnv()
+ .getConfig()
+ .getCommonConfig()
+ .setDataRegionConsensusProtocolClass(ConsensusFactory.IOT_CONSENSUS)
+
.setSchemaRegionConsensusProtocolClass(ConsensusFactory.RATIS_CONSENSUS)
+ .setDataReplicationFactor(2)
+ .setSchemaReplicationFactor(3)
+ .setDefaultDataRegionGroupNumPerDatabase(1)
+ .setDataRegionGroupExtensionPolicy("CUSTOM");
+ Properties properties = new Properties();
+ properties.setProperty("wal_file_size_threshold_in_byte", "16384");
+ properties.setProperty("delete_wal_files_period_in_ms", "3600000");
+ ((MppCommonConfig)
EnvFactory.getEnv().getConfig().getDataNodeCommonConfig())
+ .updateProperties(properties);
+ EnvFactory.getEnv().initClusterEnvironment(1, 3);
+ Map<DataNodeWrapper, Integer> ports = new HashMap<>();
+ for (DataNodeWrapper node : EnvFactory.getEnv().getDataNodeWrapperList()) {
+ int port;
+ try (ServerSocket socket = new ServerSocket(0)) {
+ port = socket.getLocalPort();
+ }
+ node.stopForcibly();
+ MppJVMConfig jvm = new MppJVMConfig();
+ jvm.setDebugPort(port);
+ node.changeConfig(
+ new MppDataNodeConfig(),
+ (MppCommonConfig)
EnvFactory.getEnv().getConfig().getDataNodeCommonConfig(),
+ jvm);
+ node.start();
+ ports.put(node, port);
+ }
+ EnvFactory.getAbstractEnv().checkClusterStatusWithoutUnknown();
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try {
+ final Map<Integer, Pair<Integer, Set<Integer>>> regions;
+ try (Connection connection = EnvFactory.getEnv().getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("create timeseries root.rebuild.d.s with
datatype=INT64, encoding=PLAIN");
+ statement.execute("insert into root.rebuild.d(time,s) values(0,0)");
+ statement.execute("flush");
+ regions = getDataRegionMapWithLeader(statement);
+ }
+ assertEquals(1, regions.size());
+ int region = regions.keySet().iterator().next();
+ Pair<Integer, Set<Integer>> peers = regions.get(region);
+ int sourceId = peers.left;
+ int targetId = peers.right.stream().filter(id -> id !=
sourceId).findFirst().get();
+ DataNodeWrapper source =
EnvFactory.getEnv().dataNodeIdToWrapper(sourceId).get();
+ DataNodeWrapper target =
EnvFactory.getEnv().dataNodeIdToWrapper(targetId).get();
+ DataNodeWrapper coordinator =
+ EnvFactory.getEnv().getDataNodeWrapperList().stream()
+ .filter(node -> node != source && node != target)
+ .findFirst()
+ .get();
+ try (Connection stableConnection =
EnvFactory.getEnv().getConnection(coordinator);
+ Statement stableStatement = stableConnection.createStatement();
+ NodeDebugger debugger = new NodeDebugger(ports.get(source), SERVER,
"transmitSnapshot")) {
+ Future<?> reconstruct =
+ executor.submit(
+ () -> {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(coordinator);
+ Statement statement = connection.createStatement()) {
+ statement.execute("reconstruct region " + region + " on "
+ targetId);
+ }
+ return null;
+ });
+ StackFrame frame = debugger.await(candidate -> true);
+ ThreadReference thread = frame.thread();
+ ObjectReference server = frame.thisObject();
+ ObjectReference wal =
+ (ObjectReference)
+
server.getValue(server.referenceType().fieldByName("consensusReqReader"));
+ for (int row = 1; row <= ROWS; row++) {
+ stableStatement.execute(
+ "insert into root.rebuild.d(time,s) values(" + row + "," + row +
")");
+ }
+ stableStatement.execute("flush");
+ wal.invokeMethod(
+ thread,
+ wal.referenceType().methodsByName("rollWALFile").get(0),
+ Collections.emptyList(),
+ ObjectReference.INVOKE_SINGLE_THREADED);
+ wal.invokeMethod(
+ thread,
+ wal.referenceType().methodsByName("deleteOutdatedFiles").get(0),
+ Collections.emptyList(),
+ ObjectReference.INVOKE_SINGLE_THREADED);
+ debugger.resume();
+ reconstruct.get(3, TimeUnit.MINUTES);
+ Awaitility.await()
+ .atMost(3, TimeUnit.MINUTES)
+ .until(
+ () -> {
+ try (ResultSet status = stableStatement.executeQuery("show
regions")) {
+ while (status.next()) {
+ if (status.getInt("RegionId") == region
+ && status.getInt("DataNodeId") == targetId) {
+ return "Running".equals(status.getString("Status"));
+ }
+ }
+ return false;
+ }
+ });
+ source.stopForcibly();
+ assertRows(stableStatement);
+ source.start();
+ EnvFactory.getAbstractEnv().checkNodeInStatus(sourceId,
NodeStatus.Running);
+ target.stopForcibly();
+ assertRows(stableStatement);
+ }
+ } finally {
+ executor.shutdownNow();
+ assertTrue(executor.awaitTermination(30, TimeUnit.SECONDS));
+ }
+ }
+
+ private static void assertRows(Statement statement) {
+ Awaitility.await()
+ .ignoreExceptionsInstanceOf(SQLException.class)
+ .atMost(1, TimeUnit.MINUTES)
+ .untilAsserted(
+ () -> {
+ try (ResultSet rows =
+ statement.executeQuery("select s from root.rebuild.d order
by time")) {
+ int expected = 0;
+ while (rows.next()) {
+ assertEquals(expected, rows.getLong(1));
+ assertEquals(expected, rows.getLong(2));
+ expected++;
+ }
+ assertEquals(ROWS + 1, expected);
+ }
+ });
+ }
+}
diff --git
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensus.java
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensus.java
index d15d6e365a7..3f89e619643 100644
---
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensus.java
+++
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensus.java
@@ -81,6 +81,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
@@ -138,25 +139,46 @@ public class IoTConsensus implements IConsensus {
@Override
public synchronized void start() throws IOException {
- initAndRecover();
- service.initSyncedServiceImpl(new IoTConsensusRPCServiceProcessor(this));
try {
- registerManager.register(service);
- } catch (StartupException e) {
- throw new IOException(e);
+ initAndRecover();
+ service.initSyncedServiceImpl(new IoTConsensusRPCServiceProcessor(this));
+ try {
+ registerManager.register(service);
+ } catch (StartupException e) {
+ throw new IOException(e);
+ }
+ if (updateReaderFuture == null) {
+ updateReaderFuture =
+ ScheduledExecutorUtil.safelyScheduleWithFixedDelay(
+ backgroundTaskService,
+ () ->
+ stateMachineMap
+ .values()
+ .forEach(impl ->
impl.getLogDispatcher().checkAndFlushIndex()),
+ READER_UPDATE_INTERVAL_IN_MINUTES,
+ READER_UPDATE_INTERVAL_IN_MINUTES,
+ TimeUnit.MINUTES);
+ }
+ } catch (IOException | RuntimeException e) {
+ cleanupAfterFailedStart(e);
+ throw e;
}
- if (updateReaderFuture == null) {
- updateReaderFuture =
- ScheduledExecutorUtil.safelyScheduleWithFixedDelay(
- backgroundTaskService,
- () ->
- stateMachineMap
- .values()
- .forEach(impl ->
impl.getLogDispatcher().checkAndFlushIndex()),
- READER_UPDATE_INTERVAL_IN_MINUTES,
- READER_UPDATE_INTERVAL_IN_MINUTES,
- TimeUnit.MINUTES);
+ }
+
+ private void cleanupAfterFailedStart(final Throwable startupFailure) {
+ if (updateReaderFuture != null) {
+ updateReaderFuture.cancel(false);
+ updateReaderFuture = null;
}
+ registerManager.deregisterAll();
+ for (IoTConsensusServerImpl impl : stateMachineMap.values()) {
+ try {
+ impl.stop();
+ } catch (RuntimeException e) {
+ startupFailure.addSuppressed(e);
+ }
+ }
+ stateMachineMap.clear();
}
private void initAndRecover() throws IOException {
@@ -186,6 +208,7 @@ public class IoTConsensus implements IConsensus {
}
}
if (correctPeerListBeforeStart != null) {
+ final AtomicReference<Exception> peerListResetFailure = new
AtomicReference<>();
BiConsumer<ConsensusGroupId, List<Peer>> resetPeerListWithoutThrow =
(consensusGroupId, peers) -> {
try {
@@ -193,6 +216,7 @@ public class IoTConsensus implements IConsensus {
} catch (ConsensusGroupNotExistException ignore) {
} catch (Exception e) {
+ peerListResetFailure.compareAndSet(null, e);
logger.warn("Failed to reset peer list while start", e);
}
};
@@ -206,6 +230,13 @@ public class IoTConsensus implements IConsensus {
.forEach(
consensusGroupId ->
resetPeerListWithoutThrow.accept(consensusGroupId,
Collections.emptyList()));
+ final Exception resetFailure = peerListResetFailure.get();
+ if (resetFailure != null) {
+ throw new IOException(resetFailure);
+ }
+ }
+ if (correctPeerListBeforeStart != null) {
+
stateMachineMap.values().forEach(IoTConsensusServerImpl::markPeerConfigurationRecovered);
}
stateMachineMap.values().forEach(IoTConsensusServerImpl::start);
}
@@ -354,6 +385,7 @@ public class IoTConsensus implements IConsensus {
// step 6: active new Peer
logger.info("[IoTConsensus] activate new peer...");
impl.activePeer(peer);
+ impl.waitNewPeerUntilSyncLogCompleted(peer);
// step 7: notify remote peer to clean up transferred snapshot
logger.info("[IoTConsensus] clean up remote snapshot...");
diff --git
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java
index 051bfc392cd..3f1df62e83c 100644
---
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java
+++
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java
@@ -116,6 +116,8 @@ public class IoTConsensusServerImpl {
private final String storageDir;
private final TreeSet<Peer> configuration;
private final AtomicLong searchIndex;
+ private final Object retentionPublicationLock = new Object();
+ private boolean recoveringPeerConfiguration;
private final LogDispatcher logDispatcher;
private IoTConsensusConfig config;
private final ConsensusReqReader consensusReqReader;
@@ -144,6 +146,7 @@ public class IoTConsensusServerImpl {
this.cacheQueueMap = new ConcurrentHashMap<>();
this.syncClientManager = syncClientManager;
this.configuration = configuration;
+ this.recoveringPeerConfiguration = configuration.isEmpty();
this.backgroundTaskService = backgroundTaskService;
this.config = config;
this.consensusGroupId = thisNode.getGroupId().toString();
@@ -159,12 +162,20 @@ public class IoTConsensusServerImpl {
}
public void start() {
- checkAndUpdateIndex();
+ synchronized (retentionPublicationLock) {
+ checkAndUpdateIndex();
+ }
MetricService.getInstance().addMetricSet(this.ioTConsensusServerMetrics);
stateMachine.start();
logDispatcher.start();
}
+ void markPeerConfigurationRecovered() {
+ synchronized (retentionPublicationLock) {
+ recoveringPeerConfiguration = false;
+ }
+ }
+
public void stop() {
logDispatcher.stop();
stateMachine.stop();
@@ -577,6 +588,10 @@ public class IoTConsensusServerImpl {
}
}
+ public void waitNewPeerUntilSyncLogCompleted(Peer peer) throws
ConsensusGroupModifyPeerException {
+ logDispatcher.waitUntilSyncLogCompleted(peer, getSearchIndex(),
TimeUnit.MINUTES.toMillis(10));
+ }
+
public void waitTargetPeerUntilSyncLogCompleted(Peer targetPeer)
throws ConsensusGroupModifyPeerException {
long checkIntervalInMs = 10_000L;
@@ -659,21 +674,31 @@ public class IoTConsensusServerImpl {
/** build SyncLog channel with safeIndex as the default initial sync index.
*/
public void buildSyncLogChannel(Peer targetPeer, boolean startNow) {
- buildSyncLogChannel(targetPeer, getMinSyncIndex(), startNow);
+ stateMachineLock.lock();
+ try {
+ synchronized (retentionPublicationLock) {
+ buildSyncLogChannel(targetPeer, getMinSyncIndex(), startNow);
+ }
+ } finally {
+ stateMachineLock.unlock();
+ }
}
public void buildSyncLogChannel(Peer targetPeer, long initialSyncIndex,
boolean startNow) {
- KillPoint.setKillPoint(DataNodeKillPoints.ORIGINAL_ADD_PEER_DONE);
- configuration.add(targetPeer);
- if (Objects.equals(targetPeer, thisNode)) {
- return;
+ synchronized (retentionPublicationLock) {
+ KillPoint.setKillPoint(DataNodeKillPoints.ORIGINAL_ADD_PEER_DONE);
+ configuration.add(targetPeer);
+ if (Objects.equals(targetPeer, thisNode)) {
+ return;
+ }
+ logDispatcher.addLogDispatcherThread(targetPeer, initialSyncIndex,
startNow);
+ checkAndUpdateSafeDeletedSearchIndex();
+ logger.info(
+ "[IoTConsensus] Successfully build sync log channel to {} with
initialSyncIndex {}. {}",
+ targetPeer,
+ initialSyncIndex,
+ startNow ? "Sync log channel has started." : "Sync log channel maybe
start later.");
}
- logDispatcher.addLogDispatcherThread(targetPeer, initialSyncIndex,
startNow);
- logger.info(
- "[IoTConsensus] Successfully build sync log channel to {} with
initialSyncIndex {}. {}",
- targetPeer,
- initialSyncIndex,
- startNow ? "Sync log channel has started." : "Sync log channel maybe
start later.");
}
/**
@@ -870,13 +895,18 @@ public class IoTConsensusServerImpl {
* latest SafelyDeletedSearchIndex again. This enables wal to be deleted in
a timely manner.
*/
void checkAndUpdateSafeDeletedSearchIndex() {
- if (configuration.isEmpty()) {
- logger.error(
- "Configuration is empty, which is unexpected. Safe deleted search
index won't be updated this time.");
- } else if (configuration.size() == 1) {
- consensusReqReader.setSafelyDeletedSearchIndex(Long.MAX_VALUE);
- } else {
- consensusReqReader.setSafelyDeletedSearchIndex(getMinFlushedSyncIndex());
+ synchronized (retentionPublicationLock) {
+ if (recoveringPeerConfiguration) {
+ return;
+ }
+ if (configuration.isEmpty()) {
+ logger.error(
+ "Configuration is empty, which is unexpected. Safe deleted search
index won't be updated this time.");
+ } else if (configuration.size() == 1) {
+ consensusReqReader.setSafelyDeletedSearchIndex(Long.MAX_VALUE);
+ } else {
+
consensusReqReader.setSafelyDeletedSearchIndex(getMinFlushedSyncIndex());
+ }
}
}
diff --git
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java
index 374691bf38b..cfab1cacc38 100644
---
a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java
+++
b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/logdispatcher/LogDispatcher.java
@@ -27,6 +27,7 @@ import org.apache.iotdb.commons.service.metric.MetricService;
import org.apache.iotdb.consensus.common.Peer;
import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
import org.apache.iotdb.consensus.config.IoTConsensusConfig;
+import org.apache.iotdb.consensus.exception.ConsensusGroupModifyPeerException;
import org.apache.iotdb.consensus.iot.IoTConsensusServerImpl;
import org.apache.iotdb.consensus.iot.client.AsyncIoTConsensusServiceClient;
import org.apache.iotdb.consensus.iot.client.DispatchLogHandler;
@@ -101,7 +102,11 @@ public class LogDispatcher {
public synchronized void start() {
if (!threads.isEmpty()) {
- threads.forEach(logDispatcherThread ->
executorService.submit(logDispatcherThread));
+ threads.forEach(
+ logDispatcherThread -> {
+ logDispatcherThread.markSubmitted();
+ executorService.submit(logDispatcherThread);
+ });
}
}
@@ -136,6 +141,7 @@ public class LogDispatcher {
initLogSyncThreadPool();
}
if (startNow) {
+ thread.markSubmitted();
executorService.submit(thread);
}
}
@@ -167,6 +173,41 @@ public class LogDispatcher {
return
threads.stream().mapToLong(LogDispatcherThread::getLastFlushedSyncIndex).min();
}
+ public void waitUntilSyncLogCompleted(Peer peer, long targetIndex, long
timeoutMs)
+ throws ConsensusGroupModifyPeerException {
+ LogDispatcherThread thread = null;
+ synchronized (this) {
+ for (LogDispatcherThread candidate : threads) {
+ if (candidate.getPeer().equals(peer)) {
+ thread = candidate;
+ break;
+ }
+ }
+ }
+ if (thread == null) {
+ throw new ConsensusGroupModifyPeerException(new IllegalStateException());
+ }
+ final long deadline = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(timeoutMs);
+ while (true) {
+ if (thread.replicationFailure != null) {
+ throw new ConsensusGroupModifyPeerException(thread.replicationFailure);
+ }
+ if (thread.stopped) {
+ throw new ConsensusGroupModifyPeerException(new
IllegalStateException());
+ }
+ if (thread.getCurrentSyncIndex() >= targetIndex) return;
+ if (System.nanoTime() >= deadline) {
+ throw new ConsensusGroupModifyPeerException(new
java.util.concurrent.TimeoutException());
+ }
+ try {
+ TimeUnit.MILLISECONDS.sleep(100);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw new ConsensusGroupModifyPeerException(e);
+ }
+ }
+ }
+
public void checkAndFlushIndex() {
if (!threads.isEmpty()) {
threads.forEach(
@@ -229,6 +270,7 @@ public class LogDispatcher {
(ConsensusReqReader) impl.getStateMachine().read(new
GetConsensusReqReaderPlan());
private final IoTConsensusMemoryManager iotConsensusMemoryManager =
IoTConsensusMemoryManager.getInstance();
+ private volatile Exception replicationFailure;
private volatile boolean stopped = false;
private final ConsensusReqReader.ReqIterator walEntryIterator;
@@ -236,6 +278,7 @@ public class LogDispatcher {
private final LogDispatcherThreadMetrics logDispatcherThreadMetrics;
private final CountDownLatch runFinished = new CountDownLatch(1);
+ private volatile boolean submitted;
public LogDispatcherThread(Peer peer, IoTConsensusConfig config, long
initialSyncIndex) {
this.peer = peer;
@@ -311,8 +354,13 @@ public class LogDispatcher {
processStopped();
}
+ private void markSubmitted() {
+ submitted = true;
+ }
+
private void setStopped() {
stopped = true;
+ if (!submitted) runFinished.countDown();
}
private void processStopped() {
@@ -386,6 +434,7 @@ public class LogDispatcher {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (Exception e) {
+ replicationFailure = e;
logger.error("Unexpected error in logDispatcher for peer {}", peer, e);
}
runFinished.countDown();
@@ -453,9 +502,8 @@ public class LogDispatcher {
// Prevents gap between logs. For example, some requests are not
written into the queue when
// the queue is full. In this case, requests need to be loaded from
the WAL
if (startIndex != prev.getSearchIndex()) {
- boolean hasCorruptedData =
- constructBatchFromWAL(startIndex, prev.getSearchIndex(),
batches);
- if (hasCorruptedData || !batches.canAccumulate()) {
+ constructBatchFromWAL(startIndex, prev.getSearchIndex(), batches);
+ if (!batches.canAccumulate()) {
batches.buildIndex();
logger.debug(
"{} : accumulated a {} from wal",
impl.getThisNode().getGroupId(), batches);
@@ -478,9 +526,8 @@ public class LogDispatcher {
// Prevents gap between logs. For example, some logs are not written
into the queue when
// the queue is full. In this case, requests need to be loaded from
the WAL
if (current.getSearchIndex() != prev.getSearchIndex() + 1) {
- boolean hasCorruptedData =
- constructBatchFromWAL(prev.getSearchIndex() + 1,
current.getSearchIndex(), batches);
- if (hasCorruptedData || !batches.canAccumulate()) {
+ constructBatchFromWAL(prev.getSearchIndex() + 1,
current.getSearchIndex(), batches);
+ if (!batches.canAccumulate()) {
batches.buildIndex();
logger.debug(
"gap {} : accumulated a {} from queue and wal when gap",
@@ -526,14 +573,13 @@ public class LogDispatcher {
return syncStatus;
}
- private boolean constructBatchFromWAL(long currentIndex, long maxIndex,
Batch logBatches) {
+ private void constructBatchFromWAL(long currentIndex, long maxIndex, Batch
logBatches) {
logger.debug(
"DataRegion[{}]->{}: currentIndex: {}, maxIndex: {}",
peer.getGroupId().getId(),
peer.getEndpoint().getIp(),
currentIndex,
maxIndex);
- boolean hasCorruptedData = false;
// targetIndex is the index of request that we need to find
long targetIndex = currentIndex;
// Even if there is no WAL files, these code won't produce error.
@@ -555,12 +601,7 @@ public class LogDispatcher {
data.getSearchIndex());
continue;
} else if (data.getSearchIndex() > targetIndex) {
- logger.warn(
- "search for one Entry which index is {}, but find a larger one,
index : {}."
- + "Perhaps the wal file is corrupted, in which case we skip
it and choose a larger index to replicate",
- targetIndex,
- data.getSearchIndex());
- hasCorruptedData = true;
+ throw new IllegalStateException();
}
targetIndex = data.getSearchIndex() + 1;
data.buildSerializedRequests();
@@ -569,9 +610,6 @@ public class LogDispatcher {
new TLogEntry(
data.getSerializedRequests(), data.getSearchIndex(), true,
data.getMemorySize()));
}
- // In the case of corrupt Data, we return true so that we can send a
batch as soon as
- // possible, avoiding potential duplication
- return hasCorruptedData;
}
private void constructBatchIndexedFromConsensusRequest(
diff --git
a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusRecoveryTest.java
b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusRecoveryTest.java
new file mode 100644
index 00000000000..1d589bbe440
--- /dev/null
+++
b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusRecoveryTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.iotdb.consensus.iot;
+
+import org.apache.iotdb.common.rpc.thrift.TConsensusGroupType;
+import org.apache.iotdb.common.rpc.thrift.TEndPoint;
+import org.apache.iotdb.commons.consensus.DataRegionId;
+import org.apache.iotdb.consensus.IStateMachine;
+import org.apache.iotdb.consensus.common.DataSet;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.config.ConsensusConfig;
+import org.apache.iotdb.consensus.iot.log.GetConsensusReqReaderPlan;
+import org.apache.iotdb.consensus.iot.util.FakeConsensusReqReader;
+import org.apache.iotdb.consensus.iot.util.RequestSets;
+import org.apache.iotdb.consensus.iot.util.TestStateMachine;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class IoTConsensusRecoveryTest {
+
+ @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Test
+ public void testPeerListResetFailureAbortsRecoveryAndStopsCreatedPeer()
throws Exception {
+ File storageDir = temporaryFolder.newFolder("consensus");
+ DataRegionId regionId = new DataRegionId(1);
+ TEndPoint selfEndpoint = new TEndPoint("127.0.0.1", 6667);
+ Peer self = new Peer(regionId, 0, selfEndpoint);
+ IoTConsensus initialConsensus =
+ newConsensus(storageDir, selfEndpoint, groupId -> new
TestStateMachine());
+ try {
+ initialConsensus.createLocalPeer(regionId,
Collections.singletonList(self));
+ } finally {
+ initialConsensus.stop();
+ }
+
+ AtomicInteger iteratorCount = new AtomicInteger();
+ FakeConsensusReqReader reader =
+ new FakeConsensusReqReader(new RequestSets(Collections.emptySet())) {
+ @Override
+ public ReqIterator getReqIterator(long startIndex) {
+ if (iteratorCount.getAndIncrement() == 0) {
+ return super.getReqIterator(startIndex);
+ }
+ throw new IllegalStateException("failed to restore peer list");
+ }
+ };
+ AtomicBoolean stateMachineStopped = new AtomicBoolean();
+ TestStateMachine recoveredStateMachine =
+ new TestStateMachine() {
+ @Override
+ public synchronized DataSet read(IConsensusRequest request) {
+ return request instanceof GetConsensusReqReaderPlan ? reader :
null;
+ }
+
+ @Override
+ public void stop() {
+ stateMachineStopped.set(true);
+ }
+ };
+ IoTConsensus recoveringConsensus =
+ newConsensus(storageDir, selfEndpoint, groupId ->
recoveredStateMachine);
+ Peer firstPeer = new Peer(regionId, 1, new TEndPoint("127.0.0.1", 6668));
+ Peer secondPeer = new Peer(regionId, 2, new TEndPoint("127.0.0.1", 6669));
+ recoveringConsensus.recordCorrectPeerListBeforeStarting(
+ Collections.singletonMap(regionId, Arrays.asList(self, firstPeer,
secondPeer)));
+
+ try {
+ IOException failure = assertThrows(IOException.class,
recoveringConsensus::start);
+
+ assertTrue(failure.getCause() instanceof IllegalStateException);
+ assertTrue(stateMachineStopped.get());
+ assertTrue(recoveringConsensus.getAllConsensusGroupIds().isEmpty());
+ } finally {
+ recoveringConsensus.stop();
+ }
+ }
+
+ private IoTConsensus newConsensus(
+ File storageDir, TEndPoint selfEndpoint, IStateMachine.Registry
registry) {
+ ConsensusConfig config =
+ ConsensusConfig.newBuilder()
+ .setThisNodeId(0)
+ .setThisNode(selfEndpoint)
+ .setStorageDir(storageDir.getAbsolutePath())
+ .setConsensusGroupType(TConsensusGroupType.DataRegion)
+ .build();
+ return new IoTConsensus(config, registry);
+ }
+}
diff --git
a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java
b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java
index 64c2ea56a04..fd14a8a9e2e 100644
---
a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java
+++
b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImplTest.java
@@ -23,10 +23,16 @@ import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.consensus.DataRegionId;
import org.apache.iotdb.commons.utils.StatusUtils;
+import org.apache.iotdb.consensus.common.DataSet;
import org.apache.iotdb.consensus.common.Peer;
import
org.apache.iotdb.consensus.common.request.DeserializedBatchIndexedConsensusRequest;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
import org.apache.iotdb.consensus.common.request.IndexedConsensusRequest;
import org.apache.iotdb.consensus.config.IoTConsensusConfig;
+import org.apache.iotdb.consensus.exception.ConsensusGroupModifyPeerException;
+import org.apache.iotdb.consensus.iot.logdispatcher.LogDispatcher;
+import org.apache.iotdb.consensus.iot.util.FakeConsensusReqReader;
+import org.apache.iotdb.consensus.iot.util.RequestSets;
import org.apache.iotdb.consensus.iot.util.TestEntry;
import org.apache.iotdb.consensus.iot.util.TestStateMachine;
import org.apache.iotdb.rpc.TSStatusCode;
@@ -35,21 +41,204 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
import java.util.Collections;
+import java.util.List;
import java.util.TreeSet;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class IoTConsensusServerImplTest {
@Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @Test
+ public void testRecoveryDoesNotPublishWalBoundaryUntilPeerListIsRestored()
throws Exception {
+ AtomicLong boundary = new AtomicLong();
+ AtomicInteger boundaryUpdates = new AtomicInteger();
+ FakeConsensusReqReader reader =
+ new FakeConsensusReqReader(new RequestSets(Collections.emptySet())) {
+ @Override
+ public void setSafelyDeletedSearchIndex(long
safelyDeletedSearchIndex) {
+ boundary.set(safelyDeletedSearchIndex);
+ boundaryUpdates.incrementAndGet();
+ }
+ };
+ ScheduledExecutorService background =
Executors.newSingleThreadScheduledExecutor();
+ Peer self = new Peer(new DataRegionId(1), 0, new TEndPoint("127.0.0.1",
6667));
+ Peer peer = new Peer(new DataRegionId(1), 1, new TEndPoint("127.0.0.1",
6668));
+ IoTConsensusServerImpl server =
+ new IoTConsensusServerImpl(
+ temporaryFolder.getRoot().getAbsolutePath(),
+ self,
+ new TreeSet<>(),
+ new TestStateMachine() {
+ @Override
+ public synchronized DataSet read(IConsensusRequest request) {
+ return reader;
+ }
+ },
+ background,
+ null,
+ null,
+ IoTConsensusConfig.newBuilder().build());
+ try {
+ server.buildSyncLogChannel(self, false);
+ server.buildSyncLogChannel(peer, false);
+ assertEquals(0, boundaryUpdates.get());
+
+ server.markPeerConfigurationRecovered();
+ server.checkAndUpdateSafeDeletedSearchIndex();
+
+ assertEquals(1, boundaryUpdates.get());
+ assertFalse(boundary.get() == Long.MAX_VALUE);
+ } finally {
+ server.stop();
+ background.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testNewPeerImmediatelyProtectsWALAndCatchupTimesOut() throws
Exception {
+ AtomicLong boundary = new AtomicLong();
+ FakeConsensusReqReader reader =
+ new FakeConsensusReqReader(new RequestSets(Collections.emptySet())) {
+ @Override
+ public void setSafelyDeletedSearchIndex(long
safelyDeletedSearchIndex) {
+ boundary.set(safelyDeletedSearchIndex);
+ }
+ };
+ ScheduledExecutorService background =
Executors.newSingleThreadScheduledExecutor();
+ Peer self = new Peer(new DataRegionId(1), 0, new TEndPoint("127.0.0.1",
6667));
+ Peer peer = new Peer(new DataRegionId(1), 1, new TEndPoint("127.0.0.1",
6668));
+ IoTConsensusServerImpl server = newRetentionTestServer(self, reader,
background);
+ try {
+ server.getIndexObject().set(10);
+ server.checkAndUpdateSafeDeletedSearchIndex();
+ assertEquals(Long.MAX_VALUE, boundary.get());
+ server.buildSyncLogChannel(peer, false);
+ assertEquals(10, boundary.get());
+ server.getLogDispatcher().waitUntilSyncLogCompleted(peer, 10, 100);
+ assertThrows(
+ ConsensusGroupModifyPeerException.class,
+ () -> server.getLogDispatcher().waitUntilSyncLogCompleted(peer, 11,
1));
+ } finally {
+ server.stop();
+ background.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testMissingWALCannotProduceAnAcknowledgableBatch() throws
Exception {
+ FakeConsensusReqReader reader =
+ new FakeConsensusReqReader(new RequestSets(Collections.emptySet())) {
+ @Override
+ public ReqIterator getReqIterator(long startIndex) {
+ return new ReqIterator() {
+ @Override
+ public boolean hasNext() {
+ return true;
+ }
+
+ @Override
+ public IndexedConsensusRequest next() {
+ return new IndexedConsensusRequest(4, Collections.emptyList());
+ }
+
+ @Override
+ public void waitForNextReady() {}
+
+ @Override
+ public void waitForNextReady(long time, TimeUnit unit) {}
+
+ @Override
+ public void skipTo(long targetIndex) {}
+ };
+ }
+ };
+ ScheduledExecutorService background =
Executors.newSingleThreadScheduledExecutor();
+ Peer self = new Peer(new DataRegionId(1), 0, new TEndPoint("127.0.0.1",
6667));
+ Peer peer = new Peer(new DataRegionId(1), 1, new TEndPoint("127.0.0.1",
6668));
+ IoTConsensusServerImpl server = newRetentionTestServer(self, reader,
background);
+ try {
+ server.getIndexObject().set(4);
+ server.buildSyncLogChannel(peer, 0, false);
+ Field threadsField = LogDispatcher.class.getDeclaredField("threads");
+ threadsField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ List<LogDispatcher.LogDispatcherThread> threads =
+ (List<LogDispatcher.LogDispatcherThread>)
threadsField.get(server.getLogDispatcher());
+ LogDispatcher.LogDispatcherThread thread = threads.get(0);
+ assertThrows(IllegalStateException.class, thread::getBatch);
+ assertEquals(0, thread.getCurrentSyncIndex());
+ thread.run();
+ assertThrows(
+ ConsensusGroupModifyPeerException.class,
+ () -> server.getLogDispatcher().waitUntilSyncLogCompleted(peer, 4,
100));
+ } finally {
+ server.stop();
+ background.shutdownNow();
+ }
+ }
+
+ @Test
+ public void testStoppingUnsubmittedDispatcherCompletesWaitLatch() throws
Exception {
+ FakeConsensusReqReader reader =
+ new FakeConsensusReqReader(new RequestSets(Collections.emptySet()));
+ ScheduledExecutorService background =
Executors.newSingleThreadScheduledExecutor();
+ Peer self = new Peer(new DataRegionId(1), 0, new TEndPoint("127.0.0.1",
6667));
+ Peer peer = new Peer(new DataRegionId(1), 1, new TEndPoint("127.0.0.1",
6668));
+ IoTConsensusServerImpl server = newRetentionTestServer(self, reader,
background);
+ try {
+ server.buildSyncLogChannel(peer, false);
+ Field threadsField = LogDispatcher.class.getDeclaredField("threads");
+ threadsField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ List<LogDispatcher.LogDispatcherThread> threads =
+ (List<LogDispatcher.LogDispatcherThread>)
threadsField.get(server.getLogDispatcher());
+ Object dispatcherThread = threads.get(0);
+ Field runFinishedField =
dispatcherThread.getClass().getDeclaredField("runFinished");
+ runFinishedField.setAccessible(true);
+ CountDownLatch runFinished = (CountDownLatch)
runFinishedField.get(dispatcherThread);
+ Method setStopped =
dispatcherThread.getClass().getDeclaredMethod("setStopped");
+ setStopped.setAccessible(true);
+ setStopped.invoke(dispatcherThread);
+ assertEquals(0, runFinished.getCount());
+ } finally {
+ server.stop();
+ background.shutdownNow();
+ }
+ }
+
+ private IoTConsensusServerImpl newRetentionTestServer(
+ Peer self, FakeConsensusReqReader reader, ScheduledExecutorService
background) {
+ return new IoTConsensusServerImpl(
+ temporaryFolder.getRoot().getAbsolutePath(),
+ self,
+ new TreeSet<>(Collections.singletonList(self)),
+ new TestStateMachine() {
+ @Override
+ public synchronized DataSet read(IConsensusRequest request) {
+ return reader;
+ }
+ },
+ background,
+ null,
+ null,
+ IoTConsensusConfig.newBuilder().build());
+ }
+
@Test
public void testSyncLogBecomesReadOnlyWhileWaiting() throws Exception {
final ScheduledExecutorService backgroundTaskService =
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNode.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNode.java
index b0e19364ddb..5bade724c31 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNode.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNode.java
@@ -107,6 +107,7 @@ public class WALNode implements IWALNode {
// used to avoid write amplification caused by frequent snapshot
private final Map<Long, Integer> memTableSnapshotCount = new
ConcurrentHashMap<>();
// insert nodes whose search index are before this value can be deleted
safely
+ private final Object walRetentionLock = new Object();
private volatile long safelyDeletedSearchIndex =
DEFAULT_SAFELY_DELETED_SEARCH_INDEX;
private volatile boolean deleted = false;
@@ -242,13 +243,14 @@ public class WALNode implements IWALNode {
private File[] sortedWalFilesExcludingLast;
private List<MemTableInfo> activeOrPinnedMemTables;
+ private long cachedSafelyDeletedSearchIndex;
+ private int fileIndexAfterFilterSafelyDeleteIndex;
private static final int MAX_RECURSION_TIME = 5;
// the effective information ratio
private double effectiveInfoRatio = 1.0d;
- private int fileIndexAfterFilterSafelyDeleteIndex = Integer.MAX_VALUE;
private List<Long> successfullyDeleted;
private long deleteFileSize;
@@ -273,7 +275,7 @@ public class WALNode implements IWALNode {
this.sortedWalFilesExcludingLast =
Arrays.copyOfRange(allWalFilesOfOneNode, 0,
allWalFilesOfOneNode.length - 1);
this.activeOrPinnedMemTables =
checkpointManager.activeOrPinnedMemTables();
- this.fileIndexAfterFilterSafelyDeleteIndex =
initFileIndexAfterFilterSafelyDeleteIndex();
+ updateFileIndexAfterFilterSafelyDeleteIndex();
this.successfullyDeleted = new ArrayList<>();
this.deleteFileSize = 0;
return true;
@@ -362,15 +364,17 @@ public class WALNode implements IWALNode {
File currentWal = sortedWalFilesExcludingLast[fileArrIdx];
WALFileStatus walFileStatus =
WALFileUtils.parseStatusCode(currentWal.getName());
long versionId = WALFileUtils.parseVersionId(currentWal.getName());
- if (canDeleteFile(fileArrIdx, walFileStatus, versionId)) {
- long fileSize = currentWal.length();
- if (currentWal.delete()) {
- deleteFileSize += fileSize;
- buffer.removeMemTableIdsOfWal(versionId);
- successfullyDeleted.add(versionId);
- } else {
- logger.info(
- "Fail to delete outdated wal file {} of wal node-{}.",
currentWal, identifier);
+ synchronized (walRetentionLock) {
+ if (canDeleteFile(fileArrIdx, walFileStatus, versionId)) {
+ long fileSize = currentWal.length();
+ if (currentWal.delete()) {
+ deleteFileSize += fileSize;
+ buffer.removeMemTableIdsOfWal(versionId);
+ successfullyDeleted.add(versionId);
+ } else {
+ logger.info(
+ "Fail to delete outdated wal file {} of wal node-{}.",
currentWal, identifier);
+ }
}
}
}
@@ -378,11 +382,13 @@ public class WALNode implements IWALNode {
buffer.subtractFileNum(successfullyDeleted.size());
}
- private int initFileIndexAfterFilterSafelyDeleteIndex() {
- return safelyDeletedSearchIndex == DEFAULT_SAFELY_DELETED_SEARCH_INDEX
- ? sortedWalFilesExcludingLast.length
- : WALFileUtils.binarySearchFileBySearchIndex(
- sortedWalFilesExcludingLast, safelyDeletedSearchIndex + 1);
+ private void updateFileIndexAfterFilterSafelyDeleteIndex() {
+ cachedSafelyDeletedSearchIndex = safelyDeletedSearchIndex;
+ fileIndexAfterFilterSafelyDeleteIndex =
+ cachedSafelyDeletedSearchIndex == DEFAULT_SAFELY_DELETED_SEARCH_INDEX
+ ? sortedWalFilesExcludingLast.length
+ : WALFileUtils.binarySearchFileBySearchIndex(
+ sortedWalFilesExcludingLast, cachedSafelyDeletedSearchIndex
+ 1);
}
/** Return true iff effective information ratio is too small or disk usage
is too large. */
@@ -548,6 +554,9 @@ public class WALNode implements IWALNode {
}
private boolean canDeleteFile(long fileArrIdx, WALFileStatus
walFileStatus, long versionId) {
+ if (cachedSafelyDeletedSearchIndex != safelyDeletedSearchIndex) {
+ updateFileIndexAfterFilterSafelyDeleteIndex();
+ }
return (fileArrIdx < fileIndexAfterFilterSafelyDeleteIndex
|| walFileStatus == WALFileStatus.CONTAINS_NONE_SEARCH_INDEX)
&& !isContainsActiveOrPinnedMemTable(versionId);
@@ -559,7 +568,9 @@ public class WALNode implements IWALNode {
// region Search interfaces for consensus group
@Override
public void setSafelyDeletedSearchIndex(long safelyDeletedSearchIndex) {
- this.safelyDeletedSearchIndex = safelyDeletedSearchIndex;
+ synchronized (walRetentionLock) {
+ this.safelyDeletedSearchIndex = safelyDeletedSearchIndex;
+ }
}
/** This iterator is not concurrency-safe, cannot read the current-writing
wal file. */
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNodeTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNodeTest.java
index 661675d9688..9e5403fcbab 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNodeTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/wal/node/WALNodeTest.java
@@ -52,6 +52,8 @@ import org.junit.Before;
import org.junit.Test;
import java.io.File;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -261,6 +263,47 @@ public class WALNodeTest {
assertEquals(expectedMemTableId2Info, actualMemTableId2Info);
}
+ @Test
+ public void testCleanupRechecksLoweredReplicationBoundary() throws Exception
{
+ IMemTable memTable = new PrimitiveMemTable(databasePath, dataRegionId);
+ long memTableId = memTable.getMemTableId();
+ String tsFilePath = logDirectory + File.separator + memTableId + ".tsfile";
+ walNode.onMemTableCreated(memTable, tsFilePath);
+ for (long index = 1; index <= 3; index++) {
+ InsertTabletNode node = getInsertTabletNode(devicePath, new long[]
{index});
+ node.setSearchIndex(index);
+ assertEquals(
+ WALFlushListener.Status.SUCCESS,
+ walNode.log(memTableId, node, 0,
node.getRowCount()).waitForResult());
+ walNode.rollWALFile();
+ }
+ walNode.onMemTableFlushed(memTable);
+ Awaitility.await().until(walNode::isAllWALEntriesConsumed);
+ walNode.setSafelyDeletedSearchIndex(Long.MAX_VALUE - 1);
+ Class<?> taskClass = Class.forName(WALNode.class.getName() +
"$DeleteOutdatedFileTask");
+ Constructor<?> constructor =
taskClass.getDeclaredConstructor(WALNode.class);
+ constructor.setAccessible(true);
+ Object task = constructor.newInstance(walNode);
+ Method initialize =
taskClass.getDeclaredMethod("initAndCheckIfNeedContinue");
+ initialize.setAccessible(true);
+ assertTrue((Boolean) initialize.invoke(task));
+ walNode.setSafelyDeletedSearchIndex(0);
+ Method delete =
taskClass.getDeclaredMethod("deleteOutdatedFilesAndUpdateMetric");
+ delete.setAccessible(true);
+ delete.invoke(task);
+ int retained = 0;
+ for (File file : WALFileUtils.listAllWALFiles(new File(logDirectory))) {
+ try (WALReader reader = new WALReader(file)) {
+ while (reader.hasNext()) {
+ if (reader.next().getValue() instanceof InsertTabletNode) {
+ retained++;
+ }
+ }
+ }
+ }
+ assertEquals(3, retained);
+ }
+
@Test
public void testDeleteOutdatedFiles() throws Exception {
// write data to make the first WAL file non-empty