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