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