You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by ta...@apache.org on 2023/07/25 02:33:56 UTC

[iotdb] branch rel/1.2 updated: [IOTDB-5557] [RatisConsensus] Support linearizable read during recovery (#10597) (#10673)

This is an automated email from the ASF dual-hosted git repository.

tanxinyu pushed a commit to branch rel/1.2
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/rel/1.2 by this push:
     new 2882ab5ee26 [IOTDB-5557] [RatisConsensus] Support linearizable read during recovery (#10597) (#10673)
2882ab5ee26 is described below

commit 2882ab5ee26027c903d157eae97e4353985980e8
Author: William Song <48...@users.noreply.github.com>
AuthorDate: Tue Jul 25 10:33:50 2023 +0800

    [IOTDB-5557] [RatisConsensus] Support linearizable read during recovery (#10597) (#10673)
---
 .../apache/iotdb/consensus/config/RatisConfig.java |  64 +++++-
 .../exception/RatisUnderRecoveryException.java     |  31 +++
 .../iotdb/consensus/ratis/RatisConsensus.java      |  58 ++++-
 .../apache/iotdb/consensus/ratis/utils/Utils.java  |   7 +
 .../iotdb/consensus/ratis/RatisConsensusTest.java  |   1 +
 .../iotdb/consensus/ratis/RecoverReadTest.java     | 238 +++++++++++++++++++++
 .../apache/iotdb/consensus/ratis/TestUtils.java    |  85 +++++++-
 7 files changed, 463 insertions(+), 21 deletions(-)

diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/config/RatisConfig.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/config/RatisConfig.java
index a6c91d672db..08bc80d9ed7 100644
--- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/config/RatisConfig.java
+++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/config/RatisConfig.java
@@ -40,6 +40,7 @@ public class RatisConfig {
   private final Client client;
   private final Impl impl;
   private final LeaderLogAppender leaderLogAppender;
+  private final Read read;
 
   private RatisConfig(
       Rpc rpc,
@@ -50,7 +51,8 @@ public class RatisConfig {
       Grpc grpc,
       Client client,
       Impl impl,
-      LeaderLogAppender leaderLogAppender) {
+      LeaderLogAppender leaderLogAppender,
+      Read read) {
     this.rpc = rpc;
     this.leaderElection = leaderElection;
     this.snapshot = snapshot;
@@ -60,6 +62,7 @@ public class RatisConfig {
     this.client = client;
     this.impl = impl;
     this.leaderLogAppender = leaderLogAppender;
+    this.read = read;
   }
 
   public Rpc getRpc() {
@@ -98,6 +101,10 @@ public class RatisConfig {
     return leaderLogAppender;
   }
 
+  public Read getRead() {
+    return read;
+  }
+
   public static Builder newBuilder() {
     return new Builder();
   }
@@ -114,6 +121,7 @@ public class RatisConfig {
     private Client client;
     private Impl impl;
     private LeaderLogAppender leaderLogAppender;
+    private Read read;
 
     public RatisConfig build() {
       return new RatisConfig(
@@ -126,7 +134,8 @@ public class RatisConfig {
           Optional.ofNullable(client).orElseGet(() -> Client.newBuilder().build()),
           Optional.ofNullable(impl).orElseGet(() -> Impl.newBuilder().build()),
           Optional.ofNullable(leaderLogAppender)
-              .orElseGet(() -> LeaderLogAppender.newBuilder().build()));
+              .orElseGet(() -> LeaderLogAppender.newBuilder().build()),
+          Optional.ofNullable(read).orElseGet(() -> Read.newBuilder().build()));
     }
 
     public Builder setRpc(Rpc rpc) {
@@ -173,6 +182,11 @@ public class RatisConfig {
       this.leaderLogAppender = leaderLogAppender;
       return this;
     }
+
+    public Builder setRead(Read read) {
+      this.read = read;
+      return this;
+    }
   }
 
   /** server rpc timeout related. */
@@ -1044,4 +1058,50 @@ public class RatisConfig {
       }
     }
   }
+
+  public static class Read {
+    public enum Option {
+      DEFAULT,
+      LINEARIZABLE
+    }
+
+    private final Read.Option readOption;
+    private final TimeDuration readTimeout;
+
+    private Read(Read.Option readOption, TimeDuration readTimeout) {
+      this.readOption = readOption;
+      this.readTimeout = readTimeout;
+    }
+
+    public Option getReadOption() {
+      return readOption;
+    }
+
+    public TimeDuration getReadTimeout() {
+      return readTimeout;
+    }
+
+    public static Read.Builder newBuilder() {
+      return new Read.Builder();
+    }
+
+    public static class Builder {
+      private Read.Option readOption = Option.LINEARIZABLE;
+      private TimeDuration readTimeout = TimeDuration.valueOf(10, TimeUnit.SECONDS);
+
+      public Read.Builder setReadOption(Read.Option readOption) {
+        this.readOption = readOption;
+        return this;
+      }
+
+      public Read.Builder setReadTimeout(TimeDuration timeout) {
+        this.readTimeout = timeout;
+        return this;
+      }
+
+      public Read build() {
+        return new Read(readOption, readTimeout);
+      }
+    }
+  }
 }
diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/exception/RatisUnderRecoveryException.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/exception/RatisUnderRecoveryException.java
new file mode 100644
index 00000000000..762b7ea432c
--- /dev/null
+++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/exception/RatisUnderRecoveryException.java
@@ -0,0 +1,31 @@
+/*
+ * 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.exception;
+
+/** RaftServer is redoing RaftLog. Unable to serve linearizable read requests. */
+public class RatisUnderRecoveryException extends ConsensusException {
+
+  public RatisUnderRecoveryException(Throwable cause) {
+    super(
+        "Ratis Server is redoing Raft Log and cannot serve read requests now. Please try read later: "
+            + cause,
+        cause);
+  }
+}
diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
index 0fcd2fcb0e6..f8a4b498353 100644
--- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
+++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/RatisConsensus.java
@@ -50,6 +50,7 @@ import org.apache.iotdb.consensus.exception.NodeReadOnlyException;
 import org.apache.iotdb.consensus.exception.PeerAlreadyInConsensusGroupException;
 import org.apache.iotdb.consensus.exception.PeerNotInConsensusGroupException;
 import org.apache.iotdb.consensus.exception.RatisRequestFailedException;
+import org.apache.iotdb.consensus.exception.RatisUnderRecoveryException;
 import org.apache.iotdb.consensus.ratis.metrics.RatisMetricSet;
 import org.apache.iotdb.consensus.ratis.metrics.RatisMetricsManager;
 import org.apache.iotdb.consensus.ratis.utils.RatisLogMonitor;
@@ -92,6 +93,7 @@ import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.stream.Collectors;
 
@@ -132,6 +134,9 @@ class RatisConsensus implements IConsensus {
   private final RatisMetricSet ratisMetricSet;
   private final TConsensusGroupType consensusGroupType;
 
+  private final ConcurrentHashMap<ConsensusGroupId, AtomicBoolean> canServeStaleRead =
+      new ConcurrentHashMap<>();
+
   public RatisConsensus(ConsensusConfig config, IStateMachine.Registry registry)
       throws IOException {
     myself =
@@ -326,18 +331,24 @@ class RatisConsensus implements IConsensus {
       return failedRead(new ConsensusGroupNotExistException(consensusGroupId));
     }
 
+    final boolean isLinearizableRead =
+        !canServeStaleRead.computeIfAbsent(consensusGroupId, id -> new AtomicBoolean(false)).get();
+
     RaftClientReply reply;
-    try (AutoCloseable ignored =
-        RatisMetricsManager.getInstance().startReadTimer(consensusGroupType)) {
-      RequestMessage message = new RequestMessage(IConsensusRequest);
-      RaftClientRequest clientRequest =
-          buildRawRequest(groupId, message, RaftClientRequest.staleReadRequestType(-1));
-      reply = server.submitClientRequest(clientRequest);
-      if (!reply.isSuccess()) {
-        return failedRead(new RatisRequestFailedException(reply.getException()));
+    try {
+      reply = doRead(groupId, IConsensusRequest, isLinearizableRead);
+      // allow stale read if current linearizable read returns successfully
+      if (isLinearizableRead) {
+        canServeStaleRead.get(consensusGroupId).set(true);
       }
     } catch (Exception e) {
-      return failedRead(new RatisRequestFailedException(e));
+      if (isLinearizableRead) {
+        // linearizable read failed. the RaftServer is recovering from Raft Log and cannot serve
+        // read requests.
+        return failedRead(new RatisUnderRecoveryException(e));
+      } else {
+        return failedRead(new RatisRequestFailedException(e));
+      }
     }
 
     Message ret = reply.getMessage();
@@ -346,6 +357,30 @@ class RatisConsensus implements IConsensus {
     return ConsensusReadResponse.newBuilder().setDataSet(dataSet).build();
   }
 
+  /** return a success raft client reply or throw an Exception */
+  private RaftClientReply doRead(
+      RaftGroupId gid, IConsensusRequest readRequest, boolean linearizable) throws Exception {
+    final RaftClientRequest.Type readType =
+        linearizable
+            ? RaftClientRequest.readRequestType()
+            : RaftClientRequest.staleReadRequestType(-1);
+    final RequestMessage requestMessage = new RequestMessage(readRequest);
+    final RaftClientRequest request = buildRawRequest(gid, requestMessage, readType);
+
+    RaftClientReply reply;
+    try (AutoCloseable ignored =
+        RatisMetricsManager.getInstance().startReadTimer(consensusGroupType)) {
+      reply = server.submitClientRequest(request);
+    }
+
+    // rethrow the exception if the reply is not successful
+    if (!reply.isSuccess()) {
+      throw reply.getException();
+    }
+
+    return reply;
+  }
+
   /**
    * Add this IConsensus Peer into ConsensusGroup(groupId, peers) Caller's responsibility to call
    * addConsensusGroup to every peer of this group and ensure the group is all up
@@ -804,6 +839,11 @@ class RatisConsensus implements IConsensus {
     return server;
   }
 
+  @TestOnly
+  public void allowStaleRead(ConsensusGroupId consensusGroupId) {
+    canServeStaleRead.computeIfAbsent(consensusGroupId, id -> new AtomicBoolean(false)).set(true);
+  }
+
   private class RatisClientPoolFactory implements IClientPoolFactory<RaftGroup, RatisClient> {
 
     @Override
diff --git a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
index d274232bece..14400b7d145 100644
--- a/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
+++ b/iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/ratis/utils/Utils.java
@@ -282,5 +282,12 @@ public class Utils {
         properties, config.getRpc().getFirstElectionTimeoutMin());
     RaftServerConfigKeys.Rpc.setFirstElectionTimeoutMax(
         properties, config.getRpc().getFirstElectionTimeoutMax());
+
+    RaftServerConfigKeys.Read.Option option =
+        config.getRead().getReadOption() == RatisConfig.Read.Option.DEFAULT
+            ? RaftServerConfigKeys.Read.Option.DEFAULT
+            : RaftServerConfigKeys.Read.Option.LINEARIZABLE;
+    RaftServerConfigKeys.Read.setOption(properties, option);
+    RaftServerConfigKeys.Read.setTimeout(properties, config.getRead().getReadTimeout());
   }
 }
diff --git a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
index 0a1fc20bf81..245474c10e5 100644
--- a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
+++ b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RatisConsensusTest.java
@@ -170,6 +170,7 @@ public class RatisConsensusTest {
     // 200 operation will trigger snapshot & purge
     doConsensus(servers.get(0), group.getGroupId(), 200, 200);
 
+    miniCluster.stop();
     miniCluster.restart();
 
     doConsensus(servers.get(0), gid, 10, 210);
diff --git a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RecoverReadTest.java b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RecoverReadTest.java
new file mode 100644
index 00000000000..c1ea40c5a51
--- /dev/null
+++ b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/RecoverReadTest.java
@@ -0,0 +1,238 @@
+/*
+ * 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.ratis;
+
+import org.apache.iotdb.common.rpc.thrift.TSStatus;
+import org.apache.iotdb.commons.consensus.ConsensusGroupId;
+import org.apache.iotdb.consensus.common.Peer;
+import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
+import org.apache.iotdb.consensus.config.RatisConfig;
+import org.apache.iotdb.consensus.exception.RatisUnderRecoveryException;
+
+import org.apache.ratis.util.TimeDuration;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+public class RecoverReadTest {
+  private static final Logger logger = LoggerFactory.getLogger(RecoverReadTest.class);
+  private static final TimeDuration stallDuration =
+      TimeDuration.valueOf(500, TimeUnit.MILLISECONDS);
+
+  private static class SlowRecoverStateMachine extends TestUtils.IntegerCounter {
+    private final TimeDuration stallDuration;
+    private final AtomicBoolean stallApply = new AtomicBoolean(false);
+
+    private SlowRecoverStateMachine(TimeDuration stallDuration) {
+      this.stallDuration = stallDuration;
+    }
+
+    private SlowRecoverStateMachine(TimeDuration stallDuration, boolean isStall) {
+      this.stallDuration = stallDuration;
+      this.stallApply.set(isStall);
+    }
+
+    @Override
+    public TSStatus write(IConsensusRequest request) {
+      if (stallApply.get()) {
+        try {
+          stallDuration.sleep();
+          logger.info("Apply i={} when recovering", integer.get());
+        } catch (InterruptedException e) {
+          logger.warn("Interrupted when stalling for write operations", e);
+          Thread.currentThread().interrupt();
+        }
+      }
+      return super.write(request);
+    }
+
+    @Override
+    public boolean takeSnapshot(File snapshotDir) {
+      // allow no snapshot to ensure the raft log be replayed
+      return false;
+    }
+
+    void setStall() {
+      stallApply.set(true);
+    }
+  }
+
+  private TestUtils.MiniCluster miniCluster;
+
+  @Before
+  public void setUp() throws Exception {
+    logger.info("[RECOVER TEST] start setting up the test env");
+    final TestUtils.MiniClusterFactory factory = new TestUtils.MiniClusterFactory();
+    miniCluster =
+        factory
+            .setSMProvider(() -> new SlowRecoverStateMachine(stallDuration))
+            .setRatisConfig(
+                RatisConfig.newBuilder()
+                    .setLog(
+                        RatisConfig.Log.newBuilder()
+                            .setPurgeUptoSnapshotIndex(false)
+                            .setPreserveNumsWhenPurge(1024)
+                            .build())
+                    .setRead(
+                        RatisConfig.Read.newBuilder()
+                            .setReadTimeout(TimeDuration.valueOf(20, TimeUnit.SECONDS))
+                            .build())
+                    .setRpc(
+                        RatisConfig.Rpc.newBuilder()
+                            .setFirstElectionTimeoutMin(TimeDuration.valueOf(1, TimeUnit.SECONDS))
+                            .setFirstElectionTimeoutMax(TimeDuration.valueOf(2, TimeUnit.SECONDS))
+                            .setRequestTimeout(TimeDuration.valueOf(20, TimeUnit.SECONDS))
+                            .build())
+                    .build())
+            .create();
+    miniCluster.start();
+    logger.info("[RECOVER TEST] end setting up the test env");
+  }
+
+  @After
+  public void tearUp() throws Exception {
+    logger.info("[RECOVER TEST] start tearing down the test env");
+    miniCluster.cleanUp();
+    logger.info("[RECOVER TEST] end tearing down the test env");
+  }
+
+  /* mimics the situation before this patch */
+  @Test
+  public void inconsistentReadAfterRestart() throws Exception {
+    final ConsensusGroupId gid = miniCluster.getGid();
+    final List<Peer> members = miniCluster.getPeers();
+
+    miniCluster.getServers().forEach(s -> s.createPeer(gid, members));
+
+    // first write 10 ops
+    TestUtils.write(miniCluster.getServer(0), gid, 10);
+    Assert.assertEquals(10, TestUtils.read(miniCluster.getServer(0), gid));
+
+    // stop the cluster
+    miniCluster.stop();
+
+    // set stall when restart
+    miniCluster.resetSMProviderBeforeRestart(
+        () -> new SlowRecoverStateMachine(stallDuration, true));
+
+    // restart the cluster
+    miniCluster.restart();
+
+    // manually set the canServe flag to true to mimic original implementation
+    miniCluster.getServer(0).allowStaleRead(gid);
+
+    Assert.assertNotEquals(10, TestUtils.read(miniCluster.getServer(0), gid));
+  }
+
+  @Test
+  public void consistentRead() throws Exception {
+    final ConsensusGroupId gid = miniCluster.getGid();
+    final List<Peer> members = miniCluster.getPeers();
+
+    miniCluster.getServers().forEach(s -> s.createPeer(gid, members));
+
+    // first write 10 ops
+    TestUtils.write(miniCluster.getServer(0), gid, 10);
+    Assert.assertEquals(10, TestUtils.read(miniCluster.getServer(0), gid));
+
+    // stop the cluster
+    miniCluster.stop();
+
+    // set stall when restart
+    miniCluster.resetSMProviderBeforeRestart(
+        () -> new SlowRecoverStateMachine(stallDuration, true));
+
+    // restart the cluster
+    miniCluster.restart();
+
+    // wait an active leader to serve linearizable read requests
+    miniCluster.waitUntilActiveLeader();
+
+    ConsensusReadResponse resp = TestUtils.doRead(miniCluster.getServer(0), gid);
+    while (!resp.isSuccess()) {
+      resp = TestUtils.doRead(miniCluster.getServer(0), gid);
+    }
+
+    Assert.assertEquals(10, ((TestUtils.TestDataSet) resp.getDataset()).getNumber());
+  }
+
+  @Test
+  public void consistentReadFailedWithNoLeader() throws Exception {
+    final ConsensusGroupId gid = miniCluster.getGid();
+    final List<Peer> members = miniCluster.getPeers();
+
+    miniCluster.getServers().forEach(s -> s.createPeer(gid, members));
+
+    // first write 10 ops
+    TestUtils.write(miniCluster.getServer(0), gid, 10);
+    Assert.assertEquals(10, TestUtils.read(miniCluster.getServer(0), gid));
+
+    // stop the cluster
+    miniCluster.stop();
+
+    // set stall when restart
+    miniCluster.resetSMProviderBeforeRestart(
+        () -> new SlowRecoverStateMachine(stallDuration, true));
+
+    // restart the cluster
+    miniCluster.restart();
+
+    // query during redo: get exception that ratis is under recovery
+    final ConsensusReadResponse readResponse = TestUtils.doRead(miniCluster.getServer(0), gid);
+    Assert.assertTrue(readResponse.getException() instanceof RatisUnderRecoveryException);
+  }
+
+  @Test
+  public void consistentReadTimeout() throws Exception {
+    final ConsensusGroupId gid = miniCluster.getGid();
+    final List<Peer> members = miniCluster.getPeers();
+
+    miniCluster.getServers().forEach(s -> s.createPeer(gid, members));
+
+    // first write 30 ops
+    TestUtils.write(miniCluster.getServer(0), gid, 50);
+    Assert.assertEquals(50, TestUtils.read(miniCluster.getServer(0), gid));
+
+    // stop the cluster
+    miniCluster.stop();
+
+    // set stall when restart
+    miniCluster.resetSMProviderBeforeRestart(
+        () -> new SlowRecoverStateMachine(stallDuration, true));
+
+    // restart the cluster
+    miniCluster.restart();
+
+    // wait until active leader to serve read index requests
+    miniCluster.waitUntilActiveLeader();
+
+    // query during redo: get exception that ratis is under recovery
+    final ConsensusReadResponse readResponse = TestUtils.doRead(miniCluster.getServer(0), gid);
+    Assert.assertTrue(readResponse.getException() instanceof RatisUnderRecoveryException);
+  }
+}
diff --git a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
index 72de6665948..3e7325b5844 100644
--- a/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
+++ b/iotdb-core/consensus/src/test/java/org/apache/iotdb/consensus/ratis/TestUtils.java
@@ -26,17 +26,24 @@ import org.apache.iotdb.commons.consensus.ConsensusGroupId;
 import org.apache.iotdb.commons.consensus.DataRegionId;
 import org.apache.iotdb.commons.utils.TestOnly;
 import org.apache.iotdb.consensus.ConsensusFactory;
+import org.apache.iotdb.consensus.IConsensus;
 import org.apache.iotdb.consensus.IStateMachine;
 import org.apache.iotdb.consensus.common.ConsensusGroup;
 import org.apache.iotdb.consensus.common.DataSet;
 import org.apache.iotdb.consensus.common.Peer;
 import org.apache.iotdb.consensus.common.request.ByteBufferConsensusRequest;
 import org.apache.iotdb.consensus.common.request.IConsensusRequest;
+import org.apache.iotdb.consensus.common.response.ConsensusReadResponse;
+import org.apache.iotdb.consensus.common.response.ConsensusWriteResponse;
 import org.apache.iotdb.consensus.config.ConsensusConfig;
 import org.apache.iotdb.consensus.config.RatisConfig;
+import org.apache.iotdb.consensus.exception.ConsensusException;
 
 import org.apache.ratis.thirdparty.com.google.common.base.Preconditions;
 import org.apache.ratis.util.FileUtils;
+import org.apache.ratis.util.JavaUtils;
+import org.apache.ratis.util.TimeDuration;
+import org.junit.Assert;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,11 +56,16 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Scanner;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Function;
 import java.util.function.Supplier;
 
 public class TestUtils {
+  private static final Logger logger = LoggerFactory.getLogger(TestUtils.class);
+
   public static class TestDataSet implements DataSet {
     private int number;
 
@@ -100,10 +112,8 @@ public class TestUtils {
   }
 
   public static class IntegerCounter implements IStateMachine, IStateMachine.EventApi {
-    private AtomicInteger integer;
+    protected AtomicInteger integer;
     private final Logger logger = LoggerFactory.getLogger(IntegerCounter.class);
-    private TEndPoint leaderEndpoint;
-    private int leaderId;
     private List<Peer> configuration;
 
     @Override
@@ -165,7 +175,6 @@ public class TestUtils {
 
     @Override
     public void notifyLeaderChanged(ConsensusGroupId groupId, int newLeaderId) {
-      this.leaderId = newLeaderId;
       System.out.println("---------newLeader-----------");
       System.out.println(groupId);
       System.out.println(newLeaderId);
@@ -184,6 +193,10 @@ public class TestUtils {
       System.out.println("----------------------");
     }
 
+    public void reset() {
+      this.integer.set(0);
+    }
+
     @TestOnly
     public static synchronized String ensureSnapshotFileName(File snapshotDir, String metadata) {
       File dir = new File(snapshotDir + File.separator + metadata);
@@ -193,10 +206,6 @@ public class TestUtils {
       return dir.getPath() + File.separator + "snapshot";
     }
 
-    public TEndPoint getLeaderEndpoint() {
-      return leaderEndpoint;
-    }
-
     public List<Peer> getConfiguration() {
       return configuration;
     }
@@ -212,6 +221,8 @@ public class TestUtils {
     private final RatisConfig config;
     private final List<RatisConsensus> servers;
     private final ConsensusGroup group;
+    private Supplier<IStateMachine> smProvider;
+    private final AtomicBoolean isStopped = new AtomicBoolean(false);
 
     private MiniCluster(
         ConsensusGroupId gid,
@@ -222,6 +233,7 @@ public class TestUtils {
       this.gid = gid;
       this.replicas = replicas;
       this.config = config;
+      this.smProvider = smProvider;
       Preconditions.checkArgument(
           replicas % 2 == 1, "Test Env Raft Group should consists singular peers");
 
@@ -272,12 +284,14 @@ public class TestUtils {
       for (RatisConsensus server : servers) {
         server.start();
       }
+      isStopped.set(false);
     }
 
     void stop() throws IOException {
       for (RatisConsensus server : servers) {
         server.stop();
       }
+      isStopped.set(true);
     }
 
     void cleanUp() throws IOException {
@@ -285,13 +299,20 @@ public class TestUtils {
       for (File storage : peerStorage) {
         FileUtils.deleteFully(storage);
       }
+      stateMachines.clear();
     }
 
     void restart() throws IOException {
-      stop();
+      logger.info("start restarting the mini cluster");
+      isStopped.set(false);
       servers.clear();
+      stateMachines.clear();
+      for (int i = 0; i < replicas; i++) {
+        stateMachines.add(smProvider.get());
+      }
       makeServers();
       start();
+      logger.info("end restarting the mini cluster");
     }
 
     List<RatisConsensus> getServers() {
@@ -317,13 +338,30 @@ public class TestUtils {
     ConsensusGroup getGroup() {
       return group;
     }
+
+    void waitUntilActiveLeader() throws InterruptedException {
+      JavaUtils.attemptUntilTrue(
+          () -> getServer(0).getLeader(gid) != null,
+          100,
+          TimeDuration.valueOf(100, TimeUnit.MILLISECONDS),
+          "wait leader",
+          null);
+    }
+
+    void resetSMProviderBeforeRestart(Supplier<IStateMachine> smProvider) {
+      Preconditions.checkArgument(
+          isStopped.get(), "call resetSMProviderBeforeRestart() before restart");
+      this.smProvider = smProvider;
+    }
   }
 
   static class MiniClusterFactory {
     private int replicas = 3;
     private ConsensusGroupId gid = new DataRegionId(1);
     private Function<Integer, File> peerStorageProvider =
-        peerId -> new File("target" + java.io.File.separator + peerId);
+        peerId ->
+            new File(
+                "target" + java.io.File.separator + UUID.randomUUID() + File.separator + peerId);
 
     private Supplier<IStateMachine> smProvider = TestUtils.IntegerCounter::new;
     private RatisConfig ratisConfig;
@@ -333,8 +371,35 @@ public class TestUtils {
       return this;
     }
 
+    MiniClusterFactory setSMProvider(Supplier<IStateMachine> smProvider) {
+      this.smProvider = smProvider;
+      return this;
+    }
+
     MiniCluster create() {
       return new MiniCluster(gid, replicas, peerStorageProvider, smProvider, ratisConfig);
     }
   }
+
+  static void write(IConsensus consensus, ConsensusGroupId gid, int count) {
+    for (int i = 0; i < count; i++) {
+      final ByteBufferConsensusRequest increment = TestRequest.incrRequest();
+      final ConsensusWriteResponse response = consensus.write(gid, increment);
+      Assert.assertEquals(200, response.getStatus().getCode());
+    }
+  }
+
+  static int read(IConsensus consensus, ConsensusGroupId gid) throws ConsensusException {
+    final ConsensusReadResponse response = doRead(consensus, gid);
+    if (!response.isSuccess()) {
+      throw response.getException();
+    }
+    final TestUtils.TestDataSet result = (TestUtils.TestDataSet) response.getDataset();
+    return result.getNumber();
+  }
+
+  static ConsensusReadResponse doRead(IConsensus consensus, ConsensusGroupId gid) {
+    final ByteBufferConsensusRequest getReq = TestUtils.TestRequest.getRequest();
+    return consensus.read(gid, getReq);
+  }
 }