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