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