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