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