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