You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ratis.apache.org by wi...@apache.org on 2023/08/28 08:55:20 UTC

[ratis] branch snapshot-branch2 updated (d8814a395 -> 1aeb69d60)

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

williamsong pushed a change to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git


 discard d8814a395 upgrade snapshot version
     new 60d520146 RATIS-1858. Follower keeps logging first election timeout. (#894)
     new 1d07f9faf RATIS-1861. NullPointerException in readAsync when Ratis leader is changing (#895)
     new ee5bce0b7 RATIS-1862 Add the parameter whether to take Snapshot when stopping to adapt to different services (#896)
     new 3165c25e5 RATIS-1867. To uniformly manage the timeout parameters for detecting gc. (#899)
     new 31d281d10 RATIS-1870. Refactor hasMajority code during configuration changes. (#902)
     new 209bbe232 RATIS-1873. Remove RetryCache assertion that doesn't hold (#904)
     new 4b7305ac8 RATIS-1872. HeartbeatAck use in-correct callId as minCallId. (#905)
     new efeeca0e5 RATIS-1874. Add notifyLeaderReady function in IStateMachine (#906)
     new 8efe8a110 RATIS-1877. In JvmPauseMonitor, sleepTime should not be larger than sleepDeviationThreshold (#907)
     new 1aeb69d60 upgrade snapshot version

This update added new revisions after undoing existing revisions.
That is to say, some revisions that were in the old version of the
branch are not in the new version.  This situation occurs
when a user --force pushes a change and generates a repository
containing something like this:

 * -- * -- B -- O -- O -- O   (d8814a395)
            \
             N -- N -- N   refs/heads/snapshot-branch2 (1aeb69d60)

You should already have received notification emails for all of the O
revisions, and so the following emails describe only the N revisions
from the common base, B.

Any revisions marked "omit" are not gone; other references still
refer to them.  Any revisions marked "discard" are gone forever.

The 10 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 pom.xml                                            |  4 +-
 ratis-assembly/pom.xml                             |  2 +-
 ratis-client/pom.xml                               |  2 +-
 ratis-common/pom.xml                               |  2 +-
 .../org/apache/ratis/util/JvmPauseMonitor.java     | 61 +++++++++++++++++++---
 .../java/org/apache/ratis/util/TimeDuration.java   |  9 ++++
 ratis-docs/pom.xml                                 |  2 +-
 ratis-examples/pom.xml                             |  2 +-
 ratis-experiments/pom.xml                          |  2 +-
 ratis-grpc/pom.xml                                 |  2 +-
 ratis-metrics/pom.xml                              |  2 +-
 ratis-netty/pom.xml                                |  2 +-
 ratis-proto/pom.xml                                |  2 +-
 ratis-replicated-map/pom.xml                       |  2 +-
 ratis-resource-bundle/pom.xml                      |  2 +-
 ratis-server-api/pom.xml                           |  2 +-
 .../apache/ratis/server/RaftServerConfigKeys.java  | 12 +++++
 .../apache/ratis/statemachine/StateMachine.java    |  5 ++
 ratis-server/pom.xml                               |  2 +-
 .../apache/ratis/server/impl/LeaderStateImpl.java  | 52 +++++-------------
 .../ratis/server/impl/PeerConfiguration.java       | 16 ++++--
 .../ratis/server/impl/RaftConfigurationImpl.java   | 20 +++++++
 .../apache/ratis/server/impl/RaftServerImpl.java   | 18 +++++--
 .../apache/ratis/server/impl/RaftServerProxy.java  |  9 ++--
 .../ratis/server/impl/ReadIndexHeartbeats.java     |  9 ++--
 .../org/apache/ratis/server/impl/RoleInfo.java     |  5 +-
 .../org/apache/ratis/server/impl/ServerState.java  | 16 +++---
 .../ratis/server/impl/StateMachineUpdater.java     |  5 +-
 ratis-shell/pom.xml                                |  2 +-
 ratis-test/pom.xml                                 |  2 +-
 ratis-tools/pom.xml                                |  2 +-
 31 files changed, 180 insertions(+), 95 deletions(-)


[ratis] 02/10: RATIS-1861. NullPointerException in readAsync when Ratis leader is changing (#895)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 1d07f9faf947e99e0680834541f5aa2731b806e0
Author: Xiangpeng Hu <65...@users.noreply.github.com>
AuthorDate: Fri Jul 28 22:42:10 2023 +0800

    RATIS-1861. NullPointerException in readAsync when Ratis leader is changing (#895)
---
 .../src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java   | 3 ++-
 .../src/main/java/org/apache/ratis/server/impl/RoleInfo.java         | 5 ++---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
index 8f8c0a982..341890588 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
@@ -569,10 +569,11 @@ class RaftServerImpl implements RaftServer.Division,
     Preconditions.assertTrue(getInfo().isCandidate());
     role.shutdownLeaderElection();
     setRole(RaftPeerRole.LEADER, "changeToLeader");
+    final LeaderStateImpl leader = role.updateLeaderState(this);
     state.becomeLeader();
 
     // start sending AppendEntries RPC to followers
-    final LogEntryProto e = role.startLeaderState(this);
+    final LogEntryProto e = leader.start();
     getState().setRaftConf(e);
   }
 
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RoleInfo.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RoleInfo.java
index d09c8017b..603ba1326 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RoleInfo.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RoleInfo.java
@@ -18,7 +18,6 @@
 
 package org.apache.ratis.server.impl;
 
-import org.apache.ratis.proto.RaftProtos.LogEntryProto;
 import org.apache.ratis.proto.RaftProtos.RaftPeerRole;
 import org.apache.ratis.protocol.RaftPeerId;
 import org.apache.ratis.util.Preconditions;
@@ -79,8 +78,8 @@ class RoleInfo {
     return Objects.requireNonNull(leaderState.get(), "leaderState is null");
   }
 
-  LogEntryProto startLeaderState(RaftServerImpl server) {
-    return updateAndGet(leaderState, new LeaderStateImpl(server)).start();
+  LeaderStateImpl updateLeaderState(RaftServerImpl server) {
+    return updateAndGet(leaderState, new LeaderStateImpl(server));
   }
 
   void shutdownLeaderState(boolean allowNull) {


[ratis] 04/10: RATIS-1867. To uniformly manage the timeout parameters for detecting gc. (#899)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 3165c25e54dd03445b8709ba0feab2cfd07e3d72
Author: Potato <ta...@apache.org>
AuthorDate: Mon Aug 7 22:33:49 2023 +0800

    RATIS-1867. To uniformly manage the timeout parameters for detecting gc. (#899)
---
 .../src/main/java/org/apache/ratis/util/JvmPauseMonitor.java      | 8 +++++---
 .../main/java/org/apache/ratis/server/impl/RaftServerProxy.java   | 3 ++-
 2 files changed, 7 insertions(+), 4 deletions(-)

diff --git a/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java b/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
index 532bd2255..fac3d0ede 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
@@ -88,14 +88,16 @@ public class JvmPauseMonitor {
   }
 
   private static final TimeDuration SLEEP_TIME = TimeDuration.valueOf(500, TimeUnit.MILLISECONDS);
-  private static final TimeDuration WARN_THRESHOLD = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS);
+  private final TimeDuration sleepDeviationThreshold;
 
   private final String name;
   private final AtomicReference<Thread> threadRef = new AtomicReference<>();
   private final CheckedConsumer<TimeDuration, IOException> handler;
 
-  public JvmPauseMonitor(Object name, CheckedConsumer<TimeDuration, IOException> handler) {
+  public JvmPauseMonitor(Object name, TimeDuration sleepDeviationThreshold,
+      CheckedConsumer<TimeDuration, IOException> handler) {
     this.name = JavaUtils.getClassSimpleName(getClass()) + "-" + name;
+    this.sleepDeviationThreshold = sleepDeviationThreshold;
     this.handler = handler;
   }
 
@@ -119,7 +121,7 @@ public class JvmPauseMonitor {
       return;
     }
 
-    if (extraSleep.compareTo(WARN_THRESHOLD) > 0) {
+    if (extraSleep.compareTo(sleepDeviationThreshold) > 0) {
       final Map<String, GcInfo> after = getGcTimes();
       LOG.warn("{}: {}", this, toString(before, extraSleep, after));
     }
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
index 528790981..bceeb44a1 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
@@ -218,9 +218,10 @@ class RaftServerProxy implements RaftServer {
         RaftServerConfigKeys.ThreadPool.proxySize(properties),
         id + "-impl");
 
+    final TimeDuration sleepDeviationThreshold = RaftServerConfigKeys.sleepDeviationThreshold(properties);
     final TimeDuration rpcSlownessTimeout = RaftServerConfigKeys.Rpc.slownessTimeout(properties);
     final TimeDuration leaderStepDownWaitTime = RaftServerConfigKeys.LeaderElection.leaderStepDownWaitTime(properties);
-    this.pauseMonitor = new JvmPauseMonitor(id,
+    this.pauseMonitor = new JvmPauseMonitor(id, sleepDeviationThreshold,
         extraSleep -> handleJvmPause(extraSleep, rpcSlownessTimeout, leaderStepDownWaitTime));
     this.threadGroup = threadGroup == null ? new ThreadGroup(this.id.toString()) : threadGroup;
   }


[ratis] 08/10: RATIS-1874. Add notifyLeaderReady function in IStateMachine (#906)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit efeeca0e5f12993a09feb9966e9e983d57552d06
Author: Potato <ta...@apache.org>
AuthorDate: Fri Aug 25 15:11:44 2023 +0800

    RATIS-1874. Add notifyLeaderReady function in IStateMachine (#906)
---
 .../main/java/org/apache/ratis/statemachine/StateMachine.java  |  5 +++++
 .../java/org/apache/ratis/server/impl/LeaderStateImpl.java     | 10 +++++++++-
 .../main/java/org/apache/ratis/server/impl/RaftServerImpl.java |  1 +
 3 files changed, 15 insertions(+), 1 deletion(-)

diff --git a/ratis-server-api/src/main/java/org/apache/ratis/statemachine/StateMachine.java b/ratis-server-api/src/main/java/org/apache/ratis/statemachine/StateMachine.java
index e21411ec7..90813f325 100644
--- a/ratis-server-api/src/main/java/org/apache/ratis/statemachine/StateMachine.java
+++ b/ratis-server-api/src/main/java/org/apache/ratis/statemachine/StateMachine.java
@@ -228,6 +228,11 @@ public interface StateMachine extends Closeable {
      * Notify {@link StateMachine} that this server is no longer the leader.
      */
     default void notifyNotLeader(Collection<TransactionContext> pendingEntries) throws IOException {}
+
+    /**
+     * Notify the {@link StateMachine} that this server becomes ready after changed to leader.
+     */
+    default void notifyLeaderReady() {}
   }
 
   /**
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
index adf035e4f..6d57e68aa 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
@@ -315,6 +315,7 @@ class LeaderStateImpl implements LeaderState {
 
   private final int stagingCatchupGap;
   private final long placeHolderIndex;
+  private final AtomicBoolean isReady = new AtomicBoolean();
   private final RaftServerMetricsImpl raftServerMetrics;
   private final LogAppenderMetrics logAppenderMetrics;
   private final long followerMaxGapThreshold;
@@ -382,7 +383,14 @@ class LeaderStateImpl implements LeaderState {
   }
 
   boolean isReady() {
-    return server.getState().getLastAppliedIndex() >= placeHolderIndex;
+    return isReady.get();
+  }
+
+  void checkReady(LogEntryProto entry) {
+    if (entry.getTerm() == currentTerm && entry.getIndex() == placeHolderIndex) {
+      isReady.set(true);
+      server.getStateMachine().leaderEvent().notifyLeaderReady();
+    }
   }
 
   void stop() {
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
index 3eaf2dc6c..9f3f7982d 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
@@ -1767,6 +1767,7 @@ class RaftServerImpl implements RaftServer.Division,
       // the new conf in the metadata file and notify the StateMachine.
       state.writeRaftConfiguration(next);
       stateMachine.event().notifyConfigurationChanged(next.getTerm(), next.getIndex(), next.getConfigurationEntry());
+      role.getLeaderState().ifPresent(leader -> leader.checkReady(next));
     } else if (next.hasStateMachineLogEntry()) {
       // check whether there is a TransactionContext because we are the leader.
       TransactionContext trx = role.getLeaderState()


[ratis] 05/10: RATIS-1870. Refactor hasMajority code during configuration changes. (#902)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 31d281d1071d0ac9ee58844adfb72796c366662a
Author: William Song <48...@users.noreply.github.com>
AuthorDate: Tue Aug 15 02:15:39 2023 +0800

    RATIS-1870. Refactor hasMajority code during configuration changes. (#902)
---
 .../apache/ratis/server/impl/LeaderStateImpl.java  | 33 ++--------------------
 .../ratis/server/impl/PeerConfiguration.java       | 16 +++++++----
 .../ratis/server/impl/RaftConfigurationImpl.java   | 20 +++++++++++++
 3 files changed, 33 insertions(+), 36 deletions(-)

diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
index 7ea4d738d..5dfbc009b 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
@@ -875,36 +875,7 @@ class LeaderStateImpl implements LeaderState {
 
   private boolean hasMajority(Predicate<RaftPeerId> isAcked) {
     final RaftPeerId selfId = server.getId();
-    final RaftConfigurationImpl conf = server.getRaftConf();
-
-    final CurrentOldFollowerInfos infos = followerInfoMap.getFollowerInfos(conf);
-    final List<FollowerInfo> followers = infos.getCurrent();
-    final boolean includeSelf = conf.containsInConf(selfId);
-    final boolean newConf = hasMajority(isAcked, followers, includeSelf);
-
-    if (!conf.isTransitional()) {
-      return newConf;
-    } else {
-      final List<FollowerInfo> oldFollowers = infos.getOld();
-      final boolean includeSelfInOldConf = conf.containsInOldConf(selfId);
-      final boolean oldConf = hasMajority(isAcked, oldFollowers, includeSelfInOldConf);
-      return newConf && oldConf;
-    }
-  }
-
-  private boolean hasMajority(Predicate<RaftPeerId> isAcked, List<FollowerInfo> followers, boolean includeSelf) {
-    if (followers.isEmpty() && !includeSelf) {
-      return true;
-    }
-
-    int count = includeSelf ? 1 : 0;
-    for (FollowerInfo follower: followers) {
-      if (isAcked.test(follower.getId())) {
-        count++;
-      }
-    }
-    final int size = includeSelf ? followers.size() + 1 : followers.size();
-    return count > size / 2;
+    return server.getRaftConf().hasMajority(isAcked, selfId);
   }
 
   private void updateCommit(LogEntryHeader[] entriesToCommit) {
@@ -1094,7 +1065,7 @@ class LeaderStateImpl implements LeaderState {
     final long readIndex = server.getRaftLog().getLastCommittedIndex();
 
     // if group contains only one member, fast path
-    if (server.getRaftConf().getCurrentPeers().size() == 1) {
+    if (server.getRaftConf().isSingleton()) {
       return CompletableFuture.completedFuture(readIndex);
     }
 
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
index 38e3602e8..600667c38 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
@@ -31,6 +31,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Optional;
+import java.util.function.Predicate;
 import java.util.stream.Stream;
 
 /**
@@ -150,12 +151,17 @@ class PeerConfiguration {
 
   boolean hasMajority(Collection<RaftPeerId> others, RaftPeerId selfId) {
     Preconditions.assertTrue(!others.contains(selfId));
-    int num = 0;
-    if (contains(selfId)) {
-      num++;
+    return hasMajority(others::contains, contains(selfId));
+  }
+
+  boolean hasMajority(Predicate<RaftPeerId> activePeers, boolean includeSelf) {
+    if (peers.isEmpty() && !includeSelf) {
+      return true;
     }
-    for (RaftPeerId other : others) {
-      if (contains(other)) {
+
+    int num = includeSelf ? 1 : 0;
+    for (RaftPeerId peerId: peers.keySet()) {
+      if (activePeers.test(peerId)) {
         num++;
       }
     }
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfigurationImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfigurationImpl.java
index da9481a2e..aba5ae176 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfigurationImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfigurationImpl.java
@@ -30,6 +30,7 @@ import java.util.Collections;
 import java.util.EnumSet;
 import java.util.List;
 import java.util.Objects;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
 /**
@@ -238,6 +239,20 @@ final class RaftConfigurationImpl implements RaftConfiguration {
         (oldConf == null || oldConf.hasMajority(others, selfId));
   }
 
+  /** @return true if the self id together with the acknowledged followers reach majority. */
+  boolean hasMajority(Predicate<RaftPeerId> followers, RaftPeerId selfId) {
+    final boolean includeInCurrent = containsInConf(selfId);
+    final boolean hasMajorityInNewConf = conf.hasMajority(followers, includeInCurrent);
+
+    if (!isTransitional()) {
+      return hasMajorityInNewConf;
+    } else {
+      final boolean includeInOldConf = containsInOldConf(selfId);
+      final boolean hasMajorityInOldConf = oldConf.hasMajority(followers, includeInOldConf);
+      return hasMajorityInOldConf && hasMajorityInNewConf;
+    }
+  }
+
   int getMajorityCount() {
     return conf.getMajorityCount();
   }
@@ -248,6 +263,11 @@ final class RaftConfigurationImpl implements RaftConfiguration {
             (oldConf != null && oldConf.majorityRejectVotes(rejects));
   }
 
+  /** @return true if only one voting member (the leader) in the cluster */
+  boolean isSingleton() {
+    return getCurrentPeers().size() == 1 && getPreviousPeers().size() <= 1;
+  }
+
   @Override
   public String toString() {
     return logEntryIndex + ": " + conf + ", old=" + oldConf;


[ratis] 09/10: RATIS-1877. In JvmPauseMonitor, sleepTime should not be larger than sleepDeviationThreshold (#907)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 8efe8a110c750e4434babe25b25f570ae46d07b2
Author: Tsz-Wo Nicholas Sze <sz...@apache.org>
AuthorDate: Sun Aug 27 04:56:28 2023 -0700

    RATIS-1877. In JvmPauseMonitor, sleepTime should not be larger than sleepDeviationThreshold (#907)
---
 .../org/apache/ratis/util/JvmPauseMonitor.java     | 55 +++++++++++++++++++---
 .../java/org/apache/ratis/util/TimeDuration.java   |  9 ++++
 .../apache/ratis/server/impl/RaftServerProxy.java  |  8 ++--
 3 files changed, 63 insertions(+), 9 deletions(-)

diff --git a/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java b/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
index fac3d0ede..2e84c1122 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/JvmPauseMonitor.java
@@ -32,8 +32,11 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Collectors;
 
-public class JvmPauseMonitor {
-  public static final Logger LOG = LoggerFactory.getLogger(JvmPauseMonitor.class);
+/**
+ * Detect pauses in JVM causing by GC or other problems in the machine.
+ */
+public final class JvmPauseMonitor {
+  static final Logger LOG = LoggerFactory.getLogger(JvmPauseMonitor.class);
   private static final AtomicInteger THREAD_COUNT = new AtomicInteger(0);
 
   static final class GcInfo {
@@ -87,16 +90,54 @@ public class JvmPauseMonitor {
         + extraSleepTime.toString(TimeUnit.SECONDS, 3) + gc;
   }
 
-  private static final TimeDuration SLEEP_TIME = TimeDuration.valueOf(500, TimeUnit.MILLISECONDS);
+  /** To build {@link JvmPauseMonitor}. */
+  public static class Builder {
+    private Object name = "default";
+    private TimeDuration sleepDeviationThreshold = TimeDuration.valueOf(300, TimeUnit.MILLISECONDS);
+    private TimeDuration sleepTime = sleepDeviationThreshold;
+    private CheckedConsumer<TimeDuration, IOException> handler = t -> {};
+
+    public Builder setName(Object name) {
+      this.name = name;
+      return this;
+    }
+
+    public Builder setSleepTime(TimeDuration sleepTime) {
+      this.sleepTime = sleepTime;
+      return this;
+    }
+
+    public Builder setSleepDeviationThreshold(TimeDuration sleepDeviationThreshold) {
+      this.sleepDeviationThreshold = sleepDeviationThreshold;
+      return this;
+    }
+
+    public Builder setHandler(CheckedConsumer<TimeDuration, IOException> handler) {
+      this.handler = handler;
+      return this;
+    }
+
+    public JvmPauseMonitor build() {
+      return new JvmPauseMonitor(name, sleepTime, sleepDeviationThreshold, handler);
+    }
+  }
+
+  public static Builder newBuilder() {
+    return new Builder();
+  }
+
+  private final TimeDuration sleepTime;
   private final TimeDuration sleepDeviationThreshold;
 
   private final String name;
   private final AtomicReference<Thread> threadRef = new AtomicReference<>();
   private final CheckedConsumer<TimeDuration, IOException> handler;
 
-  public JvmPauseMonitor(Object name, TimeDuration sleepDeviationThreshold,
+  private JvmPauseMonitor(Object name, TimeDuration sleepTime, TimeDuration sleepDeviationThreshold,
       CheckedConsumer<TimeDuration, IOException> handler) {
     this.name = JavaUtils.getClassSimpleName(getClass()) + "-" + name;
+    // use min -- if the sleep time is too long, it may not be able to detect the given deviation.
+    this.sleepTime = TimeDuration.min(sleepTime, sleepDeviationThreshold);
     this.sleepDeviationThreshold = sleepDeviationThreshold;
     this.handler = handler;
   }
@@ -116,7 +157,7 @@ public class JvmPauseMonitor {
     final Map<String, GcInfo> before = getGcTimes();
     final TimeDuration extraSleep;
     try {
-      extraSleep = SLEEP_TIME.sleep();
+      extraSleep = sleepTime.sleep();
     } catch (InterruptedException ie) {
       return;
     }
@@ -140,7 +181,9 @@ public class JvmPauseMonitor {
   /** Start this monitor. */
   public void start() {
     final MemoizedSupplier<Thread> supplier = JavaUtils.memoize(() -> Daemon.newBuilder()
-        .setName("JvmPauseMonitor" + THREAD_COUNT.getAndIncrement()).setRunnable(this::run).build());
+        .setName(JavaUtils.getClassSimpleName(getClass()) + THREAD_COUNT.getAndIncrement())
+        .setRunnable(this::run)
+        .build());
     Optional.of(threadRef.updateAndGet(previous -> Optional.ofNullable(previous).orElseGet(supplier)))
         .filter(t -> supplier.isInitialized())
         .ifPresent(Thread::start);
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/TimeDuration.java b/ratis-common/src/main/java/org/apache/ratis/util/TimeDuration.java
index 98fb3694e..10c5c6bd1 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/TimeDuration.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/TimeDuration.java
@@ -29,6 +29,7 @@ import java.util.Objects;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Consumer;
 import java.util.function.LongUnaryOperator;
+import java.util.stream.Stream;
 
 /**
  * Time duration is represented by a long together with a {@link TimeUnit}.
@@ -59,6 +60,14 @@ public final class TimeDuration implements Comparable<TimeDuration> {
     return ordinal == timeUnits.length - 1? unit: timeUnits[ordinal + 1];
   }
 
+  /** @return the minimum of the given parameters. */
+  public static TimeDuration min(TimeDuration left, TimeDuration right) {
+    Objects.requireNonNull(left, "left == null");
+    Objects.requireNonNull(right, "right == null");
+    return Stream.of(left, right).min(TimeDuration::compareTo).orElseThrow(
+        () -> new IllegalStateException("Failed to compute min(" + left + ", " + right + ")"));
+  }
+
   /** Abbreviations of {@link TimeUnit}. */
   public enum Abbreviation {
     NANOSECONDS("ns", "nanos"),
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
index bceeb44a1..7057f53d6 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerProxy.java
@@ -73,7 +73,7 @@ import java.util.stream.Stream;
 class RaftServerProxy implements RaftServer {
   /**
    * A map: {@link RaftGroupId} -> {@link RaftServerImpl} futures.
-   *
+   * <p>
    * The map is synchronized for mutations and the bulk {@link #getGroupIds()}/{@link #getAll()} methods
    * but the (non-bulk) {@link #get(RaftGroupId)} and {@link #containsGroup(RaftGroupId)} methods are not.
    * The thread safety and atomicity guarantees for the non-bulk methods are provided by {@link ConcurrentMap}.
@@ -221,8 +221,10 @@ class RaftServerProxy implements RaftServer {
     final TimeDuration sleepDeviationThreshold = RaftServerConfigKeys.sleepDeviationThreshold(properties);
     final TimeDuration rpcSlownessTimeout = RaftServerConfigKeys.Rpc.slownessTimeout(properties);
     final TimeDuration leaderStepDownWaitTime = RaftServerConfigKeys.LeaderElection.leaderStepDownWaitTime(properties);
-    this.pauseMonitor = new JvmPauseMonitor(id, sleepDeviationThreshold,
-        extraSleep -> handleJvmPause(extraSleep, rpcSlownessTimeout, leaderStepDownWaitTime));
+    this.pauseMonitor = JvmPauseMonitor.newBuilder().setName(id)
+        .setSleepDeviationThreshold(sleepDeviationThreshold)
+        .setHandler(extraSleep -> handleJvmPause(extraSleep, rpcSlownessTimeout, leaderStepDownWaitTime))
+        .build();
     this.threadGroup = threadGroup == null ? new ThreadGroup(this.id.toString()) : threadGroup;
   }
 


[ratis] 06/10: RATIS-1873. Remove RetryCache assertion that doesn't hold (#904)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 209bbe232b89bd9418da7c16d6e7ad3f9e41a40f
Author: William Song <48...@users.noreply.github.com>
AuthorDate: Fri Aug 18 22:28:01 2023 +0800

    RATIS-1873. Remove RetryCache assertion that doesn't hold (#904)
---
 .../src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java  | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
index 341890588..3eaf2dc6c 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
@@ -1730,9 +1730,9 @@ class RaftServerImpl implements RaftServer.Division,
     final ClientInvocationId invocationId = ClientInvocationId.valueOf(logEntry.getStateMachineLogEntry());
     // update the retry cache
     final CacheEntry cacheEntry = retryCache.getOrCreateEntry(invocationId);
-    if (getInfo().isLeader()) {
-      Preconditions.assertTrue(cacheEntry != null && !cacheEntry.isCompletedNormally(),
-              "retry cache entry should be pending: %s", cacheEntry);
+    Preconditions.assertTrue(cacheEntry != null);
+    if (getInfo().isLeader() && !cacheEntry.isCompletedNormally()) {
+      LOG.warn("{} retry cache entry of leader should be pending: {}", this, cacheEntry);
     }
     if (cacheEntry.isFailed()) {
       retryCache.refreshEntry(new CacheEntry(cacheEntry.getKey()));


[ratis] 03/10: RATIS-1862 Add the parameter whether to take Snapshot when stopping to adapt to different services (#896)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit ee5bce0b7362bba63390a354e520c3f8d54b2b1e
Author: Potato <ta...@apache.org>
AuthorDate: Fri Jul 28 22:44:05 2023 +0800

    RATIS-1862 Add the parameter whether to take Snapshot when stopping to adapt to different services (#896)
---
 .../java/org/apache/ratis/server/RaftServerConfigKeys.java   | 12 ++++++++++++
 .../org/apache/ratis/server/impl/StateMachineUpdater.java    |  5 ++++-
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/ratis-server-api/src/main/java/org/apache/ratis/server/RaftServerConfigKeys.java b/ratis-server-api/src/main/java/org/apache/ratis/server/RaftServerConfigKeys.java
index 6c5aa1212..8665c8874 100644
--- a/ratis-server-api/src/main/java/org/apache/ratis/server/RaftServerConfigKeys.java
+++ b/ratis-server-api/src/main/java/org/apache/ratis/server/RaftServerConfigKeys.java
@@ -571,6 +571,18 @@ public interface RaftServerConfigKeys {
       setBoolean(properties::setBoolean, AUTO_TRIGGER_ENABLED_KEY, autoTriggerEnabled);
     }
 
+    /** whether trigger snapshot when stop raft server */
+    String TRIGGER_WHEN_STOP_ENABLED_KEY = PREFIX + ".trigger-when-stop.enabled";
+    /** by default let the state machine to trigger snapshot when stop */
+    boolean TRIGGER_WHEN_STOP_ENABLED_DEFAULT = true;
+    static boolean triggerWhenStopEnabled(RaftProperties properties) {
+      return getBoolean(properties::getBoolean,
+          TRIGGER_WHEN_STOP_ENABLED_KEY, TRIGGER_WHEN_STOP_ENABLED_DEFAULT, getDefaultLog());
+    }
+    static void setTriggerWhenStopEnabled(RaftProperties properties, boolean triggerWhenStopEnabled) {
+      setBoolean(properties::setBoolean, TRIGGER_WHEN_STOP_ENABLED_KEY, triggerWhenStopEnabled);
+    }
+
     /** The log index gap between to two snapshot creations. */
     String CREATION_GAP_KEY = PREFIX + ".creation.gap";
     long CREATION_GAP_DEFAULT = 1024;
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
index 18f165198..3cfaea8d1 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
@@ -73,6 +73,8 @@ class StateMachineUpdater implements Runnable {
   private final RaftServerImpl server;
   private final RaftLog raftLog;
 
+  private final boolean triggerSnapshotWhenStopEnabled;
+
   private final Long autoSnapshotThreshold;
   private final boolean purgeUptoSnapshotIndex;
 
@@ -104,6 +106,7 @@ class StateMachineUpdater implements Runnable {
     this.appliedIndex = new RaftLogIndex("appliedIndex", lastAppliedIndex);
     this.snapshotIndex = new RaftLogIndex("snapshotIndex", lastAppliedIndex);
 
+    this.triggerSnapshotWhenStopEnabled = RaftServerConfigKeys.Snapshot.triggerWhenStopEnabled(properties);
     final boolean autoSnapshot = RaftServerConfigKeys.Snapshot.autoTriggerEnabled(properties);
     this.autoSnapshotThreshold = autoSnapshot? RaftServerConfigKeys.Snapshot.autoTriggerThreshold(properties): null;
     final int numSnapshotFilesRetained = RaftServerConfigKeys.Snapshot.retentionFileNum(properties);
@@ -318,7 +321,7 @@ class StateMachineUpdater implements Runnable {
     if (autoSnapshotThreshold == null) {
       return false;
     } else if (shouldStop()) {
-      return getLastAppliedIndex() - snapshotIndex.get() > 0;
+      return triggerSnapshotWhenStopEnabled && getLastAppliedIndex() - snapshotIndex.get() > 0;
     }
     return state == State.RUNNING &&
         getStateMachineLastAppliedIndex() - snapshotIndex.get() >= autoSnapshotThreshold;


[ratis] 07/10: RATIS-1872. HeartbeatAck use in-correct callId as minCallId. (#905)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 4b7305ac87551b1461248d4852a19237f01f2af7
Author: Tsz-Wo Nicholas Sze <sz...@apache.org>
AuthorDate: Fri Aug 18 07:49:03 2023 -0700

    RATIS-1872. HeartbeatAck use in-correct callId as minCallId. (#905)
---
 .../main/java/org/apache/ratis/server/impl/LeaderStateImpl.java  | 9 +--------
 .../java/org/apache/ratis/server/impl/ReadIndexHeartbeats.java   | 9 ++++++---
 2 files changed, 7 insertions(+), 11 deletions(-)

diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
index 5dfbc009b..adf035e4f 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java
@@ -54,7 +54,6 @@ import org.apache.ratis.util.CodeInjectionForTesting;
 import org.apache.ratis.util.CollectionUtils;
 import org.apache.ratis.util.Daemon;
 import org.apache.ratis.util.JavaUtils;
-import org.apache.ratis.util.MemoizedSupplier;
 import org.apache.ratis.util.Preconditions;
 import org.apache.ratis.util.TimeDuration;
 import org.apache.ratis.util.Timestamp;
@@ -1076,20 +1075,14 @@ class LeaderStateImpl implements LeaderState {
           new LeaderNotReadyException(server.getMemberId())));
     }
 
-    final MemoizedSupplier<AppendEntriesListener> supplier = MemoizedSupplier.valueOf(
-        () -> new AppendEntriesListener(readIndex));
     final AppendEntriesListener listener = readIndexHeartbeats.addAppendEntriesListener(
-        readIndex, key -> supplier.get());
+        readIndex, i -> new AppendEntriesListener(i, senders));
 
     // the readIndex is already acknowledged before
     if (listener == null) {
       return CompletableFuture.completedFuture(readIndex);
     }
 
-    if (supplier.isInitialized()) {
-      senders.forEach(LogAppender::triggerHeartbeat);
-    }
-
     return listener.getFuture();
   }
 
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/ReadIndexHeartbeats.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/ReadIndexHeartbeats.java
index 92513086d..7e252f7ad 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/ReadIndexHeartbeats.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/ReadIndexHeartbeats.java
@@ -85,8 +85,12 @@ class ReadIndexHeartbeats {
     private final CompletableFuture<Long> future = new CompletableFuture<>();
     private final ConcurrentHashMap<RaftPeerId, HeartbeatAck> replies = new ConcurrentHashMap<>();
 
-    AppendEntriesListener(long commitIndex) {
+    AppendEntriesListener(long commitIndex, Iterable<LogAppender> logAppenders) {
       this.commitIndex = commitIndex;
+      for (LogAppender a : logAppenders) {
+        a.triggerHeartbeat();
+        replies.put(a.getFollowerId(), new HeartbeatAck(a));
+      }
     }
 
     CompletableFuture<Long> getFuture() {
@@ -159,8 +163,7 @@ class ReadIndexHeartbeats {
   private final AppendEntriesListeners appendEntriesListeners = new AppendEntriesListeners();
   private final RaftLogIndex ackedCommitIndex = new RaftLogIndex("ackedCommitIndex", RaftLog.INVALID_LOG_INDEX);
 
-  AppendEntriesListener addAppendEntriesListener(long commitIndex,
-                                                              Function<Long, AppendEntriesListener> constructor) {
+  AppendEntriesListener addAppendEntriesListener(long commitIndex, Function<Long, AppendEntriesListener> constructor) {
     if (commitIndex <= ackedCommitIndex.get()) {
       return null;
     }


[ratis] 10/10: upgrade snapshot version

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 1aeb69d60bde68e751192c739d27312ddcc50caf
Author: szywilliam <sz...@163.com>
AuthorDate: Mon Aug 28 16:55:06 2023 +0800

    upgrade snapshot version
---
 pom.xml                       | 4 ++--
 ratis-assembly/pom.xml        | 2 +-
 ratis-client/pom.xml          | 2 +-
 ratis-common/pom.xml          | 2 +-
 ratis-docs/pom.xml            | 2 +-
 ratis-examples/pom.xml        | 2 +-
 ratis-experiments/pom.xml     | 2 +-
 ratis-grpc/pom.xml            | 2 +-
 ratis-metrics/pom.xml         | 2 +-
 ratis-netty/pom.xml           | 2 +-
 ratis-proto/pom.xml           | 2 +-
 ratis-replicated-map/pom.xml  | 2 +-
 ratis-resource-bundle/pom.xml | 2 +-
 ratis-server-api/pom.xml      | 2 +-
 ratis-server/pom.xml          | 2 +-
 ratis-shell/pom.xml           | 2 +-
 ratis-test/pom.xml            | 2 +-
 ratis-tools/pom.xml           | 2 +-
 18 files changed, 19 insertions(+), 19 deletions(-)

diff --git a/pom.xml b/pom.xml
index 2d63a7d8e..b65e66f84 100644
--- a/pom.xml
+++ b/pom.xml
@@ -24,7 +24,7 @@
 
   <artifactId>ratis</artifactId>
   <groupId>org.apache.ratis</groupId>
-  <version>2.5.1-SNAPSHOT</version>
+  <version>2.5.2-8efe8a1-SNAPSHOT</version>
   <name>Apache Ratis</name>
   <packaging>pom</packaging>
   <description>
@@ -160,7 +160,7 @@
 
 
   <properties>
-    <project.build.outputTimestamp>2023-01-01T00:00:00Z</project.build.outputTimestamp>
+    <project.build.outputTimestamp>2023-08-28T08:54:42Z</project.build.outputTimestamp>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <!-- where to find the generated LICENSE files -->
diff --git a/ratis-assembly/pom.xml b/ratis-assembly/pom.xml
index f968eea92..12b968817 100644
--- a/ratis-assembly/pom.xml
+++ b/ratis-assembly/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-assembly</artifactId>
diff --git a/ratis-client/pom.xml b/ratis-client/pom.xml
index 9ecc549b5..e63b1a87f 100644
--- a/ratis-client/pom.xml
+++ b/ratis-client/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-client</artifactId>
diff --git a/ratis-common/pom.xml b/ratis-common/pom.xml
index 10c5ec129..747a613bf 100644
--- a/ratis-common/pom.xml
+++ b/ratis-common/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-common</artifactId>
diff --git a/ratis-docs/pom.xml b/ratis-docs/pom.xml
index 6060c6598..c7355d0b8 100644
--- a/ratis-docs/pom.xml
+++ b/ratis-docs/pom.xml
@@ -20,7 +20,7 @@ https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-docs</artifactId>
diff --git a/ratis-examples/pom.xml b/ratis-examples/pom.xml
index e0f15d56c..ffc7e8d39 100644
--- a/ratis-examples/pom.xml
+++ b/ratis-examples/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-examples</artifactId>
diff --git a/ratis-experiments/pom.xml b/ratis-experiments/pom.xml
index 23f057f74..5f7421c4d 100644
--- a/ratis-experiments/pom.xml
+++ b/ratis-experiments/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-experiments</artifactId>
diff --git a/ratis-grpc/pom.xml b/ratis-grpc/pom.xml
index d120e02d7..9e0a7b4ec 100644
--- a/ratis-grpc/pom.xml
+++ b/ratis-grpc/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-grpc</artifactId>
diff --git a/ratis-metrics/pom.xml b/ratis-metrics/pom.xml
index caab6d4e8..7c68b3383 100644
--- a/ratis-metrics/pom.xml
+++ b/ratis-metrics/pom.xml
@@ -18,7 +18,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-metrics</artifactId>
diff --git a/ratis-netty/pom.xml b/ratis-netty/pom.xml
index 36786a4e7..8c83b9a75 100644
--- a/ratis-netty/pom.xml
+++ b/ratis-netty/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-netty</artifactId>
diff --git a/ratis-proto/pom.xml b/ratis-proto/pom.xml
index 2b6c8aa86..7870c5cdc 100644
--- a/ratis-proto/pom.xml
+++ b/ratis-proto/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-proto</artifactId>
diff --git a/ratis-replicated-map/pom.xml b/ratis-replicated-map/pom.xml
index 33bea2341..cd199cd6d 100644
--- a/ratis-replicated-map/pom.xml
+++ b/ratis-replicated-map/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-replicated-map</artifactId>
diff --git a/ratis-resource-bundle/pom.xml b/ratis-resource-bundle/pom.xml
index 88f294dd5..527576470 100644
--- a/ratis-resource-bundle/pom.xml
+++ b/ratis-resource-bundle/pom.xml
@@ -23,7 +23,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
     <relativePath>..</relativePath>
   </parent>
 
diff --git a/ratis-server-api/pom.xml b/ratis-server-api/pom.xml
index c342ba0d0..aa5a66271 100644
--- a/ratis-server-api/pom.xml
+++ b/ratis-server-api/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-server-api</artifactId>
diff --git a/ratis-server/pom.xml b/ratis-server/pom.xml
index d9b045db8..f1921dce1 100644
--- a/ratis-server/pom.xml
+++ b/ratis-server/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-server</artifactId>
diff --git a/ratis-shell/pom.xml b/ratis-shell/pom.xml
index f22d90fbc..2571a97b4 100644
--- a/ratis-shell/pom.xml
+++ b/ratis-shell/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-shell</artifactId>
diff --git a/ratis-test/pom.xml b/ratis-test/pom.xml
index b7e036e2e..d43690179 100644
--- a/ratis-test/pom.xml
+++ b/ratis-test/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-test</artifactId>
diff --git a/ratis-tools/pom.xml b/ratis-tools/pom.xml
index 1fc865035..e71e26d83 100644
--- a/ratis-tools/pom.xml
+++ b/ratis-tools/pom.xml
@@ -17,7 +17,7 @@
   <parent>
     <artifactId>ratis</artifactId>
     <groupId>org.apache.ratis</groupId>
-    <version>2.5.1-SNAPSHOT</version>
+    <version>2.5.2-8efe8a1-SNAPSHOT</version>
   </parent>
 
   <artifactId>ratis-tools</artifactId>


[ratis] 01/10: RATIS-1858. Follower keeps logging first election timeout. (#894)

Posted by wi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

williamsong pushed a commit to branch snapshot-branch2
in repository https://gitbox.apache.org/repos/asf/ratis.git

commit 60d520146ba26c6408bb7a6064280c51c79a8954
Author: Tsz-Wo Nicholas Sze <sz...@apache.org>
AuthorDate: Thu Jul 27 10:52:11 2023 -0700

    RATIS-1858. Follower keeps logging first election timeout. (#894)
---
 .../org/apache/ratis/server/impl/RaftServerImpl.java     |  8 +++++++-
 .../java/org/apache/ratis/server/impl/ServerState.java   | 16 ++++++++--------
 2 files changed, 15 insertions(+), 9 deletions(-)

diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
index 295ddbc61..8f8c0a982 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
@@ -517,6 +517,12 @@ class RaftServerImpl implements RaftServer.Division,
     });
   }
 
+  void setFirstElection(Object reason) {
+    if (firstElectionSinceStartup.compareAndSet(true, false)) {
+      LOG.info("{}: set firstElectionSinceStartup to false for {}", getMemberId(), reason);
+    }
+  }
+
   /**
    * Change the server state to Follower if this server is in a different role or force is true.
    * @param newTerm The new term.
@@ -545,7 +551,7 @@ class RaftServerImpl implements RaftServer.Division,
         role.shutdownFollowerState();
       }
       role.startFollowerState(this, reason);
-      firstElectionSinceStartup.set(false);
+      setFirstElection(reason);
     }
     return metadataUpdated;
   }
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
index ee0760f1e..281569190 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
@@ -75,7 +75,7 @@ class ServerState implements Closeable {
   /** local storage for log and snapshot */
   private RaftStorageImpl storage;
   private final SnapshotManager snapshotManager;
-  private volatile Timestamp lastNoLeaderTime;
+  private final AtomicReference<Timestamp> lastNoLeaderTime;
   private final TimeDuration noLeaderTimeout;
 
   private final ReadRequests readRequests;
@@ -151,7 +151,7 @@ class ServerState implements Closeable {
     snapshotManager = new SnapshotManager(id, storage.getStorageDir(), stateMachine.getStateMachineStorage());
 
     // On start the leader is null, start the clock now
-    this.lastNoLeaderTime = Timestamp.currentTime();
+    this.lastNoLeaderTime = new AtomicReference<>(Timestamp.currentTime());
     this.noLeaderTimeout = RaftServerConfigKeys.Notification.noLeaderTimeout(prop);
 
     final LongSupplier getSnapshotIndexFromStateMachine = () -> Optional.ofNullable(stateMachine.getLatestSnapshot())
@@ -303,15 +303,15 @@ class ServerState implements Closeable {
   void setLeader(RaftPeerId newLeaderId, Object op) {
     final RaftPeerId oldLeaderId = leaderId.getAndSet(newLeaderId);
     if (!Objects.equals(oldLeaderId, newLeaderId)) {
-      String suffix;
+      final String suffix;
       if (newLeaderId == null) {
         // reset the time stamp when a null leader is assigned
-        lastNoLeaderTime = Timestamp.currentTime();
+        lastNoLeaderTime.set(Timestamp.currentTime());
         suffix = "";
       } else {
-        Timestamp previous = lastNoLeaderTime;
-        lastNoLeaderTime = null;
+        final Timestamp previous = lastNoLeaderTime.getAndSet(null);
         suffix = ", leader elected after " + previous.elapsedTimeMs() + "ms";
+        server.setFirstElection(op);
         server.getStateMachine().event().notifyLeaderChanged(getMemberId(), newLeaderId);
       }
       LOG.info("{}: change Leader from {} to {} at term {} for {}{}",
@@ -323,14 +323,14 @@ class ServerState implements Closeable {
   }
 
   boolean shouldNotifyExtendedNoLeader() {
-    return Optional.ofNullable(lastNoLeaderTime)
+    return Optional.ofNullable(lastNoLeaderTime.get())
         .map(Timestamp::elapsedTime)
         .filter(t -> t.compareTo(noLeaderTimeout) > 0)
         .isPresent();
   }
 
   long getLastLeaderElapsedTimeMs() {
-    return Optional.ofNullable(lastNoLeaderTime).map(Timestamp::elapsedTimeMs).orElse(0L);
+    return Optional.ofNullable(lastNoLeaderTime.get()).map(Timestamp::elapsedTimeMs).orElse(0L);
   }
 
   void becomeLeader() {