b4d30c28b43f47a39cba70c08fb5765722e6300f
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / AbstractLeader.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.cluster.raft.behaviors;
9
10 import static java.util.Objects.requireNonNull;
11
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.Cancellable;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.io.ByteSource;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.io.IOException;
19 import java.io.ObjectOutputStream;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.LinkedList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.OptionalInt;
30 import java.util.Queue;
31 import java.util.concurrent.TimeUnit;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.controller.cluster.io.SharedFileBackedOutputStream;
34 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
35 import org.opendaylight.controller.cluster.messaging.SliceOptions;
36 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
37 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
38 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
39 import org.opendaylight.controller.cluster.raft.PeerInfo;
40 import org.opendaylight.controller.cluster.raft.RaftActorContext;
41 import org.opendaylight.controller.cluster.raft.RaftState;
42 import org.opendaylight.controller.cluster.raft.RaftVersions;
43 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
44 import org.opendaylight.controller.cluster.raft.VotingState;
45 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
46 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
47 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
48 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
49 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
50 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
51 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
52 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
53 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
54 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
55 import org.opendaylight.controller.cluster.raft.messages.Payload;
56 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
57 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
58 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
59 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
60 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
61 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
62 import scala.concurrent.duration.FiniteDuration;
63
64 /**
65  * The behavior of a RaftActor when it is in the Leader state.
66  *
67  * <p>
68  * Leaders:
69  * <ul>
70  * <li> Upon election: send initial empty AppendEntries RPCs
71  * (heartbeat) to each server; repeat during idle periods to
72  * prevent election timeouts (§5.2)
73  * <li> If command received from client: append entry to local log,
74  * respond after entry applied to state machine (§5.3)
75  * <li> If last log index ≥ nextIndex for a follower: send
76  * AppendEntries RPC with log entries starting at nextIndex
77  * <li> If successful: update nextIndex and matchIndex for
78  * follower (§5.3)
79  * <li> If AppendEntries fails because of log inconsistency:
80  * decrement nextIndex and retry (§5.3)
81  * <li> If there exists an N such that N &gt; commitIndex, a majority
82  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
83  * set commitIndex = N (§5.3, §5.4).
84  * </ul>
85  */
86 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
87     private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
88
89     /**
90      * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
91      * expect the entries to be modified in sequence, hence we open-code the lookup.
92      * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
93      *       but we already expect those to be far from frequent.
94      */
95     private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
96
97     /**
98      * Map of serialized AppendEntries output streams keyed by log index. This is used in conjunction with the
99      * appendEntriesMessageSlicer for slicing single ReplicatedLogEntry payloads that exceed the message size threshold.
100      * This Map allows the SharedFileBackedOutputStreams to be reused for multiple followers.
101      */
102     private final Map<Long, SharedFileBackedOutputStream> sharedSerializedAppendEntriesStreams = new HashMap<>();
103     private final MessageSlicer appendEntriesMessageSlicer;
104
105     private Cancellable heartbeatSchedule = null;
106     private Optional<SnapshotHolder> snapshotHolder = Optional.empty();
107     private int minReplicationCount;
108
109     protected AbstractLeader(final RaftActorContext context, final RaftState state,
110             final @Nullable AbstractLeader initializeFromLeader) {
111         super(context, state);
112
113         appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName())
114             .messageSliceSize(context.getConfigParams().getSnapshotChunkSize())
115             .expireStateAfterInactivity(context.getConfigParams().getElectionTimeOutInterval().toMillis() * 3,
116                     TimeUnit.MILLISECONDS).build();
117
118         if (initializeFromLeader != null) {
119             followerToLog.putAll(initializeFromLeader.followerToLog);
120             snapshotHolder = initializeFromLeader.snapshotHolder;
121             trackers.addAll(initializeFromLeader.trackers);
122         } else {
123             for (PeerInfo peerInfo: context.getPeers()) {
124                 FollowerLogInformation followerLogInformation = new FollowerLogInformation(peerInfo, context);
125                 followerToLog.put(peerInfo.getId(), followerLogInformation);
126             }
127         }
128
129         log.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
130
131         updateMinReplicaCount();
132
133         // Immediately schedule a heartbeat
134         // Upon election: send initial empty AppendEntries RPCs
135         // (heartbeat) to each server; repeat during idle periods to
136         // prevent election timeouts (§5.2)
137         sendAppendEntries(0, false);
138
139         // It is important to schedule this heartbeat here
140         scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
141     }
142
143     protected AbstractLeader(final RaftActorContext context, final RaftState state) {
144         this(context, state, null);
145     }
146
147     /**
148      * Return an immutable collection of follower identifiers.
149      *
150      * @return Collection of follower IDs
151      */
152     public final Collection<String> getFollowerIds() {
153         return followerToLog.keySet();
154     }
155
156     public void addFollower(final String followerId) {
157         FollowerLogInformation followerLogInformation = new FollowerLogInformation(context.getPeerInfo(followerId),
158             context);
159         followerToLog.put(followerId, followerLogInformation);
160
161         if (heartbeatSchedule == null) {
162             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
163         }
164     }
165
166     public void removeFollower(final String followerId) {
167         followerToLog.remove(followerId);
168     }
169
170     public final void updateMinReplicaCount() {
171         int numVoting = 0;
172         for (PeerInfo peer: context.getPeers()) {
173             if (peer.isVoting()) {
174                 numVoting++;
175             }
176         }
177
178         minReplicationCount = getMajorityVoteCount(numVoting);
179     }
180
181     protected int getMinIsolatedLeaderPeerCount() {
182       //the isolated Leader peer count will be 1 less than the majority vote count.
183         //this is because the vote count has the self vote counted in it
184         //for e.g
185         //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
186         //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
187         //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
188
189         return minReplicationCount > 0 ? minReplicationCount - 1 : 0;
190     }
191
192     @VisibleForTesting
193     void setSnapshotHolder(final @Nullable SnapshotHolder snapshotHolder) {
194         this.snapshotHolder = Optional.ofNullable(snapshotHolder);
195     }
196
197     @VisibleForTesting
198     boolean hasSnapshot() {
199         return snapshotHolder.isPresent();
200     }
201
202     @Override
203     protected RaftActorBehavior handleAppendEntries(final ActorRef sender,
204         final AppendEntries appendEntries) {
205
206         log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
207
208         return this;
209     }
210
211     @Override
212     protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
213             final AppendEntriesReply appendEntriesReply) {
214         log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
215
216         // Update the FollowerLogInformation
217         String followerId = appendEntriesReply.getFollowerId();
218         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
219
220         if (followerLogInformation == null) {
221             log.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
222             return this;
223         }
224
225         final var followerRaftVersion = appendEntriesReply.getRaftVersion();
226         if (followerRaftVersion < RaftVersions.FLUORINE_VERSION) {
227             log.warn("{}: handleAppendEntriesReply - ignoring reply from follower {} raft version {}", logName(),
228                 followerId, followerRaftVersion);
229             return this;
230         }
231
232         final long lastActivityNanos = followerLogInformation.nanosSinceLastActivity();
233         if (lastActivityNanos > context.getConfigParams().getElectionTimeOutInterval().toNanos()) {
234             log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
235                     + "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
236                     logName(), appendEntriesReply, TimeUnit.NANOSECONDS.toMillis(lastActivityNanos),
237                     context.getLastApplied(), context.getCommitIndex());
238         }
239
240         followerLogInformation.markFollowerActive();
241         followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
242         followerLogInformation.setRaftVersion(followerRaftVersion);
243         followerLogInformation.setNeedsLeaderAddress(appendEntriesReply.isNeedsLeaderAddress());
244
245         long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
246         boolean updated = false;
247         if (appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
248             // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
249             // in raft as a node cannot become leader if it's log is behind another's. However, the
250             // non-voting semantics deviate a bit from raft. Only voting members participate in
251             // elections and can become leader so it's possible for a non-voting follower to be ahead
252             // of the leader. This can happen if persistence is disabled and all voting members are
253             // restarted. In this case, the voting leader will start out with an empty log however
254             // the non-voting followers still retain the previous data in memory. On the first
255             // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
256             // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
257             // lastLogIndex may be higher in which case we want to reset the follower by installing a
258             // snapshot. It's also possible that the follower's last log index is behind the leader's.
259             // However in this case the log terms won't match and the logs will conflict - this is handled
260             // elsewhere.
261             log.info("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} "
262                     + "(snapshotIndex {}, snapshotTerm {}) - forcing install snaphot", logName(),
263                     followerLogInformation.getId(), appendEntriesReply.getLogLastIndex(),
264                     context.getReplicatedLog().lastIndex(), context.getReplicatedLog().getSnapshotIndex(),
265                     context.getReplicatedLog().getSnapshotTerm());
266
267             followerLogInformation.setMatchIndex(-1);
268             followerLogInformation.setNextIndex(-1);
269
270             initiateCaptureSnapshot(followerId);
271
272             updated = true;
273         } else if (appendEntriesReply.isSuccess()) {
274             long followersLastLogTermInLeadersLog = getLogEntryTerm(followerLastLogIndex);
275             if (followerLastLogIndex >= 0 && followersLastLogTermInLeadersLog >= 0
276                     && followersLastLogTermInLeadersLog != appendEntriesReply.getLogLastTerm()) {
277                 // The follower's last entry is present in the leader's journal but the terms don't match so the
278                 // follower has a conflicting entry. Since the follower didn't report that it's out of sync, this means
279                 // either the previous leader entry sent didn't conflict or the previous leader entry is in the snapshot
280                 // and no longer in the journal. Either way, we set the follower's next index to 1 less than the last
281                 // index reported by the follower. For the former case, the leader will send all entries starting with
282                 // the previous follower's index and the follower will remove and replace the conflicting entries as
283                 // needed. For the latter, the leader will initiate an install snapshot.
284
285                 followerLogInformation.setNextIndex(followerLastLogIndex - 1);
286                 updated = true;
287
288                 log.info("{}: handleAppendEntriesReply: follower {} last log term {} for index {} conflicts with the "
289                         + "leader's {} - set the follower's next index to {}", logName(),
290                         followerId, appendEntriesReply.getLogLastTerm(), appendEntriesReply.getLogLastIndex(),
291                         followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
292             } else {
293                 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
294             }
295         } else {
296             log.info("{}: handleAppendEntriesReply - received unsuccessful reply: {}, leader snapshotIndex: {}, "
297                     + "snapshotTerm: {}, replicatedToAllIndex: {}", logName(), appendEntriesReply,
298                     context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm(),
299                     getReplicatedToAllIndex());
300
301             long followersLastLogTermInLeadersLogOrSnapshot = getLogEntryOrSnapshotTerm(followerLastLogIndex);
302             if (appendEntriesReply.isForceInstallSnapshot()) {
303                 // Reset the followers match and next index. This is to signal that this follower has nothing
304                 // in common with this Leader and so would require a snapshot to be installed
305                 followerLogInformation.setMatchIndex(-1);
306                 followerLogInformation.setNextIndex(-1);
307
308                 // Force initiate a snapshot capture
309                 initiateCaptureSnapshot(followerId);
310             } else if (followerLastLogIndex < 0 || followersLastLogTermInLeadersLogOrSnapshot >= 0
311                     && followersLastLogTermInLeadersLogOrSnapshot == appendEntriesReply.getLogLastTerm()) {
312                 // The follower's log is empty or the follower's last entry is present in the leader's journal or
313                 // snapshot and the terms match so the follower is just behind the leader's journal from the last
314                 // snapshot, if any. We'll catch up the follower quickly by starting at the follower's last log index.
315
316                 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
317
318                 log.info("{}: follower {} appears to be behind the leader from the last snapshot - "
319                     + "updated: matchIndex: {}, nextIndex: {}", logName(), followerId,
320                     followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
321             } else {
322                 // The follower's log conflicts with leader's log so decrement follower's next index
323                 // in an attempt to find where the logs match.
324                 if (followerLogInformation.decrNextIndex(appendEntriesReply.getLogLastIndex())) {
325                     updated = true;
326
327                     log.info("{}: follower {} last log term {} conflicts with the leader's {} - dec next index to {}",
328                             logName(), followerId, appendEntriesReply.getLogLastTerm(),
329                             followersLastLogTermInLeadersLogOrSnapshot, followerLogInformation.getNextIndex());
330                 }
331             }
332         }
333
334         if (log.isTraceEnabled()) {
335             log.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
336                     logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
337         }
338
339         possiblyUpdateCommitIndex();
340
341         //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
342         sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
343
344         return this;
345     }
346
347     private void possiblyUpdateCommitIndex() {
348         // Figure out if we can update the the commitIndex as follows:
349         //   If there exists an index N such that N > commitIndex, a majority of matchIndex[i] ≥ N,
350         //     and log[N].term == currentTerm:
351         //   set commitIndex = N (§5.3, §5.4).
352         for (long index = context.getCommitIndex() + 1; ; index++) {
353             ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(index);
354             if (replicatedLogEntry == null) {
355                 log.trace("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
356                         logName(), index, context.getReplicatedLog().getSnapshotIndex(),
357                         context.getReplicatedLog().size());
358                 break;
359             }
360
361             // Count our entry if it has been persisted.
362             int replicatedCount = replicatedLogEntry.isPersistencePending() ? 0 : 1;
363
364             if (replicatedCount == 0) {
365                 // We don't commit and apply a log entry until we've gotten the ack from our local persistence,
366                 // even though there *shouldn't* be any issue with updating the commit index if we get a consensus
367                 // amongst the followers w/o the local persistence ack.
368                 break;
369             }
370
371             log.trace("{}: checking Nth index {}", logName(), index);
372             for (FollowerLogInformation info : followerToLog.values()) {
373                 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
374                 if (info.getMatchIndex() >= index && peerInfo != null && peerInfo.isVoting()) {
375                     replicatedCount++;
376                 } else if (log.isTraceEnabled()) {
377                     log.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
378                             info.getMatchIndex(), peerInfo);
379                 }
380             }
381
382             if (log.isTraceEnabled()) {
383                 log.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount,
384                         minReplicationCount);
385             }
386
387             if (replicatedCount >= minReplicationCount) {
388                 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
389                 // "Raft never commits log entries from previous terms by counting replicas".
390                 // However we keep looping so we can make progress when new entries in the current term
391                 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
392                 // counting replicas, then all prior entries are committed indirectly".
393                 if (replicatedLogEntry.getTerm() == currentTerm()) {
394                     log.trace("{}: Setting commit index to {}", logName(), index);
395                     context.setCommitIndex(index);
396                 } else {
397                     log.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, "
398                             + "term {} does not match the current term {}", logName(), index,
399                             replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
400                 }
401             } else {
402                 log.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
403                 break;
404             }
405         }
406
407         // Apply the change to the state machine
408         if (context.getCommitIndex() > context.getLastApplied()) {
409             log.debug("{}: Applying to log - commitIndex: {}, lastAppliedIndex: {}", logName(),
410                     context.getCommitIndex(), context.getLastApplied());
411
412             applyLogToStateMachine(context.getCommitIndex());
413         }
414
415         if (!context.getSnapshotManager().isCapturing()) {
416             purgeInMemoryLog();
417         }
418     }
419
420     private boolean updateFollowerLogInformation(final FollowerLogInformation followerLogInformation,
421             final AppendEntriesReply appendEntriesReply) {
422         boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
423         updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
424
425         if (updated && log.isDebugEnabled()) {
426             log.debug(
427                 "{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
428                 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
429                 followerLogInformation.getNextIndex());
430         }
431         return updated;
432     }
433
434     private void purgeInMemoryLog() {
435         //find the lowest index across followers which has been replicated to all.
436         // lastApplied if there are no followers, so that we keep clearing the log for single-node
437         // we would delete the in-mem log from that index on, in-order to minimize mem usage
438         // we would also share this info thru AE with the followers so that they can delete their log entries as well.
439         long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
440         for (FollowerLogInformation info : followerToLog.values()) {
441             minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
442         }
443
444         super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
445     }
446
447     /**
448      * Removes and returns the ClientRequestTracker for the specified log index.
449      * @param logIndex the log index
450      * @return the ClientRequestTracker or null if none available
451      */
452     private ClientRequestTracker removeClientRequestTracker(final long logIndex) {
453         final Iterator<ClientRequestTracker> it = trackers.iterator();
454         while (it.hasNext()) {
455             final ClientRequestTracker t = it.next();
456             if (t.getIndex() == logIndex) {
457                 it.remove();
458                 return t;
459             }
460         }
461
462         return null;
463     }
464
465     @Override
466     final ApplyState getApplyStateFor(final ReplicatedLogEntry entry) {
467         // first check whether a ClientRequestTracker exists for this entry.
468         // If it does that means the leader wasn't dropped before the transaction applied.
469         // That means that this transaction can be safely applied as a local transaction since we
470         // have the ClientRequestTracker.
471         final ClientRequestTracker tracker = removeClientRequestTracker(entry.getIndex());
472         if (tracker != null) {
473             return new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), entry);
474         }
475
476         // Tracker is missing, this means that we switched behaviours between replicate and applystate
477         // and became the leader again,. We still want to apply this as a local modification because
478         // we have resumed leadership with that log entry having been committed.
479         final Payload payload = entry.getData();
480         if (payload instanceof IdentifiablePayload<?> identifiable) {
481             return new ApplyState(null, identifiable.getIdentifier(), entry);
482         }
483
484         return new ApplyState(null, null, entry);
485     }
486
487     @Override
488     protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender, final RequestVoteReply requestVoteReply) {
489         return this;
490     }
491
492     protected void beforeSendHeartbeat() {
493         // No-op
494     }
495
496     @Override
497     public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
498         requireNonNull(sender, "sender should not be null");
499
500         if (appendEntriesMessageSlicer.handleMessage(message)) {
501             return this;
502         }
503
504         // If RPC request or response contains term T > currentTerm:
505         // set currentTerm = T, convert to follower (§5.1)
506         // This applies to all RPC messages and responses
507         if (message instanceof RaftRPC rpc && rpc.getTerm() > context.getTermInformation().getCurrentTerm()
508                 && shouldUpdateTerm(rpc)) {
509
510             log.info("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
511                 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
512
513             context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
514
515             // This is a special case. Normally when stepping down as leader we don't process and reply to the
516             // RaftRPC as per raft. But if we're in the process of transferring leadership and we get a
517             // RequestVote, process the RequestVote before switching to Follower. This enables the requesting
518             // candidate node to be elected the leader faster and avoids us possibly timing out in the Follower
519             // state and starting a new election and grabbing leadership back before the other candidate node can
520             // start a new election due to lack of responses. This case would only occur if there isn't a majority
521             // of other nodes available that can elect the requesting candidate. Since we're transferring
522             // leadership, we should make every effort to get the requesting node elected.
523             if (rpc instanceof RequestVote requestVote && context.getRaftActorLeadershipTransferCohort() != null) {
524                 log.debug("{}: Leadership transfer in progress - processing RequestVote", logName());
525                 requestVote(sender, requestVote);
526             }
527
528             return internalSwitchBehavior(RaftState.Follower);
529         }
530
531         if (message instanceof SendHeartBeat) {
532             beforeSendHeartbeat();
533             sendHeartBeat();
534             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
535         } else if (message instanceof SendInstallSnapshot sendInstallSnapshot) {
536             setSnapshotHolder(new SnapshotHolder(sendInstallSnapshot.getSnapshot(),
537                 sendInstallSnapshot.getSnapshotBytes()));
538             sendInstallSnapshot();
539         } else if (message instanceof Replicate replicate) {
540             replicate(replicate);
541         } else if (message instanceof InstallSnapshotReply installSnapshotReply) {
542             handleInstallSnapshotReply(installSnapshotReply);
543         } else if (message instanceof CheckConsensusReached) {
544             possiblyUpdateCommitIndex();
545         } else {
546             return super.handleMessage(sender, message);
547         }
548
549         return this;
550     }
551
552     @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS",
553             justification = "JDT nullness with SpotBugs at setSnapshotHolder(null)")
554     private void handleInstallSnapshotReply(final InstallSnapshotReply reply) {
555         log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
556
557         String followerId = reply.getFollowerId();
558         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
559         if (followerLogInformation == null) {
560             // This can happen during AddServer if it times out.
561             log.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
562                     logName(), followerId);
563             return;
564         }
565
566         LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
567         if (installSnapshotState == null) {
568             log.error("{}: LeaderInstallSnapshotState not found for follower {} in InstallSnapshotReply",
569                     logName(), followerId);
570             return;
571         }
572
573         installSnapshotState.resetChunkTimer();
574         followerLogInformation.markFollowerActive();
575
576         if (installSnapshotState.getChunkIndex() == reply.getChunkIndex()) {
577             boolean wasLastChunk = false;
578             if (reply.isSuccess()) {
579                 if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
580                     //this was the last chunk reply
581
582                     long followerMatchIndex = snapshotHolder.orElseThrow().getLastIncludedIndex();
583                     followerLogInformation.setMatchIndex(followerMatchIndex);
584                     followerLogInformation.setNextIndex(followerMatchIndex + 1);
585                     followerLogInformation.clearLeaderInstallSnapshotState();
586
587                     log.info("{}: Snapshot successfully installed on follower {} (last chunk {}) - "
588                         + "matchIndex set to {}, nextIndex set to {}", logName(), followerId, reply.getChunkIndex(),
589                         followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
590
591                     if (!anyFollowersInstallingSnapshot()) {
592                         // once there are no pending followers receiving snapshots
593                         // we can remove snapshot from the memory
594                         setSnapshotHolder(null);
595                     }
596
597                     wasLastChunk = true;
598                     if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
599                         UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
600                                              new UnInitializedFollowerSnapshotReply(followerId);
601                         context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
602                         log.debug("Sent message UnInitializedFollowerSnapshotReply to self");
603                     }
604                 } else {
605                     installSnapshotState.markSendStatus(true);
606                 }
607             } else {
608                 log.warn("{}: Received failed InstallSnapshotReply - will retry: {}", logName(), reply);
609
610                 installSnapshotState.markSendStatus(false);
611             }
612
613             if (wasLastChunk) {
614                 if (!context.getSnapshotManager().isCapturing()) {
615                     // Since the follower is now caught up try to purge the log.
616                     purgeInMemoryLog();
617                 }
618             } else {
619                 ActorSelection followerActor = context.getPeerActorSelection(followerId);
620                 if (followerActor != null) {
621                     sendSnapshotChunk(followerActor, followerLogInformation);
622                 }
623             }
624
625         } else {
626             log.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
627                     logName(), reply.getChunkIndex(), followerId,
628                     installSnapshotState.getChunkIndex());
629
630             if (reply.getChunkIndex() == LeaderInstallSnapshotState.INVALID_CHUNK_INDEX) {
631                 // Since the Follower did not find this index to be valid we should reset the follower snapshot
632                 // so that Installing the snapshot can resume from the beginning
633                 installSnapshotState.reset();
634             }
635         }
636     }
637
638     private boolean anyFollowersInstallingSnapshot() {
639         for (FollowerLogInformation info: followerToLog.values()) {
640             if (info.getInstallSnapshotState() != null) {
641                 return true;
642             }
643
644         }
645
646         return false;
647     }
648
649     private void replicate(final Replicate replicate) {
650         final long logIndex = replicate.logIndex();
651
652         log.debug("{}: Replicate message: identifier: {}, logIndex: {}, isSendImmediate: {}", logName(),
653                 replicate.identifier(), logIndex, replicate.sendImmediate());
654
655         // Create a tracker entry we will use this later to notify the
656         // client actor
657         final var clientActor = replicate.clientActor();
658         if (clientActor != null) {
659             trackers.add(new ClientRequestTrackerImpl(clientActor, replicate.identifier(), logIndex));
660         }
661
662         boolean applyModificationToState = !context.anyVotingPeers()
663                 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
664
665         if (applyModificationToState) {
666             context.setCommitIndex(logIndex);
667             applyLogToStateMachine(logIndex);
668         }
669
670         if (replicate.sendImmediate() && !followerToLog.isEmpty()) {
671             sendAppendEntries(0, false);
672         }
673     }
674
675     protected void sendAppendEntries(final long timeSinceLastActivityIntervalNanos, final boolean isHeartbeat) {
676         // Send an AppendEntries to all followers
677         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
678             final String followerId = e.getKey();
679             final FollowerLogInformation followerLogInformation = e.getValue();
680             // This checks helps not to send a repeat message to the follower
681             if (!followerLogInformation.isFollowerActive()
682                     || followerLogInformation.nanosSinceLastActivity() >= timeSinceLastActivityIntervalNanos) {
683                 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
684             }
685         }
686     }
687
688     /**
689      * This method checks if any update needs to be sent to the given follower. This includes append log entries,
690      * sending next snapshot chunk, and initiating a snapshot.
691      */
692     private void sendUpdatesToFollower(final String followerId, final FollowerLogInformation followerLogInformation,
693                                        final boolean sendHeartbeat, final boolean isHeartbeat) {
694
695         ActorSelection followerActor = context.getPeerActorSelection(followerId);
696         if (followerActor != null) {
697             long followerNextIndex = followerLogInformation.getNextIndex();
698             boolean isFollowerActive = followerLogInformation.isFollowerActive();
699             boolean sendAppendEntries = false;
700             List<ReplicatedLogEntry> entries = Collections.emptyList();
701
702             LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
703             if (installSnapshotState != null) {
704
705                 // if install snapshot is in process , then sent next chunk if possible
706                 if (isFollowerActive) {
707                     // 30 seconds with default settings, can be modified via heartbeat or election timeout factor
708                     FiniteDuration snapshotReplyTimeout = context.getConfigParams().getHeartBeatInterval()
709                             .$times(context.getConfigParams().getElectionTimeoutFactor() * 3);
710
711                     if (installSnapshotState.isChunkTimedOut(snapshotReplyTimeout)) {
712                         sendAppendEntries = !resendSnapshotChunk(followerActor, followerLogInformation);
713                     } else if (installSnapshotState.canSendNextChunk()) {
714                         sendSnapshotChunk(followerActor, followerLogInformation);
715                     }
716                 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
717                     // we send a heartbeat even if we have not received a reply for the last chunk
718                     sendAppendEntries = true;
719                 }
720             } else if (followerLogInformation.isLogEntrySlicingInProgress()) {
721                 sendAppendEntries = sendHeartbeat;
722             } else {
723                 long leaderLastIndex = context.getReplicatedLog().lastIndex();
724                 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
725
726                 if (!isHeartbeat && log.isDebugEnabled() || log.isTraceEnabled()) {
727                     log.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, "
728                             + "leaderLastIndex: {}, leaderSnapShotIndex: {}", logName(), followerId, isFollowerActive,
729                             followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
730                 }
731
732                 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
733
734                     log.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
735                             followerNextIndex, followerId);
736
737                     if (followerLogInformation.okToReplicate(context.getCommitIndex())) {
738                         entries = getEntriesToSend(followerLogInformation, followerActor);
739                         sendAppendEntries = true;
740                     }
741                 } else if (isFollowerActive && followerNextIndex >= 0
742                         && leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
743                     // if the followers next index is not present in the leaders log, and
744                     // if the follower is just not starting and if leader's index is more than followers index
745                     // then snapshot should be sent
746
747                     // Send heartbeat to follower whenever install snapshot is initiated.
748                     sendAppendEntries = true;
749                     if (canInstallSnapshot(followerNextIndex)) {
750                         log.info("{}: Initiating install snapshot to follower {}: follower nextIndex: {}, leader "
751                                 + "snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(), followerId,
752                                 followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
753                                 context.getReplicatedLog().size());
754
755                         initiateCaptureSnapshot(followerId);
756                     } else {
757                         // It doesn't seem like we should ever reach here - most likely indicates sonething is
758                         // wrong.
759                         log.info("{}: Follower {} is behind but cannot install snapshot: follower nextIndex: {}, "
760                                 + "leader snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(),
761                                 followerId, followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
762                                 context.getReplicatedLog().size());
763                     }
764
765                 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
766                     // we send an AppendEntries, even if the follower is inactive
767                     // in-order to update the followers timestamp, in case it becomes active again
768                     sendAppendEntries = true;
769                 }
770
771             }
772
773             if (sendAppendEntries) {
774                 sendAppendEntriesToFollower(followerActor, entries, followerLogInformation);
775             }
776         }
777     }
778
779     private List<ReplicatedLogEntry> getEntriesToSend(final FollowerLogInformation followerLogInfo,
780             final ActorSelection followerActor) {
781         // Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
782         // message.
783         int maxEntries = (int) context.getReplicatedLog().size();
784         final int maxDataSize = context.getConfigParams().getSnapshotChunkSize();
785         final long followerNextIndex = followerLogInfo.getNextIndex();
786         List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex,
787                 maxEntries, maxDataSize);
788
789         // If the first entry's size exceeds the max data size threshold, it will be returned from the call above. If
790         // that is the case, then we need to slice it into smaller chunks.
791         if (entries.size() != 1 || entries.get(0).getData().serializedSize() <= maxDataSize) {
792             // Don't need to slice.
793             return entries;
794         }
795
796         log.debug("{}: Log entry size {} exceeds max payload size {}", logName(), entries.get(0).getData().size(),
797                 maxDataSize);
798
799         // If an AppendEntries has already been serialized for the log index then reuse the
800         // SharedFileBackedOutputStream.
801         final Long logIndex = entries.get(0).getIndex();
802         SharedFileBackedOutputStream fileBackedStream = sharedSerializedAppendEntriesStreams.get(logIndex);
803         if (fileBackedStream == null) {
804             fileBackedStream = context.getFileBackedOutputStreamFactory().newSharedInstance();
805
806             final AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
807                     getLogEntryIndex(followerNextIndex - 1), getLogEntryTerm(followerNextIndex - 1), entries,
808                     context.getCommitIndex(), getReplicatedToAllIndex(), context.getPayloadVersion());
809
810             log.debug("{}: Serializing {} for slicing for follower {}", logName(), appendEntries,
811                     followerLogInfo.getId());
812
813             try (ObjectOutputStream out = new ObjectOutputStream(fileBackedStream)) {
814                 out.writeObject(appendEntries);
815             } catch (IOException e) {
816                 log.error("{}: Error serializing {}", logName(), appendEntries, e);
817                 fileBackedStream.cleanup();
818                 return Collections.emptyList();
819             }
820
821             sharedSerializedAppendEntriesStreams.put(logIndex, fileBackedStream);
822
823             fileBackedStream.setOnCleanupCallback(index -> {
824                 log.debug("{}: On SharedFileBackedOutputStream cleanup for index {}", logName(), index);
825                 sharedSerializedAppendEntriesStreams.remove(index);
826             }, logIndex);
827         } else {
828             log.debug("{}: Reusing SharedFileBackedOutputStream for follower {}", logName(), followerLogInfo.getId());
829             fileBackedStream.incrementUsageCount();
830         }
831
832         log.debug("{}: Slicing stream for index {}, follower {}", logName(), logIndex, followerLogInfo.getId());
833
834         // Record that slicing is in progress for the follower.
835         followerLogInfo.setSlicedLogEntryIndex(logIndex);
836
837         final FollowerIdentifier identifier = new FollowerIdentifier(followerLogInfo.getId());
838         appendEntriesMessageSlicer.slice(SliceOptions.builder().identifier(identifier)
839                 .fileBackedOutputStream(fileBackedStream).sendTo(followerActor).replyTo(actor())
840                 .onFailureCallback(failure -> {
841                     log.error("{}: Error slicing AppendEntries for follower {}", logName(),
842                             followerLogInfo.getId(), failure);
843                     followerLogInfo.setSlicedLogEntryIndex(FollowerLogInformation.NO_INDEX);
844                 }).build());
845
846         return Collections.emptyList();
847     }
848
849     private void sendAppendEntriesToFollower(final ActorSelection followerActor, final List<ReplicatedLogEntry> entries,
850             final FollowerLogInformation followerLogInformation) {
851         // In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
852         // possibly committing and applying conflicting entries (those with same index, different term) from a prior
853         // term that weren't replicated to a majority, which would be a violation of raft.
854         //     - if the follower isn't active. In this case we don't know the state of the follower and we send an
855         //       empty AppendEntries as a heart beat to prevent election.
856         //     - if we're in the process of installing a snapshot. In this case we don't send any new entries but still
857         //       need to send AppendEntries to prevent election.
858         //     - if we're in the process of slicing an AppendEntries with a large log entry payload. In this case we
859         //       need to send an empty AppendEntries to prevent election.
860         boolean isInstallingSnaphot = followerLogInformation.getInstallSnapshotState() != null;
861         long leaderCommitIndex = isInstallingSnaphot || followerLogInformation.isLogEntrySlicingInProgress()
862                 || !followerLogInformation.isFollowerActive() ? -1 : context.getCommitIndex();
863
864         long followerNextIndex = followerLogInformation.getNextIndex();
865         AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
866             getLogEntryIndex(followerNextIndex - 1),
867             getLogEntryTerm(followerNextIndex - 1), entries,
868             leaderCommitIndex, super.getReplicatedToAllIndex(), context.getPayloadVersion(),
869             followerLogInformation.getRaftVersion(), followerLogInformation.needsLeaderAddress(getId()));
870
871         if (!entries.isEmpty() || log.isTraceEnabled()) {
872             log.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerLogInformation.getId(),
873                     appendEntries);
874         }
875
876         followerLogInformation.setSentCommitIndex(leaderCommitIndex);
877         followerActor.tell(appendEntries, actor());
878     }
879
880     /**
881      * Initiates a snapshot capture to install on a follower.
882      *
883      * <p>
884      * Install Snapshot works as follows
885      *   1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
886      *   2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
887      *      the Leader's handleMessage with a SendInstallSnapshot message.
888      *   3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
889      *      the Follower via InstallSnapshot messages.
890      *   4. For each chunk, the Follower sends back an InstallSnapshotReply.
891      *   5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
892      *      follower.
893      *   6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
894      *      then send the existing snapshot in chunks to the follower.
895      *
896      * @param followerId the id of the follower.
897      * @return true if capture was initiated, false otherwise.
898      */
899     public boolean initiateCaptureSnapshot(final String followerId) {
900         FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
901         if (snapshotHolder.isPresent()) {
902             // If a snapshot is present in the memory, most likely another install is in progress no need to capture
903             // snapshot. This could happen if another follower needs an install when one is going on.
904             final ActorSelection followerActor = context.getPeerActorSelection(followerId);
905
906             // Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
907             sendSnapshotChunk(followerActor, followerLogInfo);
908             return true;
909         }
910
911         boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
912             getReplicatedToAllIndex(), followerId);
913         if (captureInitiated) {
914             followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
915                 context.getConfigParams().getSnapshotChunkSize(), logName()));
916         }
917
918         return captureInitiated;
919     }
920
921     private boolean canInstallSnapshot(final long nextIndex) {
922         // If the follower's nextIndex is -1 then we might as well send it a snapshot
923         // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
924         // in the snapshot
925         return nextIndex == -1 || !context.getReplicatedLog().isPresent(nextIndex)
926                 && context.getReplicatedLog().isInSnapshot(nextIndex);
927
928     }
929
930
931     private void sendInstallSnapshot() {
932         log.debug("{}: sendInstallSnapshot", logName());
933         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
934             String followerId = e.getKey();
935             ActorSelection followerActor = context.getPeerActorSelection(followerId);
936             FollowerLogInformation followerLogInfo = e.getValue();
937
938             if (followerActor != null) {
939                 long nextIndex = followerLogInfo.getNextIndex();
940                 if (followerLogInfo.getInstallSnapshotState() != null
941                         || context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
942                         || canInstallSnapshot(nextIndex)) {
943                     sendSnapshotChunk(followerActor, followerLogInfo);
944                 }
945             }
946         }
947     }
948
949     /**
950      *  Sends a snapshot chunk to a given follower
951      *  InstallSnapshot should qualify as a heartbeat too.
952      */
953     private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) {
954         if (snapshotHolder.isPresent()) {
955             LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
956             if (installSnapshotState == null) {
957                 installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
958                         logName());
959                 followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
960             }
961
962             try {
963                 // Ensure the snapshot bytes are set - this is a no-op.
964                 installSnapshotState.setSnapshotBytes(snapshotHolder.orElseThrow().getSnapshotBytes());
965
966                 if (!installSnapshotState.canSendNextChunk()) {
967                     return;
968                 }
969
970                 byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();
971
972                 log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
973                         nextSnapshotChunk.length);
974
975                 int nextChunkIndex = installSnapshotState.incrementChunkIndex();
976                 Optional<ServerConfigurationPayload> serverConfig = Optional.empty();
977                 if (installSnapshotState.isLastChunk(nextChunkIndex)) {
978                     serverConfig = Optional.ofNullable(context.getPeerServerInfo(true));
979                 }
980
981                 sendSnapshotChunk(followerActor, followerLogInfo, nextSnapshotChunk, nextChunkIndex, serverConfig);
982
983                 log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
984                         installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
985
986             } catch (IOException e) {
987                 log.warn("{}: Unable to send chunk: {}/{}. Reseting snapshot progress. Snapshot state: {}", logName(),
988                         installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks(),
989                         installSnapshotState, e);
990                 installSnapshotState.reset();
991             }
992         }
993     }
994
995     private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo,
996                                    final byte[] snapshotChunk, final int chunkIndex,
997                                    final Optional<ServerConfigurationPayload> serverConfig) {
998         LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
999
1000         installSnapshotState.startChunkTimer();
1001         followerActor.tell(
1002                 new InstallSnapshot(currentTerm(), context.getId(),
1003                         snapshotHolder.orElseThrow().getLastIncludedIndex(),
1004                         snapshotHolder.orElseThrow().getLastIncludedTerm(),
1005                         snapshotChunk,
1006                         chunkIndex,
1007                         installSnapshotState.getTotalChunks(),
1008                         OptionalInt.of(installSnapshotState.getLastChunkHashCode()),
1009                         serverConfig,
1010                         followerLogInfo.getRaftVersion()),
1011                 actor()
1012         );
1013     }
1014
1015     private boolean resendSnapshotChunk(final ActorSelection followerActor,
1016                                         final FollowerLogInformation followerLogInfo) {
1017         if (!snapshotHolder.isPresent()) {
1018             // Seems like we should never hit this case, but just in case we do, reset the snapshot progress so that it
1019             // can restart from the next AppendEntries.
1020             log.warn("{}: Attempting to resend snapshot with no snapshot holder present.", logName());
1021             followerLogInfo.clearLeaderInstallSnapshotState();
1022             return false;
1023         }
1024
1025         LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
1026         // we are resending, timer needs to be reset
1027         installSnapshotState.resetChunkTimer();
1028         installSnapshotState.markSendStatus(false);
1029
1030         sendSnapshotChunk(followerActor, followerLogInfo);
1031
1032         return true;
1033     }
1034
1035     private void sendHeartBeat() {
1036         if (!followerToLog.isEmpty()) {
1037             log.trace("{}: Sending heartbeat", logName());
1038             sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toNanos(), true);
1039
1040             appendEntriesMessageSlicer.checkExpiredSlicedMessageState();
1041         }
1042     }
1043
1044     private void stopHeartBeat() {
1045         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
1046             heartbeatSchedule.cancel();
1047         }
1048     }
1049
1050     private void scheduleHeartBeat(final FiniteDuration interval) {
1051         if (followerToLog.isEmpty()) {
1052             // Optimization - do not bother scheduling a heartbeat as there are
1053             // no followers
1054             return;
1055         }
1056
1057         stopHeartBeat();
1058
1059         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
1060         // message is sent to itself.
1061         // Scheduling the heartbeat only once here because heartbeats do not
1062         // need to be sent if there are other messages being sent to the remote
1063         // actor.
1064         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
1065             interval, context.getActor(), SendHeartBeat.INSTANCE,
1066             context.getActorSystem().dispatcher(), context.getActor());
1067     }
1068
1069     @Override
1070     public void close() {
1071         stopHeartBeat();
1072         appendEntriesMessageSlicer.close();
1073     }
1074
1075     @Override
1076     public final String getLeaderId() {
1077         return context.getId();
1078     }
1079
1080     @Override
1081     public final short getLeaderPayloadVersion() {
1082         return context.getPayloadVersion();
1083     }
1084
1085     protected boolean isLeaderIsolated() {
1086         int minPresent = getMinIsolatedLeaderPeerCount();
1087         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1088             final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
1089             if (peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
1090                 --minPresent;
1091                 if (minPresent == 0) {
1092                     return false;
1093                 }
1094             }
1095         }
1096         return minPresent != 0;
1097     }
1098
1099     // called from example-actor for printing the follower-states
1100     public String printFollowerStates() {
1101         final StringBuilder sb = new StringBuilder();
1102
1103         sb.append('[');
1104         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1105             sb.append('{');
1106             sb.append(followerLogInformation.getId());
1107             sb.append(" state:");
1108             sb.append(followerLogInformation.isFollowerActive());
1109             sb.append("},");
1110         }
1111         sb.append(']');
1112
1113         return sb.toString();
1114     }
1115
1116     @VisibleForTesting
1117     public FollowerLogInformation getFollower(final String followerId) {
1118         return followerToLog.get(followerId);
1119     }
1120
1121     @VisibleForTesting
1122     public int followerLogSize() {
1123         return followerToLog.size();
1124     }
1125
1126     static class SnapshotHolder {
1127         private final long lastIncludedTerm;
1128         private final long lastIncludedIndex;
1129         private final ByteSource snapshotBytes;
1130
1131         SnapshotHolder(final Snapshot snapshot, final ByteSource snapshotBytes) {
1132             lastIncludedTerm = snapshot.getLastAppliedTerm();
1133             lastIncludedIndex = snapshot.getLastAppliedIndex();
1134             this.snapshotBytes = snapshotBytes;
1135         }
1136
1137         long getLastIncludedTerm() {
1138             return lastIncludedTerm;
1139         }
1140
1141         long getLastIncludedIndex() {
1142             return lastIncludedIndex;
1143         }
1144
1145         ByteSource getSnapshotBytes() {
1146             return snapshotBytes;
1147         }
1148     }
1149 }