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