Add RaftActorLeadershipTransferCohort and implement transfer in Leader
[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.protobuf.ByteString;
18 import java.io.IOException;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.LinkedList;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import javax.annotation.Nullable;
28 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
29 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
30 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
31 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
32 import org.opendaylight.controller.cluster.raft.PeerInfo;
33 import org.opendaylight.controller.cluster.raft.RaftActorContext;
34 import org.opendaylight.controller.cluster.raft.RaftState;
35 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
36 import org.opendaylight.controller.cluster.raft.Snapshot;
37 import org.opendaylight.controller.cluster.raft.VotingState;
38 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
39 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
40 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
41 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
43 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
45 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
46 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
47 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
48 import scala.concurrent.duration.FiniteDuration;
49
50 /**
51  * The behavior of a RaftActor when it is in the Leader state
52  * <p/>
53  * Leaders:
54  * <ul>
55  * <li> Upon election: send initial empty AppendEntries RPCs
56  * (heartbeat) to each server; repeat during idle periods to
57  * prevent election timeouts (§5.2)
58  * <li> If command received from client: append entry to local log,
59  * respond after entry applied to state machine (§5.3)
60  * <li> If last log index ≥ nextIndex for a follower: send
61  * AppendEntries RPC with log entries starting at nextIndex
62  * <ul>
63  * <li> If successful: update nextIndex and matchIndex for
64  * follower (§5.3)
65  * <li> If AppendEntries fails because of log inconsistency:
66  * decrement nextIndex and retry (§5.3)
67  * </ul>
68  * <li> If there exists an N such that N > commitIndex, a majority
69  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
70  * set commitIndex = N (§5.3, §5.4).
71  */
72 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
73
74     // The index of the first chunk that is sent when installing a snapshot
75     public static final int FIRST_CHUNK_INDEX = 1;
76
77     // The index that the follower should respond with if it needs the install snapshot to be reset
78     public static final int INVALID_CHUNK_INDEX = -1;
79
80     // This would be passed as the hash code of the last chunk when sending the first chunk
81     public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
82
83     private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
84     private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
85
86     private Cancellable heartbeatSchedule = null;
87
88     private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
89
90     private int minReplicationCount;
91
92     private Optional<SnapshotHolder> snapshot;
93
94     public AbstractLeader(RaftActorContext context) {
95         super(context, RaftState.Leader);
96
97         setLeaderPayloadVersion(context.getPayloadVersion());
98
99         for(PeerInfo peerInfo: context.getPeers()) {
100             FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
101             followerToLog.put(peerInfo.getId(), followerLogInformation);
102         }
103
104         leaderId = context.getId();
105
106         LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
107
108         updateMinReplicaCount();
109
110         snapshot = Optional.absent();
111
112         // Immediately schedule a heartbeat
113         // Upon election: send initial empty AppendEntries RPCs
114         // (heartbeat) to each server; repeat during idle periods to
115         // prevent election timeouts (§5.2)
116         sendAppendEntries(0, false);
117
118         // It is important to schedule this heartbeat here
119         scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
120     }
121
122     /**
123      * Return an immutable collection of follower identifiers.
124      *
125      * @return Collection of follower IDs
126      */
127     public final Collection<String> getFollowerIds() {
128         return followerToLog.keySet();
129     }
130
131     public void addFollower(String followerId) {
132         FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
133                 context.getPeerInfo(followerId), -1, context);
134         followerToLog.put(followerId, followerLogInformation);
135
136         if(heartbeatSchedule == null) {
137             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
138         }
139     }
140
141     public void removeFollower(String followerId) {
142         followerToLog.remove(followerId);
143     }
144
145     public void updateMinReplicaCount() {
146         int numVoting = 0;
147         for(PeerInfo peer: context.getPeers()) {
148             if(peer.isVoting()) {
149                 numVoting++;
150             }
151         }
152
153         minReplicationCount = getMajorityVoteCount(numVoting);
154     }
155
156     protected int getMinIsolatedLeaderPeerCount(){
157       //the isolated Leader peer count will be 1 less than the majority vote count.
158         //this is because the vote count has the self vote counted in it
159         //for e.g
160         //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
161         //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
162         //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
163
164         return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
165     }
166
167     @VisibleForTesting
168     void setSnapshot(@Nullable Snapshot snapshot) {
169         if(snapshot != null) {
170             this.snapshot = Optional.of(new SnapshotHolder(snapshot));
171         } else {
172             this.snapshot = Optional.absent();
173         }
174     }
175
176     @Override
177     protected RaftActorBehavior handleAppendEntries(ActorRef sender,
178         AppendEntries appendEntries) {
179
180         LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
181
182         return this;
183     }
184
185     @Override
186     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
187         AppendEntriesReply appendEntriesReply) {
188
189         if(LOG.isTraceEnabled()) {
190             LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
191         }
192
193         // Update the FollowerLogInformation
194         String followerId = appendEntriesReply.getFollowerId();
195         FollowerLogInformation followerLogInformation =
196             followerToLog.get(followerId);
197
198         if(followerLogInformation == null){
199             LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
200             return this;
201         }
202
203         if(followerLogInformation.timeSinceLastActivity() >
204                 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
205             LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
206                             "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
207                     logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
208                     context.getLastApplied(), context.getCommitIndex());
209         }
210
211         followerLogInformation.markFollowerActive();
212         followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
213
214         boolean updated = false;
215         if (appendEntriesReply.isSuccess()) {
216             updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
217         } else {
218             LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
219
220             long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
221             ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
222             if(appendEntriesReply.isForceInstallSnapshot()) {
223                 // Reset the followers match and next index. This is to signal that this follower has nothing
224                 // in common with this Leader and so would require a snapshot to be installed
225                 followerLogInformation.setMatchIndex(-1);
226                 followerLogInformation.setNextIndex(-1);
227
228                 // Force initiate a snapshot capture
229                 initiateCaptureSnapshot(followerId);
230             } else if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
231                     followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
232                 // The follower's log is empty or the last entry is present in the leader's journal
233                 // and the terms match so the follower is just behind the leader's journal from
234                 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
235                 // follower's last log index.
236
237                 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
238             } else {
239                 // TODO: When we find that the follower is out of sync with the
240                 // Leader we simply decrement that followers next index by 1.
241                 // Would it be possible to do better than this? The RAFT spec
242                 // does not explicitly deal with it but may be something for us to
243                 // think about.
244
245                 followerLogInformation.decrNextIndex();
246             }
247         }
248
249         // Now figure out if this reply warrants a change in the commitIndex
250         // If there exists an N such that N > commitIndex, a majority
251         // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
252         // set commitIndex = N (§5.3, §5.4).
253         for (long N = context.getCommitIndex() + 1; ; N++) {
254             int replicatedCount = 1;
255
256             for (FollowerLogInformation info : followerToLog.values()) {
257                 if ((info.getMatchIndex() >= N) && (context.getPeerInfo(followerId).isVoting())) {
258                     replicatedCount++;
259                 }
260             }
261
262             if (replicatedCount >= minReplicationCount) {
263                 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
264                 if (replicatedLogEntry != null && replicatedLogEntry.getTerm() == currentTerm()) {
265                     context.setCommitIndex(N);
266                 } else {
267                     break;
268                 }
269             } else {
270                 break;
271             }
272         }
273
274         // Apply the change to the state machine
275         if (context.getCommitIndex() > context.getLastApplied()) {
276             if(LOG.isDebugEnabled()) {
277                 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
278                         logName(), followerId, context.getCommitIndex(), context.getLastApplied());
279             }
280
281             applyLogToStateMachine(context.getCommitIndex());
282         }
283
284         if (!context.getSnapshotManager().isCapturing()) {
285             purgeInMemoryLog();
286         }
287
288         //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
289         sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
290         return this;
291     }
292
293     private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
294             AppendEntriesReply appendEntriesReply) {
295         boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
296         updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
297
298         if(updated && LOG.isDebugEnabled()) {
299             LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
300                     logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
301                     followerLogInformation.getNextIndex());
302         }
303         return updated;
304     }
305
306     private void purgeInMemoryLog() {
307         //find the lowest index across followers which has been replicated to all.
308         // lastApplied if there are no followers, so that we keep clearing the log for single-node
309         // we would delete the in-mem log from that index on, in-order to minimize mem usage
310         // we would also share this info thru AE with the followers so that they can delete their log entries as well.
311         long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
312         for (FollowerLogInformation info : followerToLog.values()) {
313             minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
314         }
315
316         super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
317     }
318
319     @Override
320     protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
321         final Iterator<ClientRequestTracker> it = trackerList.iterator();
322         while (it.hasNext()) {
323             final ClientRequestTracker t = it.next();
324             if (t.getIndex() == logIndex) {
325                 it.remove();
326                 return t;
327             }
328         }
329
330         return null;
331     }
332
333     @Override
334     protected ClientRequestTracker findClientRequestTracker(long logIndex) {
335         for (ClientRequestTracker tracker : trackerList) {
336             if (tracker.getIndex() == logIndex) {
337                 return tracker;
338             }
339         }
340         return null;
341     }
342
343     @Override
344     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
345         RequestVoteReply requestVoteReply) {
346         return this;
347     }
348
349     protected void beforeSendHeartbeat(){}
350
351     @Override
352     public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
353         Preconditions.checkNotNull(sender, "sender should not be null");
354
355         Object message = fromSerializableMessage(originalMessage);
356
357         if (message instanceof RaftRPC) {
358             RaftRPC rpc = (RaftRPC) message;
359             // If RPC request or response contains term T > currentTerm:
360             // set currentTerm = T, convert to follower (§5.1)
361             // This applies to all RPC messages and responses
362             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
363                 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
364                         logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
365
366                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
367
368                 return internalSwitchBehavior(RaftState.Follower);
369             }
370         }
371
372         if (message instanceof SendHeartBeat) {
373             beforeSendHeartbeat();
374             sendHeartBeat();
375             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
376             return this;
377
378         } else if(message instanceof SendInstallSnapshot) {
379             // received from RaftActor
380             setSnapshot(((SendInstallSnapshot) message).getSnapshot());
381             sendInstallSnapshot();
382
383         } else if (message instanceof Replicate) {
384             replicate((Replicate) message);
385
386         } else if (message instanceof InstallSnapshotReply){
387             handleInstallSnapshotReply((InstallSnapshotReply) message);
388
389         }
390
391
392         return super.handleMessage(sender, message);
393     }
394
395     private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
396         LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
397
398         String followerId = reply.getFollowerId();
399         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
400
401         if (followerToSnapshot == null) {
402             LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
403                     logName(), followerId);
404             return;
405         }
406
407         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
408         if(followerLogInformation == null) {
409             // This can happen during AddServer if it times out.
410             LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
411                     logName(), followerId);
412             mapFollowerToSnapshot.remove(followerId);
413             return;
414         }
415
416         followerLogInformation.markFollowerActive();
417
418         if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
419             boolean wasLastChunk = false;
420             if (reply.isSuccess()) {
421                 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
422                     //this was the last chunk reply
423                     if(LOG.isDebugEnabled()) {
424                         LOG.debug("{}: InstallSnapshotReply received, " +
425                                 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
426                                 logName(), reply.getChunkIndex(), followerId,
427                             context.getReplicatedLog().getSnapshotIndex() + 1
428                         );
429                     }
430
431                     long followerMatchIndex = snapshot.get().getLastIncludedIndex();
432                     followerLogInformation.setMatchIndex(followerMatchIndex);
433                     followerLogInformation.setNextIndex(followerMatchIndex + 1);
434                     mapFollowerToSnapshot.remove(followerId);
435
436                     LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
437                         logName(), followerId, followerLogInformation.getMatchIndex(),
438                         followerLogInformation.getNextIndex());
439
440                     if (mapFollowerToSnapshot.isEmpty()) {
441                         // once there are no pending followers receiving snapshots
442                         // we can remove snapshot from the memory
443                         setSnapshot(null);
444                     }
445                     wasLastChunk = true;
446                     if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
447                         UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
448                                              new UnInitializedFollowerSnapshotReply(followerId);
449                         context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
450                         LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
451                     }
452                 } else {
453                     followerToSnapshot.markSendStatus(true);
454                 }
455             } else {
456                 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
457                         logName(), reply.getChunkIndex());
458
459                 followerToSnapshot.markSendStatus(false);
460             }
461
462             if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
463                 // Since the follower is now caught up try to purge the log.
464                 purgeInMemoryLog();
465             } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
466                 ActorSelection followerActor = context.getPeerActorSelection(followerId);
467                 if(followerActor != null) {
468                     sendSnapshotChunk(followerActor, followerId);
469                 }
470             }
471
472         } else {
473             LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
474                     logName(), reply.getChunkIndex(), followerId,
475                     followerToSnapshot.getChunkIndex());
476
477             if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
478                 // Since the Follower did not find this index to be valid we should reset the follower snapshot
479                 // so that Installing the snapshot can resume from the beginning
480                 followerToSnapshot.reset();
481             }
482         }
483     }
484
485     private void replicate(Replicate replicate) {
486         long logIndex = replicate.getReplicatedLogEntry().getIndex();
487
488         LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
489                 replicate.getIdentifier(), logIndex);
490
491         // Create a tracker entry we will use this later to notify the
492         // client actor
493         trackerList.add(
494             new ClientRequestTrackerImpl(replicate.getClientActor(),
495                 replicate.getIdentifier(),
496                 logIndex)
497         );
498
499         boolean applyModificationToState = followerToLog.isEmpty()
500                 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
501
502         if(applyModificationToState){
503             context.setCommitIndex(logIndex);
504             applyLogToStateMachine(logIndex);
505         }
506
507         if (!followerToLog.isEmpty()) {
508             sendAppendEntries(0, false);
509         }
510     }
511
512     protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
513         // Send an AppendEntries to all followers
514         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
515             final String followerId = e.getKey();
516             final FollowerLogInformation followerLogInformation = e.getValue();
517             // This checks helps not to send a repeat message to the follower
518             if(!followerLogInformation.isFollowerActive() ||
519                     followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
520                 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
521             }
522         }
523     }
524
525     /**
526      *
527      * This method checks if any update needs to be sent to the given follower. This includes append log entries,
528      * sending next snapshot chunk, and initiating a snapshot.
529      * @return true if any update is sent, false otherwise
530      */
531
532     private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
533                                        boolean sendHeartbeat, boolean isHeartbeat) {
534
535         ActorSelection followerActor = context.getPeerActorSelection(followerId);
536         if (followerActor != null) {
537             long followerNextIndex = followerLogInformation.getNextIndex();
538             boolean isFollowerActive = followerLogInformation.isFollowerActive();
539             boolean sendAppendEntries = false;
540             List<ReplicatedLogEntry> entries = Collections.emptyList();
541
542             if (mapFollowerToSnapshot.get(followerId) != null) {
543                 // if install snapshot is in process , then sent next chunk if possible
544                 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
545                     sendSnapshotChunk(followerActor, followerId);
546                 } else if(sendHeartbeat) {
547                     // we send a heartbeat even if we have not received a reply for the last chunk
548                     sendAppendEntries = true;
549                 }
550             } else {
551                 long leaderLastIndex = context.getReplicatedLog().lastIndex();
552                 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
553
554                 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
555                     LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
556                             logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
557                 }
558
559                 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
560
561                     LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
562                             followerNextIndex, followerId);
563
564                     if(followerLogInformation.okToReplicate()) {
565                         // Try to send all the entries in the journal but not exceeding the max data size
566                         // for a single AppendEntries message.
567                         int maxEntries = (int) context.getReplicatedLog().size();
568                         entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
569                                 context.getConfigParams().getSnapshotChunkSize());
570                         sendAppendEntries = true;
571                     }
572                 } else if (isFollowerActive && followerNextIndex >= 0 &&
573                     leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
574                     // if the followers next index is not present in the leaders log, and
575                     // if the follower is just not starting and if leader's index is more than followers index
576                     // then snapshot should be sent
577
578                     if (LOG.isDebugEnabled()) {
579                         LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
580                                     "follower-nextIndex: %d, leader-snapshot-index: %d,  " +
581                                     "leader-last-index: %d", logName(), followerId,
582                                     followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
583                     }
584
585                     // Send heartbeat to follower whenever install snapshot is initiated.
586                     sendAppendEntries = true;
587                     if (canInstallSnapshot(followerNextIndex)) {
588                         initiateCaptureSnapshot(followerId);
589                     }
590
591                 } else if(sendHeartbeat) {
592                     // we send an AppendEntries, even if the follower is inactive
593                     // in-order to update the followers timestamp, in case it becomes active again
594                     sendAppendEntries = true;
595                 }
596
597             }
598
599             if(sendAppendEntries) {
600                 sendAppendEntriesToFollower(followerActor, followerNextIndex,
601                         entries, followerId);
602             }
603         }
604     }
605
606     private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
607         List<ReplicatedLogEntry> entries, String followerId) {
608         AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
609             prevLogIndex(followerNextIndex),
610             prevLogTerm(followerNextIndex), entries,
611             context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
612
613         if(!entries.isEmpty() || LOG.isTraceEnabled()) {
614             LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
615                     appendEntries);
616         }
617
618         followerActor.tell(appendEntries.toSerializable(), actor());
619     }
620
621     /**
622      * Install Snapshot works as follows
623      * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
624      * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
625      * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
626      * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
627      * 4. On complete, Follower sends back a InstallSnapshotReply.
628      * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
629      * and replenishes the memory by deleting the snapshot in Replicated log.
630      * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
631      * then send the existing snapshot in chunks to the follower.
632      * @param followerId
633      */
634     public boolean initiateCaptureSnapshot(String followerId) {
635         if (snapshot.isPresent()) {
636             // if a snapshot is present in the memory, most likely another install is in progress
637             // no need to capture snapshot.
638             // This could happen if another follower needs an install when one is going on.
639             final ActorSelection followerActor = context.getPeerActorSelection(followerId);
640             sendSnapshotChunk(followerActor, followerId);
641             return true;
642         } else {
643             return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
644                     this.getReplicatedToAllIndex(), followerId);
645         }
646     }
647
648     private boolean canInstallSnapshot(long nextIndex){
649         // If the follower's nextIndex is -1 then we might as well send it a snapshot
650         // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
651         // in the snapshot
652         return (nextIndex == -1 ||
653                 (!context.getReplicatedLog().isPresent(nextIndex)
654                         && context.getReplicatedLog().isInSnapshot(nextIndex)));
655
656     }
657
658
659     private void sendInstallSnapshot() {
660         LOG.debug("{}: sendInstallSnapshot", logName());
661         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
662             String followerId = e.getKey();
663             ActorSelection followerActor = context.getPeerActorSelection(followerId);
664             FollowerLogInformation followerLogInfo = e.getValue();
665
666             if (followerActor != null) {
667                 long nextIndex = followerLogInfo.getNextIndex();
668                 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
669                         canInstallSnapshot(nextIndex)) {
670                     sendSnapshotChunk(followerActor, followerId);
671                 }
672             }
673         }
674     }
675
676     /**
677      *  Sends a snapshot chunk to a given follower
678      *  InstallSnapshot should qualify as a heartbeat too.
679      */
680     private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
681         try {
682             if (snapshot.isPresent()) {
683                 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
684
685                 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
686                 // followerId to the followerToSnapshot map.
687                 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
688
689                 followerActor.tell(
690                     new InstallSnapshot(currentTerm(), context.getId(),
691                         snapshot.get().getLastIncludedIndex(),
692                         snapshot.get().getLastIncludedTerm(),
693                         nextSnapshotChunk,
694                         followerToSnapshot.incrementChunkIndex(),
695                         followerToSnapshot.getTotalChunks(),
696                         Optional.of(followerToSnapshot.getLastChunkHashCode())
697                     ).toSerializable(),
698                     actor()
699                 );
700
701                 if(LOG.isDebugEnabled()) {
702                     LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
703                             logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
704                             followerToSnapshot.getTotalChunks());
705                 }
706             }
707         } catch (IOException e) {
708             LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
709         }
710     }
711
712     /**
713      * Acccepts snaphot as ByteString, enters into map for future chunks
714      * creates and return a ByteString chunk
715      */
716     private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
717         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
718         if (followerToSnapshot == null) {
719             followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
720             mapFollowerToSnapshot.put(followerId, followerToSnapshot);
721         }
722         ByteString nextChunk = followerToSnapshot.getNextChunk();
723
724         LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
725
726         return nextChunk;
727     }
728
729     private void sendHeartBeat() {
730         if (!followerToLog.isEmpty()) {
731             LOG.trace("{}: Sending heartbeat", logName());
732             sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
733         }
734     }
735
736     private void stopHeartBeat() {
737         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
738             heartbeatSchedule.cancel();
739         }
740     }
741
742     private void scheduleHeartBeat(FiniteDuration interval) {
743         if (followerToLog.isEmpty()) {
744             // Optimization - do not bother scheduling a heartbeat as there are
745             // no followers
746             return;
747         }
748
749         stopHeartBeat();
750
751         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
752         // message is sent to itself.
753         // Scheduling the heartbeat only once here because heartbeats do not
754         // need to be sent if there are other messages being sent to the remote
755         // actor.
756         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
757             interval, context.getActor(), new SendHeartBeat(),
758             context.getActorSystem().dispatcher(), context.getActor());
759     }
760
761     @Override
762     public void close() throws Exception {
763         stopHeartBeat();
764     }
765
766     @Override
767     public String getLeaderId() {
768         return context.getId();
769     }
770
771     protected boolean isLeaderIsolated() {
772         int minPresent = getMinIsolatedLeaderPeerCount();
773         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
774             if (followerLogInformation.isFollowerActive()) {
775                 --minPresent;
776                 if (minPresent == 0) {
777                     break;
778                 }
779             }
780         }
781         return (minPresent != 0);
782     }
783
784     /**
785      * Encapsulates the snapshot bytestring and handles the logic of sending
786      * snapshot chunks
787      */
788     protected class FollowerToSnapshot {
789         private final ByteString snapshotBytes;
790         private int offset = 0;
791         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
792         private int replyReceivedForOffset;
793         // if replyStatus is false, the previous chunk is attempted
794         private boolean replyStatus = false;
795         private int chunkIndex;
796         private final int totalChunks;
797         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
798         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
799
800         public FollowerToSnapshot(ByteString snapshotBytes) {
801             this.snapshotBytes = snapshotBytes;
802             int size = snapshotBytes.size();
803             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
804                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
805             if(LOG.isDebugEnabled()) {
806                 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
807                         logName(), size, totalChunks);
808             }
809             replyReceivedForOffset = -1;
810             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
811         }
812
813         public ByteString getSnapshotBytes() {
814             return snapshotBytes;
815         }
816
817         public int incrementOffset() {
818             if(replyStatus) {
819                 // if prev chunk failed, we would want to sent the same chunk again
820                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
821             }
822             return offset;
823         }
824
825         public int incrementChunkIndex() {
826             if (replyStatus) {
827                 // if prev chunk failed, we would want to sent the same chunk again
828                 chunkIndex =  chunkIndex + 1;
829             }
830             return chunkIndex;
831         }
832
833         public int getChunkIndex() {
834             return chunkIndex;
835         }
836
837         public int getTotalChunks() {
838             return totalChunks;
839         }
840
841         public boolean canSendNextChunk() {
842             // we only send a false if a chunk is sent but we have not received a reply yet
843             return replyReceivedForOffset == offset;
844         }
845
846         public boolean isLastChunk(int chunkIndex) {
847             return totalChunks == chunkIndex;
848         }
849
850         public void markSendStatus(boolean success) {
851             if (success) {
852                 // if the chunk sent was successful
853                 replyReceivedForOffset = offset;
854                 replyStatus = true;
855                 lastChunkHashCode = nextChunkHashCode;
856             } else {
857                 // if the chunk sent was failure
858                 replyReceivedForOffset = offset;
859                 replyStatus = false;
860             }
861         }
862
863         public ByteString getNextChunk() {
864             int snapshotLength = getSnapshotBytes().size();
865             int start = incrementOffset();
866             int size = context.getConfigParams().getSnapshotChunkSize();
867             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
868                 size = snapshotLength;
869             } else {
870                 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
871                     size = snapshotLength - start;
872                 }
873             }
874
875
876             LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
877                     snapshotLength, start, size);
878
879             ByteString substring = getSnapshotBytes().substring(start, start + size);
880             nextChunkHashCode = substring.hashCode();
881             return substring;
882         }
883
884         /**
885          * reset should be called when the Follower needs to be sent the snapshot from the beginning
886          */
887         public void reset(){
888             offset = 0;
889             replyStatus = false;
890             replyReceivedForOffset = offset;
891             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
892             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
893         }
894
895         public int getLastChunkHashCode() {
896             return lastChunkHashCode;
897         }
898     }
899
900     // called from example-actor for printing the follower-states
901     public String printFollowerStates() {
902         final StringBuilder sb = new StringBuilder();
903
904         sb.append('[');
905         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
906             sb.append('{');
907             sb.append(followerLogInformation.getId());
908             sb.append(" state:");
909             sb.append(followerLogInformation.isFollowerActive());
910             sb.append("},");
911         }
912         sb.append(']');
913
914         return sb.toString();
915     }
916
917     @VisibleForTesting
918     public FollowerLogInformation getFollower(String followerId) {
919         return followerToLog.get(followerId);
920     }
921
922     @VisibleForTesting
923     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
924         mapFollowerToSnapshot.put(followerId, snapshot);
925     }
926
927     @VisibleForTesting
928     public int followerSnapshotSize() {
929         return mapFollowerToSnapshot.size();
930     }
931
932     @VisibleForTesting
933     public int followerLogSize() {
934         return followerToLog.size();
935     }
936
937     private static class SnapshotHolder {
938         private final long lastIncludedTerm;
939         private final long lastIncludedIndex;
940         private final ByteString snapshotBytes;
941
942         SnapshotHolder(Snapshot snapshot) {
943             this.lastIncludedTerm = snapshot.getLastAppliedTerm();
944             this.lastIncludedIndex = snapshot.getLastAppliedIndex();
945             this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
946         }
947
948         long getLastIncludedTerm() {
949             return lastIncludedTerm;
950         }
951
952         long getLastIncludedIndex() {
953             return lastIncludedIndex;
954         }
955
956         ByteString getSnapshotBytes() {
957             return snapshotBytes;
958         }
959     }
960 }