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