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