BUG-5626: Move leaderId/leaderPayloadVersion fields
[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 javax.annotation.Nullable;
29 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
31 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
33 import org.opendaylight.controller.cluster.raft.PeerInfo;
34 import org.opendaylight.controller.cluster.raft.RaftActorContext;
35 import org.opendaylight.controller.cluster.raft.RaftState;
36 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
37 import org.opendaylight.controller.cluster.raft.Snapshot;
38 import org.opendaylight.controller.cluster.raft.VotingState;
39 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
40 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
41 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
43 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
45 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
46 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
47 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
48 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
49 import scala.concurrent.duration.FiniteDuration;
50
51 /**
52  * The behavior of a RaftActor when it is in the Leader state
53  * <p/>
54  * Leaders:
55  * <ul>
56  * <li> Upon election: send initial empty AppendEntries RPCs
57  * (heartbeat) to each server; repeat during idle periods to
58  * prevent election timeouts (§5.2)
59  * <li> If command received from client: append entry to local log,
60  * respond after entry applied to state machine (§5.3)
61  * <li> If last log index ≥ nextIndex for a follower: send
62  * AppendEntries RPC with log entries starting at nextIndex
63  * <ul>
64  * <li> If successful: update nextIndex and matchIndex for
65  * follower (§5.3)
66  * <li> If AppendEntries fails because of log inconsistency:
67  * decrement nextIndex and retry (§5.3)
68  * </ul>
69  * <li> If there exists an N such that N > commitIndex, a majority
70  * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
71  * set commitIndex = N (§5.3, §5.4).
72  */
73 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
74
75     // The index of the first chunk that is sent when installing a snapshot
76     public static final int FIRST_CHUNK_INDEX = 1;
77
78     // The index that the follower should respond with if it needs the install snapshot to be reset
79     public static final int INVALID_CHUNK_INDEX = -1;
80
81     // This would be passed as the hash code of the last chunk when sending the first chunk
82     public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
83
84     private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
85     private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
86
87     private Cancellable heartbeatSchedule = null;
88
89     private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
90
91     private int minReplicationCount;
92
93     private Optional<SnapshotHolder> snapshot;
94
95     protected AbstractLeader(RaftActorContext context, RaftState state) {
96         super(context, state);
97
98         for(PeerInfo peerInfo: context.getPeers()) {
99             FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
100             followerToLog.put(peerInfo.getId(), followerLogInformation);
101         }
102
103         LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
104
105         updateMinReplicaCount();
106
107         snapshot = Optional.absent();
108
109         // Immediately schedule a heartbeat
110         // Upon election: send initial empty AppendEntries RPCs
111         // (heartbeat) to each server; repeat during idle periods to
112         // prevent election timeouts (§5.2)
113         sendAppendEntries(0, false);
114
115         // It is important to schedule this heartbeat here
116         scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
117     }
118
119     /**
120      * Return an immutable collection of follower identifiers.
121      *
122      * @return Collection of follower IDs
123      */
124     public final Collection<String> getFollowerIds() {
125         return followerToLog.keySet();
126     }
127
128     public void addFollower(String followerId) {
129         FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
130                 context.getPeerInfo(followerId), -1, context);
131         followerToLog.put(followerId, followerLogInformation);
132
133         if(heartbeatSchedule == null) {
134             scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
135         }
136     }
137
138     public void removeFollower(String followerId) {
139         followerToLog.remove(followerId);
140         mapFollowerToSnapshot.remove(followerId);
141     }
142
143     public void updateMinReplicaCount() {
144         int numVoting = 0;
145         for(PeerInfo peer: context.getPeers()) {
146             if(peer.isVoting()) {
147                 numVoting++;
148             }
149         }
150
151         minReplicationCount = getMajorityVoteCount(numVoting);
152     }
153
154     protected int getMinIsolatedLeaderPeerCount(){
155       //the isolated Leader peer count will be 1 less than the majority vote count.
156         //this is because the vote count has the self vote counted in it
157         //for e.g
158         //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
159         //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
160         //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
161
162         return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
163     }
164
165     @VisibleForTesting
166     void setSnapshot(@Nullable Snapshot snapshot) {
167         if(snapshot != null) {
168             this.snapshot = Optional.of(new SnapshotHolder(snapshot));
169         } else {
170             this.snapshot = Optional.absent();
171         }
172     }
173
174     @Override
175     protected RaftActorBehavior handleAppendEntries(ActorRef sender,
176         AppendEntries appendEntries) {
177
178         LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
179
180         return this;
181     }
182
183     @Override
184     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
185         AppendEntriesReply appendEntriesReply) {
186
187         if(LOG.isTraceEnabled()) {
188             LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
189         }
190
191         // Update the FollowerLogInformation
192         String followerId = appendEntriesReply.getFollowerId();
193         FollowerLogInformation followerLogInformation =
194             followerToLog.get(followerId);
195
196         if(followerLogInformation == null){
197             LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
198             return this;
199         }
200
201         if(followerLogInformation.timeSinceLastActivity() >
202                 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
203             LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
204                             "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
205                     logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
206                     context.getLastApplied(), context.getCommitIndex());
207         }
208
209         followerLogInformation.markFollowerActive();
210         followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
211         followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
212
213         boolean updated = false;
214         if (appendEntriesReply.isSuccess()) {
215             updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
216         } else {
217             LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
218
219             long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
220             ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
221             if(appendEntriesReply.isForceInstallSnapshot()) {
222                 // Reset the followers match and next index. This is to signal that this follower has nothing
223                 // in common with this Leader and so would require a snapshot to be installed
224                 followerLogInformation.setMatchIndex(-1);
225                 followerLogInformation.setNextIndex(-1);
226
227                 // Force initiate a snapshot capture
228                 initiateCaptureSnapshot(followerId);
229             } else if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
230                     followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
231                 // The follower's log is empty or the last entry is present in the leader's journal
232                 // and the terms match so the follower is just behind the leader's journal from
233                 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
234                 // follower's last log index.
235
236                 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
237             } else {
238                 // TODO: When we find that the follower is out of sync with the
239                 // Leader we simply decrement that followers next index by 1.
240                 // Would it be possible to do better than this? The RAFT spec
241                 // does not explicitly deal with it but may be something for us to
242                 // think about.
243
244                 followerLogInformation.decrNextIndex();
245             }
246         }
247
248         // Now figure out if this reply warrants a change in the commitIndex
249         // If there exists an N such that N > commitIndex, a majority
250         // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
251         // set commitIndex = N (§5.3, §5.4).
252         for (long N = context.getCommitIndex() + 1; ; N++) {
253             int replicatedCount = 1;
254
255             for (FollowerLogInformation info : followerToLog.values()) {
256                 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
257                 if(info.getMatchIndex() >= N && (peerInfo != null && peerInfo.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, 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                 byte[] 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(followerToLog.get(followerId).getRaftVersion()),
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 byte[] 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         byte[] nextChunk = followerToSnapshot.getNextChunk();
730
731         LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
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(), SendHeartBeat.INSTANCE,
765             context.getActorSystem().dispatcher(), context.getActor());
766     }
767
768     @Override
769     public void close() {
770         stopHeartBeat();
771     }
772
773     @Override
774     public final String getLeaderId() {
775         return context.getId();
776     }
777
778     @Override
779     public final short getLeaderPayloadVersion() {
780         return context.getPayloadVersion();
781     }
782
783     protected boolean isLeaderIsolated() {
784         int minPresent = getMinIsolatedLeaderPeerCount();
785         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
786             if (followerLogInformation.isFollowerActive()) {
787                 --minPresent;
788                 if (minPresent == 0) {
789                     break;
790                 }
791             }
792         }
793         return (minPresent != 0);
794     }
795
796     /**
797      * Encapsulates the snapshot bytestring and handles the logic of sending
798      * snapshot chunks
799      */
800     protected class FollowerToSnapshot {
801         private final ByteString snapshotBytes;
802         private int offset = 0;
803         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
804         private int replyReceivedForOffset;
805         // if replyStatus is false, the previous chunk is attempted
806         private boolean replyStatus = false;
807         private int chunkIndex;
808         private final int totalChunks;
809         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
810         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
811
812         public FollowerToSnapshot(ByteString snapshotBytes) {
813             this.snapshotBytes = snapshotBytes;
814             int size = snapshotBytes.size();
815             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
816                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
817             if(LOG.isDebugEnabled()) {
818                 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
819                         logName(), size, totalChunks);
820             }
821             replyReceivedForOffset = -1;
822             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
823         }
824
825         public ByteString getSnapshotBytes() {
826             return snapshotBytes;
827         }
828
829         public int incrementOffset() {
830             if(replyStatus) {
831                 // if prev chunk failed, we would want to sent the same chunk again
832                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
833             }
834             return offset;
835         }
836
837         public int incrementChunkIndex() {
838             if (replyStatus) {
839                 // if prev chunk failed, we would want to sent the same chunk again
840                 chunkIndex =  chunkIndex + 1;
841             }
842             return chunkIndex;
843         }
844
845         public int getChunkIndex() {
846             return chunkIndex;
847         }
848
849         public int getTotalChunks() {
850             return totalChunks;
851         }
852
853         public boolean canSendNextChunk() {
854             // we only send a false if a chunk is sent but we have not received a reply yet
855             return replyReceivedForOffset == offset;
856         }
857
858         public boolean isLastChunk(int chunkIndex) {
859             return totalChunks == chunkIndex;
860         }
861
862         public void markSendStatus(boolean success) {
863             if (success) {
864                 // if the chunk sent was successful
865                 replyReceivedForOffset = offset;
866                 replyStatus = true;
867                 lastChunkHashCode = nextChunkHashCode;
868             } else {
869                 // if the chunk sent was failure
870                 replyReceivedForOffset = offset;
871                 replyStatus = false;
872             }
873         }
874
875         public byte[] getNextChunk() {
876             int snapshotLength = getSnapshotBytes().size();
877             int start = incrementOffset();
878             int size = context.getConfigParams().getSnapshotChunkSize();
879             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
880                 size = snapshotLength;
881             } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
882                 size = snapshotLength - start;
883             }
884
885             byte[] nextChunk = new byte[size];
886             getSnapshotBytes().copyTo(nextChunk, start, 0, size);
887             nextChunkHashCode = Arrays.hashCode(nextChunk);
888
889             LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
890                     snapshotLength, start, size, nextChunkHashCode);
891             return nextChunk;
892         }
893
894         /**
895          * reset should be called when the Follower needs to be sent the snapshot from the beginning
896          */
897         public void reset(){
898             offset = 0;
899             replyStatus = false;
900             replyReceivedForOffset = offset;
901             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
902             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
903         }
904
905         public int getLastChunkHashCode() {
906             return lastChunkHashCode;
907         }
908     }
909
910     // called from example-actor for printing the follower-states
911     public String printFollowerStates() {
912         final StringBuilder sb = new StringBuilder();
913
914         sb.append('[');
915         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
916             sb.append('{');
917             sb.append(followerLogInformation.getId());
918             sb.append(" state:");
919             sb.append(followerLogInformation.isFollowerActive());
920             sb.append("},");
921         }
922         sb.append(']');
923
924         return sb.toString();
925     }
926
927     @VisibleForTesting
928     public FollowerLogInformation getFollower(String followerId) {
929         return followerToLog.get(followerId);
930     }
931
932     @VisibleForTesting
933     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
934         mapFollowerToSnapshot.put(followerId, snapshot);
935     }
936
937     @VisibleForTesting
938     public int followerSnapshotSize() {
939         return mapFollowerToSnapshot.size();
940     }
941
942     @VisibleForTesting
943     public int followerLogSize() {
944         return followerToLog.size();
945     }
946
947     private static class SnapshotHolder {
948         private final long lastIncludedTerm;
949         private final long lastIncludedIndex;
950         private final ByteString snapshotBytes;
951
952         SnapshotHolder(Snapshot snapshot) {
953             this.lastIncludedTerm = snapshot.getLastAppliedTerm();
954             this.lastIncludedIndex = snapshot.getLastAppliedIndex();
955             this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
956         }
957
958         long getLastIncludedTerm() {
959             return lastIncludedTerm;
960         }
961
962         long getLastIncludedIndex() {
963             return lastIncludedIndex;
964         }
965
966         ByteString getSnapshotBytes() {
967             return snapshotBytes;
968         }
969     }
970 }