Bug 3570: Use SnapShot lastAppliedIndex for install snapshot
[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         if (followerToLog.isEmpty()) {
455             context.setCommitIndex(logIndex);
456             applyLogToStateMachine(logIndex);
457         } else {
458             sendAppendEntries(0, false);
459         }
460     }
461
462     private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
463         // Send an AppendEntries to all followers
464         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
465             final String followerId = e.getKey();
466             final FollowerLogInformation followerLogInformation = e.getValue();
467             // This checks helps not to send a repeat message to the follower
468             if(!followerLogInformation.isFollowerActive() ||
469                     followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
470                 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
471             }
472         }
473     }
474
475     /**
476      *
477      * This method checks if any update needs to be sent to the given follower. This includes append log entries,
478      * sending next snapshot chunk, and initiating a snapshot.
479      * @return true if any update is sent, false otherwise
480      */
481
482     private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
483                                        boolean sendHeartbeat, boolean isHeartbeat) {
484
485         ActorSelection followerActor = context.getPeerActorSelection(followerId);
486         if (followerActor != null) {
487             long followerNextIndex = followerLogInformation.getNextIndex();
488             boolean isFollowerActive = followerLogInformation.isFollowerActive();
489             boolean sendAppendEntries = false;
490             List<ReplicatedLogEntry> entries = Collections.emptyList();
491
492             if (mapFollowerToSnapshot.get(followerId) != null) {
493                 // if install snapshot is in process , then sent next chunk if possible
494                 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
495                     sendSnapshotChunk(followerActor, followerId);
496                 } else if(sendHeartbeat) {
497                     // we send a heartbeat even if we have not received a reply for the last chunk
498                     sendAppendEntries = true;
499                 }
500             } else {
501                 long leaderLastIndex = context.getReplicatedLog().lastIndex();
502                 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
503
504                 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
505                     LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
506                             logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
507                 }
508
509                 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
510
511                     LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
512                             followerNextIndex, followerId);
513
514                     if(followerLogInformation.okToReplicate()) {
515                         // Try to send all the entries in the journal but not exceeding the max data size
516                         // for a single AppendEntries message.
517                         int maxEntries = (int) context.getReplicatedLog().size();
518                         entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
519                                 context.getConfigParams().getSnapshotChunkSize());
520                         sendAppendEntries = true;
521                     }
522                 } else if (isFollowerActive && followerNextIndex >= 0 &&
523                     leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
524                     // if the followers next index is not present in the leaders log, and
525                     // if the follower is just not starting and if leader's index is more than followers index
526                     // then snapshot should be sent
527
528                     if (LOG.isDebugEnabled()) {
529                         LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
530                                     "follower-nextIndex: %d, leader-snapshot-index: %d,  " +
531                                     "leader-last-index: %d", logName(), followerId,
532                                     followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
533                     }
534
535                     // Send heartbeat to follower whenever install snapshot is initiated.
536                     sendAppendEntries = true;
537                     initiateCaptureSnapshot(followerId, followerNextIndex);
538
539                 } else if(sendHeartbeat) {
540                     // we send an AppendEntries, even if the follower is inactive
541                     // in-order to update the followers timestamp, in case it becomes active again
542                     sendAppendEntries = true;
543                 }
544
545             }
546
547             if(sendAppendEntries) {
548                 sendAppendEntriesToFollower(followerActor, followerNextIndex,
549                         entries, followerId);
550             }
551         }
552     }
553
554     private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
555         List<ReplicatedLogEntry> entries, String followerId) {
556         AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
557             prevLogIndex(followerNextIndex),
558             prevLogTerm(followerNextIndex), entries,
559             context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
560
561         if(!entries.isEmpty() || LOG.isTraceEnabled()) {
562             LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
563                     appendEntries);
564         }
565
566         followerActor.tell(appendEntries.toSerializable(), actor());
567     }
568
569     /**
570      * Install Snapshot works as follows
571      * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
572      * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
573      * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
574      * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
575      * 4. On complete, Follower sends back a InstallSnapshotReply.
576      * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
577      * and replenishes the memory by deleting the snapshot in Replicated log.
578      * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
579      * then send the existing snapshot in chunks to the follower.
580      * @param followerId
581      * @param followerNextIndex
582      */
583     private void initiateCaptureSnapshot(String followerId, long followerNextIndex) {
584         if (!context.getReplicatedLog().isPresent(followerNextIndex) &&
585                 context.getReplicatedLog().isInSnapshot(followerNextIndex)) {
586
587             if (snapshot.isPresent()) {
588                 // if a snapshot is present in the memory, most likely another install is in progress
589                 // no need to capture snapshot.
590                 // This could happen if another follower needs an install when one is going on.
591                 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
592                 sendSnapshotChunk(followerActor, followerId);
593
594
595             } else {
596                 context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
597                         this.getReplicatedToAllIndex(), followerId);
598             }
599         }
600     }
601
602
603     private void sendInstallSnapshot() {
604         LOG.debug("{}: sendInstallSnapshot", logName());
605         for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
606             ActorSelection followerActor = context.getPeerActorSelection(e.getKey());
607
608             if (followerActor != null) {
609                 long nextIndex = e.getValue().getNextIndex();
610
611                 if (!context.getReplicatedLog().isPresent(nextIndex) &&
612                     context.getReplicatedLog().isInSnapshot(nextIndex)) {
613                     sendSnapshotChunk(followerActor, e.getKey());
614                 }
615             }
616         }
617     }
618
619     /**
620      *  Sends a snapshot chunk to a given follower
621      *  InstallSnapshot should qualify as a heartbeat too.
622      */
623     private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
624         try {
625             if (snapshot.isPresent()) {
626                 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
627
628                 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
629                 // followerId to the followerToSnapshot map.
630                 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
631
632                 followerActor.tell(
633                     new InstallSnapshot(currentTerm(), context.getId(),
634                         snapshot.get().getLastIncludedIndex(),
635                         snapshot.get().getLastIncludedTerm(),
636                         nextSnapshotChunk,
637                         followerToSnapshot.incrementChunkIndex(),
638                         followerToSnapshot.getTotalChunks(),
639                         Optional.of(followerToSnapshot.getLastChunkHashCode())
640                     ).toSerializable(),
641                     actor()
642                 );
643
644                 if(LOG.isDebugEnabled()) {
645                     LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
646                             logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
647                             followerToSnapshot.getTotalChunks());
648                 }
649             }
650         } catch (IOException e) {
651             LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
652         }
653     }
654
655     /**
656      * Acccepts snaphot as ByteString, enters into map for future chunks
657      * creates and return a ByteString chunk
658      */
659     private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
660         FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
661         if (followerToSnapshot == null) {
662             followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
663             mapFollowerToSnapshot.put(followerId, followerToSnapshot);
664         }
665         ByteString nextChunk = followerToSnapshot.getNextChunk();
666
667         LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
668
669         return nextChunk;
670     }
671
672     private void sendHeartBeat() {
673         if (!followerToLog.isEmpty()) {
674             LOG.trace("{}: Sending heartbeat", logName());
675             sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
676         }
677     }
678
679     private void stopHeartBeat() {
680         if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
681             heartbeatSchedule.cancel();
682         }
683     }
684
685     private void scheduleHeartBeat(FiniteDuration interval) {
686         if (followerToLog.isEmpty()) {
687             // Optimization - do not bother scheduling a heartbeat as there are
688             // no followers
689             return;
690         }
691
692         stopHeartBeat();
693
694         // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
695         // message is sent to itself.
696         // Scheduling the heartbeat only once here because heartbeats do not
697         // need to be sent if there are other messages being sent to the remote
698         // actor.
699         heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
700             interval, context.getActor(), new SendHeartBeat(),
701             context.getActorSystem().dispatcher(), context.getActor());
702     }
703
704     @Override
705     public void close() throws Exception {
706         stopHeartBeat();
707     }
708
709     @Override
710     public String getLeaderId() {
711         return context.getId();
712     }
713
714     protected boolean isLeaderIsolated() {
715         int minPresent = minIsolatedLeaderPeerCount;
716         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
717             if (followerLogInformation.isFollowerActive()) {
718                 --minPresent;
719                 if (minPresent == 0) {
720                     break;
721                 }
722             }
723         }
724         return (minPresent != 0);
725     }
726
727     /**
728      * Encapsulates the snapshot bytestring and handles the logic of sending
729      * snapshot chunks
730      */
731     protected class FollowerToSnapshot {
732         private final ByteString snapshotBytes;
733         private int offset = 0;
734         // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
735         private int replyReceivedForOffset;
736         // if replyStatus is false, the previous chunk is attempted
737         private boolean replyStatus = false;
738         private int chunkIndex;
739         private final int totalChunks;
740         private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
741         private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
742
743         public FollowerToSnapshot(ByteString snapshotBytes) {
744             this.snapshotBytes = snapshotBytes;
745             int size = snapshotBytes.size();
746             totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
747                 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
748             if(LOG.isDebugEnabled()) {
749                 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
750                         logName(), size, totalChunks);
751             }
752             replyReceivedForOffset = -1;
753             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
754         }
755
756         public ByteString getSnapshotBytes() {
757             return snapshotBytes;
758         }
759
760         public int incrementOffset() {
761             if(replyStatus) {
762                 // if prev chunk failed, we would want to sent the same chunk again
763                 offset = offset + context.getConfigParams().getSnapshotChunkSize();
764             }
765             return offset;
766         }
767
768         public int incrementChunkIndex() {
769             if (replyStatus) {
770                 // if prev chunk failed, we would want to sent the same chunk again
771                 chunkIndex =  chunkIndex + 1;
772             }
773             return chunkIndex;
774         }
775
776         public int getChunkIndex() {
777             return chunkIndex;
778         }
779
780         public int getTotalChunks() {
781             return totalChunks;
782         }
783
784         public boolean canSendNextChunk() {
785             // we only send a false if a chunk is sent but we have not received a reply yet
786             return replyReceivedForOffset == offset;
787         }
788
789         public boolean isLastChunk(int chunkIndex) {
790             return totalChunks == chunkIndex;
791         }
792
793         public void markSendStatus(boolean success) {
794             if (success) {
795                 // if the chunk sent was successful
796                 replyReceivedForOffset = offset;
797                 replyStatus = true;
798                 lastChunkHashCode = nextChunkHashCode;
799             } else {
800                 // if the chunk sent was failure
801                 replyReceivedForOffset = offset;
802                 replyStatus = false;
803             }
804         }
805
806         public ByteString getNextChunk() {
807             int snapshotLength = getSnapshotBytes().size();
808             int start = incrementOffset();
809             int size = context.getConfigParams().getSnapshotChunkSize();
810             if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
811                 size = snapshotLength;
812             } else {
813                 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
814                     size = snapshotLength - start;
815                 }
816             }
817
818
819             LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
820                     snapshotLength, start, size);
821
822             ByteString substring = getSnapshotBytes().substring(start, start + size);
823             nextChunkHashCode = substring.hashCode();
824             return substring;
825         }
826
827         /**
828          * reset should be called when the Follower needs to be sent the snapshot from the beginning
829          */
830         public void reset(){
831             offset = 0;
832             replyStatus = false;
833             replyReceivedForOffset = offset;
834             chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
835             lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
836         }
837
838         public int getLastChunkHashCode() {
839             return lastChunkHashCode;
840         }
841     }
842
843     // called from example-actor for printing the follower-states
844     public String printFollowerStates() {
845         final StringBuilder sb = new StringBuilder();
846
847         sb.append('[');
848         for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
849             sb.append('{');
850             sb.append(followerLogInformation.getId());
851             sb.append(" state:");
852             sb.append(followerLogInformation.isFollowerActive());
853             sb.append("},");
854         }
855         sb.append(']');
856
857         return sb.toString();
858     }
859
860     @VisibleForTesting
861     public FollowerLogInformation getFollower(String followerId) {
862         return followerToLog.get(followerId);
863     }
864
865     @VisibleForTesting
866     protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
867         mapFollowerToSnapshot.put(followerId, snapshot);
868     }
869
870     @VisibleForTesting
871     public int followerSnapshotSize() {
872         return mapFollowerToSnapshot.size();
873     }
874
875     @VisibleForTesting
876     public int followerLogSize() {
877         return followerToLog.size();
878     }
879
880     private static class SnapshotHolder {
881         private final long lastIncludedTerm;
882         private final long lastIncludedIndex;
883         private final ByteString snapshotBytes;
884
885         SnapshotHolder(Snapshot snapshot) {
886             this.lastIncludedTerm = snapshot.getLastAppliedTerm();
887             this.lastIncludedIndex = snapshot.getLastAppliedIndex();
888             this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
889         }
890
891         long getLastIncludedTerm() {
892             return lastIncludedTerm;
893         }
894
895         long getLastIncludedIndex() {
896             return lastIncludedIndex;
897         }
898
899         ByteString getSnapshotBytes() {
900             return snapshotBytes;
901         }
902     }
903 }