Introduce PeerInfo and VotingState
[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) {
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("{}: FollowerId {} in InstallSnapshotReply not known to Leader",
403                     logName(), followerId);
404             return;
405         }
406
407         FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
408         followerLogInformation.markFollowerActive();
409
410         if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
411             boolean wasLastChunk = false;
412             if (reply.isSuccess()) {
413                 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
414                     //this was the last chunk reply
415                     if(LOG.isDebugEnabled()) {
416                         LOG.debug("{}: InstallSnapshotReply received, " +
417                                 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
418                                 logName(), reply.getChunkIndex(), followerId,
419                             context.getReplicatedLog().getSnapshotIndex() + 1
420                         );
421                     }
422
423                     long followerMatchIndex = snapshot.get().getLastIncludedIndex();
424                     followerLogInformation.setMatchIndex(followerMatchIndex);
425                     followerLogInformation.setNextIndex(followerMatchIndex + 1);
426                     mapFollowerToSnapshot.remove(followerId);
427
428                     LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
429                         logName(), followerId, followerLogInformation.getMatchIndex(),
430                         followerLogInformation.getNextIndex());
431
432                     if (mapFollowerToSnapshot.isEmpty()) {
433                         // once there are no pending followers receiving snapshots
434                         // we can remove snapshot from the memory
435                         setSnapshot(null);
436                     }
437                     wasLastChunk = true;
438                     if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
439                         UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
440                                              new UnInitializedFollowerSnapshotReply(followerId);
441                         context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
442                         LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
443                     }
444                 } else {
445                     followerToSnapshot.markSendStatus(true);
446                 }
447             } else {
448                 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
449                         logName(), reply.getChunkIndex());
450
451                 followerToSnapshot.markSendStatus(false);
452             }
453
454             if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
455                 // Since the follower is now caught up try to purge the log.
456                 purgeInMemoryLog();
457             } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
458                 ActorSelection followerActor = context.getPeerActorSelection(followerId);
459                 if(followerActor != null) {
460                     sendSnapshotChunk(followerActor, followerId);
461                 }
462             }
463
464         } else {
465             LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
466                     logName(), reply.getChunkIndex(), followerId,
467                     followerToSnapshot.getChunkIndex());
468
469             if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
470                 // Since the Follower did not find this index to be valid we should reset the follower snapshot
471                 // so that Installing the snapshot can resume from the beginning
472                 followerToSnapshot.reset();
473             }
474         }
475     }
476
477     private void replicate(Replicate replicate) {
478         long logIndex = replicate.getReplicatedLogEntry().getIndex();
479
480         LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
481                 replicate.getIdentifier(), logIndex);
482
483         // Create a tracker entry we will use this later to notify the
484         // client actor
485         trackerList.add(
486             new ClientRequestTrackerImpl(replicate.getClientActor(),
487                 replicate.getIdentifier(),
488                 logIndex)
489         );
490
491         boolean applyModificationToState = followerToLog.isEmpty()
492                 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
493
494         if(applyModificationToState){
495             context.setCommitIndex(logIndex);
496             applyLogToStateMachine(logIndex);
497         }
498
499         if (!followerToLog.isEmpty()) {
500             sendAppendEntries(0, false);
501         }
502     }
503
504     private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
505         // Send an AppendEntries to all followers
506         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
507             final String followerId = e.getKey();
508             final FollowerLogInformation followerLogInformation = e.getValue();
509             // This checks helps not to send a repeat message to the follower
510             if(!followerLogInformation.isFollowerActive() ||
511                     followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
512                 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
513             }
514         }
515     }
516
517     /**
518      *
519      * This method checks if any update needs to be sent to the given follower. This includes append log entries,
520      * sending next snapshot chunk, and initiating a snapshot.
521      * @return true if any update is sent, false otherwise
522      */
523
524     private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
525                                        boolean sendHeartbeat, boolean isHeartbeat) {
526
527         ActorSelection followerActor = context.getPeerActorSelection(followerId);
528         if (followerActor != null) {
529             long followerNextIndex = followerLogInformation.getNextIndex();
530             boolean isFollowerActive = followerLogInformation.isFollowerActive();
531             boolean sendAppendEntries = false;
532             List<ReplicatedLogEntry> entries = Collections.emptyList();
533
534             if (mapFollowerToSnapshot.get(followerId) != null) {
535                 // if install snapshot is in process , then sent next chunk if possible
536                 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
537                     sendSnapshotChunk(followerActor, followerId);
538                 } else if(sendHeartbeat) {
539                     // we send a heartbeat even if we have not received a reply for the last chunk
540                     sendAppendEntries = true;
541                 }
542             } else {
543                 long leaderLastIndex = context.getReplicatedLog().lastIndex();
544                 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
545
546                 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
547                     LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
548                             logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
549                 }
550
551                 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
552
553                     LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
554                             followerNextIndex, followerId);
555
556                     if(followerLogInformation.okToReplicate()) {
557                         // Try to send all the entries in the journal but not exceeding the max data size
558                         // for a single AppendEntries message.
559                         int maxEntries = (int) context.getReplicatedLog().size();
560                         entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
561                                 context.getConfigParams().getSnapshotChunkSize());
562                         sendAppendEntries = true;
563                     }
564                 } else if (isFollowerActive && followerNextIndex >= 0 &&
565                     leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
566                     // if the followers next index is not present in the leaders log, and
567                     // if the follower is just not starting and if leader's index is more than followers index
568                     // then snapshot should be sent
569
570                     if (LOG.isDebugEnabled()) {
571                         LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
572                                     "follower-nextIndex: %d, leader-snapshot-index: %d,  " +
573                                     "leader-last-index: %d", logName(), followerId,
574                                     followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
575                     }
576
577                     // Send heartbeat to follower whenever install snapshot is initiated.
578                     sendAppendEntries = true;
579                     if (canInstallSnapshot(followerNextIndex)) {
580                         initiateCaptureSnapshot(followerId);
581                     }
582
583                 } else if(sendHeartbeat) {
584                     // we send an AppendEntries, even if the follower is inactive
585                     // in-order to update the followers timestamp, in case it becomes active again
586                     sendAppendEntries = true;
587                 }
588
589             }
590
591             if(sendAppendEntries) {
592                 sendAppendEntriesToFollower(followerActor, followerNextIndex,
593                         entries, followerId);
594             }
595         }
596     }
597
598     private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
599         List<ReplicatedLogEntry> entries, String followerId) {
600         AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
601             prevLogIndex(followerNextIndex),
602             prevLogTerm(followerNextIndex), entries,
603             context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
604
605         if(!entries.isEmpty() || LOG.isTraceEnabled()) {
606             LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
607                     appendEntries);
608         }
609
610         followerActor.tell(appendEntries.toSerializable(), actor());
611     }
612
613     /**
614      * Install Snapshot works as follows
615      * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
616      * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
617      * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
618      * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
619      * 4. On complete, Follower sends back a InstallSnapshotReply.
620      * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
621      * and replenishes the memory by deleting the snapshot in Replicated log.
622      * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
623      * then send the existing snapshot in chunks to the follower.
624      * @param followerId
625      */
626     public void initiateCaptureSnapshot(String followerId) {
627         if (snapshot.isPresent()) {
628             // if a snapshot is present in the memory, most likely another install is in progress
629             // no need to capture snapshot.
630             // This could happen if another follower needs an install when one is going on.
631             final ActorSelection followerActor = context.getPeerActorSelection(followerId);
632             sendSnapshotChunk(followerActor, followerId);
633
634
635         } else {
636             context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
637                     this.getReplicatedToAllIndex(), followerId);
638         }
639     }
640
641     private boolean canInstallSnapshot(long nextIndex){
642         // If the follower's nextIndex is -1 then we might as well send it a snapshot
643         // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
644         // in the snapshot
645         return (nextIndex == -1 ||
646                 (!context.getReplicatedLog().isPresent(nextIndex)
647                         && context.getReplicatedLog().isInSnapshot(nextIndex)));
648
649     }
650
651
652     private void sendInstallSnapshot() {
653         LOG.debug("{}: sendInstallSnapshot", logName());
654         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
655             String followerId = e.getKey();
656             ActorSelection followerActor = context.getPeerActorSelection(followerId);
657             FollowerLogInformation followerLogInfo = e.getValue();
658
659             if (followerActor != null) {
660                 long nextIndex = followerLogInfo.getNextIndex();
661                 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
662                         canInstallSnapshot(nextIndex)) {
663                     sendSnapshotChunk(followerActor, followerId);
664                 }
665             }
666         }
667     }
668
669     /**
670      *  Sends a snapshot chunk to a given follower
671      *  InstallSnapshot should qualify as a heartbeat too.
672      */
673     private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
674         try {
675             if (snapshot.isPresent()) {
676                 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
677
678                 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
679                 // followerId to the followerToSnapshot map.
680                 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
681
682                 followerActor.tell(
683                     new InstallSnapshot(currentTerm(), context.getId(),
684                         snapshot.get().getLastIncludedIndex(),
685                         snapshot.get().getLastIncludedTerm(),
686                         nextSnapshotChunk,
687                         followerToSnapshot.incrementChunkIndex(),
688                         followerToSnapshot.getTotalChunks(),
689                         Optional.of(followerToSnapshot.getLastChunkHashCode())
690                     ).toSerializable(),
691                     actor()
692                 );
693
694                 if(LOG.isDebugEnabled()) {
695                     LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
696                             logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
697                             followerToSnapshot.getTotalChunks());
698                 }
699             }
700         } catch (IOException e) {
701             LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
702         }
703     }
704
705     /**
706      * Acccepts snaphot as ByteString, enters into map for future chunks
707      * creates and return a ByteString chunk
708      */
709     private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
710         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
711         if (followerToSnapshot == null) {
712             followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
713             mapFollowerToSnapshot.put(followerId, followerToSnapshot);
714         }
715         ByteString nextChunk = followerToSnapshot.getNextChunk();
716
717         LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
718
719         return nextChunk;
720     }
721
722     private void sendHeartBeat() {
723         if (!followerToLog.isEmpty()) {
724             LOG.trace("{}: Sending heartbeat", logName());
725             sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
726         }
727     }
728
729     private void stopHeartBeat() {
730         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
731             heartbeatSchedule.cancel();
732         }
733     }
734
735     private void scheduleHeartBeat(FiniteDuration interval) {
736         if (followerToLog.isEmpty()) {
737             // Optimization - do not bother scheduling a heartbeat as there are
738             // no followers
739             return;
740         }
741
742         stopHeartBeat();
743
744         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
745         // message is sent to itself.
746         // Scheduling the heartbeat only once here because heartbeats do not
747         // need to be sent if there are other messages being sent to the remote
748         // actor.
749         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
750             interval, context.getActor(), new SendHeartBeat(),
751             context.getActorSystem().dispatcher(), context.getActor());
752     }
753
754     @Override
755     public void close() throws Exception {
756         stopHeartBeat();
757     }
758
759     @Override
760     public String getLeaderId() {
761         return context.getId();
762     }
763
764     protected boolean isLeaderIsolated() {
765         int minPresent = getMinIsolatedLeaderPeerCount();
766         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
767             if (followerLogInformation.isFollowerActive()) {
768                 --minPresent;
769                 if (minPresent == 0) {
770                     break;
771                 }
772             }
773         }
774         return (minPresent != 0);
775     }
776
777     /**
778      * Encapsulates the snapshot bytestring and handles the logic of sending
779      * snapshot chunks
780      */
781     protected class FollowerToSnapshot {
782         private final ByteString snapshotBytes;
783         private int offset = 0;
784         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
785         private int replyReceivedForOffset;
786         // if replyStatus is false, the previous chunk is attempted
787         private boolean replyStatus = false;
788         private int chunkIndex;
789         private final int totalChunks;
790         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
791         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
792
793         public FollowerToSnapshot(ByteString snapshotBytes) {
794             this.snapshotBytes = snapshotBytes;
795             int size = snapshotBytes.size();
796             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
797                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
798             if(LOG.isDebugEnabled()) {
799                 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
800                         logName(), size, totalChunks);
801             }
802             replyReceivedForOffset = -1;
803             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
804         }
805
806         public ByteString getSnapshotBytes() {
807             return snapshotBytes;
808         }
809
810         public int incrementOffset() {
811             if(replyStatus) {
812                 // if prev chunk failed, we would want to sent the same chunk again
813                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
814             }
815             return offset;
816         }
817
818         public int incrementChunkIndex() {
819             if (replyStatus) {
820                 // if prev chunk failed, we would want to sent the same chunk again
821                 chunkIndex =  chunkIndex + 1;
822             }
823             return chunkIndex;
824         }
825
826         public int getChunkIndex() {
827             return chunkIndex;
828         }
829
830         public int getTotalChunks() {
831             return totalChunks;
832         }
833
834         public boolean canSendNextChunk() {
835             // we only send a false if a chunk is sent but we have not received a reply yet
836             return replyReceivedForOffset == offset;
837         }
838
839         public boolean isLastChunk(int chunkIndex) {
840             return totalChunks == chunkIndex;
841         }
842
843         public void markSendStatus(boolean success) {
844             if (success) {
845                 // if the chunk sent was successful
846                 replyReceivedForOffset = offset;
847                 replyStatus = true;
848                 lastChunkHashCode = nextChunkHashCode;
849             } else {
850                 // if the chunk sent was failure
851                 replyReceivedForOffset = offset;
852                 replyStatus = false;
853             }
854         }
855
856         public ByteString getNextChunk() {
857             int snapshotLength = getSnapshotBytes().size();
858             int start = incrementOffset();
859             int size = context.getConfigParams().getSnapshotChunkSize();
860             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
861                 size = snapshotLength;
862             } else {
863                 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
864                     size = snapshotLength - start;
865                 }
866             }
867
868
869             LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
870                     snapshotLength, start, size);
871
872             ByteString substring = getSnapshotBytes().substring(start, start + size);
873             nextChunkHashCode = substring.hashCode();
874             return substring;
875         }
876
877         /**
878          * reset should be called when the Follower needs to be sent the snapshot from the beginning
879          */
880         public void reset(){
881             offset = 0;
882             replyStatus = false;
883             replyReceivedForOffset = offset;
884             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
885             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
886         }
887
888         public int getLastChunkHashCode() {
889             return lastChunkHashCode;
890         }
891     }
892
893     // called from example-actor for printing the follower-states
894     public String printFollowerStates() {
895         final StringBuilder sb = new StringBuilder();
896
897         sb.append('[');
898         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
899             sb.append('{');
900             sb.append(followerLogInformation.getId());
901             sb.append(" state:");
902             sb.append(followerLogInformation.isFollowerActive());
903             sb.append("},");
904         }
905         sb.append(']');
906
907         return sb.toString();
908     }
909
910     @VisibleForTesting
911     public FollowerLogInformation getFollower(String followerId) {
912         return followerToLog.get(followerId);
913     }
914
915     @VisibleForTesting
916     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
917         mapFollowerToSnapshot.put(followerId, snapshot);
918     }
919
920     @VisibleForTesting
921     public int followerSnapshotSize() {
922         return mapFollowerToSnapshot.size();
923     }
924
925     @VisibleForTesting
926     public int followerLogSize() {
927         return followerToLog.size();
928     }
929
930     private static class SnapshotHolder {
931         private final long lastIncludedTerm;
932         private final long lastIncludedIndex;
933         private final ByteString snapshotBytes;
934
935         SnapshotHolder(Snapshot snapshot) {
936             this.lastIncludedTerm = snapshot.getLastAppliedTerm();
937             this.lastIncludedIndex = snapshot.getLastAppliedIndex();
938             this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
939         }
940
941         long getLastIncludedTerm() {
942             return lastIncludedTerm;
943         }
944
945         long getLastIncludedIndex() {
946             return lastIncludedIndex;
947         }
948
949         ByteString getSnapshotBytes() {
950             return snapshotBytes;
951         }
952     }
953 }