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