2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft.behaviors;
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.io.IOException;
19 import java.util.Arrays;
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;
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.Snapshot;
39 import org.opendaylight.controller.cluster.raft.VotingState;
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 scala.concurrent.duration.FiniteDuration;
54 * The behavior of a RaftActor when it is in the Leader state
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
66 * <li> If successful: update nextIndex and matchIndex for
68 * <li> If AppendEntries fails because of log inconsistency:
69 * decrement nextIndex and retry (§5.3)
71 * <li> If there exists an N such that N > commitIndex, a majority
72 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
73 * set commitIndex = N (§5.3, §5.4).
75 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
77 // The index of the first chunk that is sent when installing a snapshot
78 public static final int FIRST_CHUNK_INDEX = 1;
80 // The index that the follower should respond with if it needs the install snapshot to be reset
81 public static final int INVALID_CHUNK_INDEX = -1;
83 // This would be passed as the hash code of the last chunk when sending the first chunk
84 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
86 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
87 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
90 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
91 * expect the entries to be modified in sequence, hence we open-code the lookup.
93 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
94 * but we already expect those to be far from frequent.
96 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
98 private Cancellable heartbeatSchedule = null;
99 private Optional<SnapshotHolder> snapshot;
100 private int minReplicationCount;
102 protected AbstractLeader(RaftActorContext context, RaftState state,
103 @Nullable AbstractLeader initializeFromLeader) {
104 super(context, state);
106 if(initializeFromLeader != null) {
107 followerToLog.putAll(initializeFromLeader.followerToLog);
109 for(PeerInfo peerInfo: context.getPeers()) {
110 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
111 followerToLog.put(peerInfo.getId(), followerLogInformation);
115 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
117 updateMinReplicaCount();
119 snapshot = Optional.absent();
121 // Immediately schedule a heartbeat
122 // Upon election: send initial empty AppendEntries RPCs
123 // (heartbeat) to each server; repeat during idle periods to
124 // prevent election timeouts (§5.2)
125 sendAppendEntries(0, false);
127 // It is important to schedule this heartbeat here
128 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
131 protected AbstractLeader(RaftActorContext context, RaftState state) {
132 this(context, state, null);
136 * Return an immutable collection of follower identifiers.
138 * @return Collection of follower IDs
140 public final Collection<String> getFollowerIds() {
141 return followerToLog.keySet();
144 public void addFollower(String followerId) {
145 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
146 context.getPeerInfo(followerId), -1, context);
147 followerToLog.put(followerId, followerLogInformation);
149 if(heartbeatSchedule == null) {
150 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
154 public void removeFollower(String followerId) {
155 followerToLog.remove(followerId);
156 mapFollowerToSnapshot.remove(followerId);
159 public void updateMinReplicaCount() {
161 for(PeerInfo peer: context.getPeers()) {
162 if(peer.isVoting()) {
167 minReplicationCount = getMajorityVoteCount(numVoting);
170 protected int getMinIsolatedLeaderPeerCount(){
171 //the isolated Leader peer count will be 1 less than the majority vote count.
172 //this is because the vote count has the self vote counted in it
174 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
175 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
176 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
178 return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
182 void setSnapshot(@Nullable Snapshot snapshot) {
183 if(snapshot != null) {
184 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
186 this.snapshot = Optional.absent();
191 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
192 AppendEntries appendEntries) {
194 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
200 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
201 AppendEntriesReply appendEntriesReply) {
203 if(LOG.isTraceEnabled()) {
204 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
207 // Update the FollowerLogInformation
208 String followerId = appendEntriesReply.getFollowerId();
209 FollowerLogInformation followerLogInformation =
210 followerToLog.get(followerId);
212 if(followerLogInformation == null){
213 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
217 if(followerLogInformation.timeSinceLastActivity() >
218 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
219 LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
220 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
221 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
222 context.getLastApplied(), context.getCommitIndex());
225 followerLogInformation.markFollowerActive();
226 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
227 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
229 boolean updated = false;
230 if(appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
231 // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
232 // in raft as a node cannot become leader if it's log is behind another's. However, the
233 // non-voting semantics deviate a bit from raft. Only voting members participate in
234 // elections and can become leader so it's possible for a non-voting follower to be ahead
235 // of the leader. This can happen if persistence is disabled and all voting members are
236 // restarted. In this case, the voting leader will start out with an empty log however
237 // the non-voting followers still retain the previous data in memory. On the first
238 // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
239 // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
240 // lastLogIndex may be higher in which case we want to reset the follower by installing a
241 // snapshot. It's also possible that the follower's last log index is behind the leader's.
242 // However in this case the log terms won't match and the logs will conflict - this is handled
244 LOG.debug("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} - forcing install snaphot",
245 logName(), followerLogInformation.getId(), appendEntriesReply.getLogLastIndex(),
246 context.getReplicatedLog().lastIndex());
248 followerLogInformation.setMatchIndex(-1);
249 followerLogInformation.setNextIndex(-1);
251 initiateCaptureSnapshot(followerId);
253 } else if (appendEntriesReply.isSuccess()) {
254 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
256 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
258 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
259 long followersLastLogTerm = getLogEntryTerm(followerLastLogIndex);
260 if(appendEntriesReply.isForceInstallSnapshot()) {
261 // Reset the followers match and next index. This is to signal that this follower has nothing
262 // in common with this Leader and so would require a snapshot to be installed
263 followerLogInformation.setMatchIndex(-1);
264 followerLogInformation.setNextIndex(-1);
266 // Force initiate a snapshot capture
267 initiateCaptureSnapshot(followerId);
268 } else if(followerLastLogIndex < 0 || (followersLastLogTerm >= 0 &&
269 followersLastLogTerm == appendEntriesReply.getLogLastTerm())) {
270 // The follower's log is empty or the last entry is present in the leader's journal
271 // and the terms match so the follower is just behind the leader's journal from
272 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
273 // follower's last log index.
275 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
277 // The follower's log conflicts with leader's log so decrement follower's next index by 1
278 // in an attempt to find where the logs match.
280 LOG.debug("{}: follower's last log term {} conflicts with the leader's {} - dec next index",
281 logName(), appendEntriesReply.getLogLastTerm(), followersLastLogTerm);
283 followerLogInformation.decrNextIndex();
287 // Now figure out if this reply warrants a change in the commitIndex
288 // If there exists an N such that N > commitIndex, a majority
289 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
290 // set commitIndex = N (§5.3, §5.4).
291 if(LOG.isTraceEnabled()) {
292 LOG.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
293 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
296 for (long N = context.getCommitIndex() + 1; ; N++) {
297 int replicatedCount = 1;
299 LOG.trace("{}: checking Nth index {}", logName(), N);
300 for (FollowerLogInformation info : followerToLog.values()) {
301 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
302 if(info.getMatchIndex() >= N && (peerInfo != null && peerInfo.isVoting())) {
304 } else if(LOG.isTraceEnabled()) {
305 LOG.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
306 info.getMatchIndex(), peerInfo);
310 if(LOG.isTraceEnabled()) {
311 LOG.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount, minReplicationCount);
314 if (replicatedCount >= minReplicationCount) {
315 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
316 if (replicatedLogEntry == null) {
317 LOG.debug("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
318 logName(), N, context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().size());
322 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
323 // "Raft never commits log entries from previous terms by counting replicas".
324 // However we keep looping so we can make progress when new entries in the current term
325 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
326 // counting replicas, then all prior entries are committed indirectly".
327 if (replicatedLogEntry.getTerm() == currentTerm()) {
328 LOG.trace("{}: Setting commit index to {}", logName(), N);
329 context.setCommitIndex(N);
331 LOG.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, term {} does not match the current term {}",
332 logName(), N, replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
335 LOG.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
340 // Apply the change to the state machine
341 if (context.getCommitIndex() > context.getLastApplied()) {
342 if(LOG.isDebugEnabled()) {
343 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
344 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
347 applyLogToStateMachine(context.getCommitIndex());
350 if (!context.getSnapshotManager().isCapturing()) {
354 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
355 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
360 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
361 AppendEntriesReply appendEntriesReply) {
362 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
363 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
365 if(updated && LOG.isDebugEnabled()) {
366 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
367 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
368 followerLogInformation.getNextIndex());
373 private void purgeInMemoryLog() {
374 //find the lowest index across followers which has been replicated to all.
375 // lastApplied if there are no followers, so that we keep clearing the log for single-node
376 // we would delete the in-mem log from that index on, in-order to minimize mem usage
377 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
378 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
379 for (FollowerLogInformation info : followerToLog.values()) {
380 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
383 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
387 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
388 final Iterator<ClientRequestTracker> it = trackers.iterator();
389 while (it.hasNext()) {
390 final ClientRequestTracker t = it.next();
391 if (t.getIndex() == logIndex) {
401 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
402 RequestVoteReply requestVoteReply) {
406 protected void beforeSendHeartbeat(){}
409 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
410 Preconditions.checkNotNull(sender, "sender should not be null");
412 if (message instanceof RaftRPC) {
413 RaftRPC rpc = (RaftRPC) message;
414 // If RPC request or response contains term T > currentTerm:
415 // set currentTerm = T, convert to follower (§5.1)
416 // This applies to all RPC messages and responses
417 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
418 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
419 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
421 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
423 return internalSwitchBehavior(RaftState.Follower);
427 if (message instanceof SendHeartBeat) {
428 beforeSendHeartbeat();
430 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
431 } else if(message instanceof SendInstallSnapshot) {
432 // received from RaftActor
433 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
434 sendInstallSnapshot();
435 } else if (message instanceof Replicate) {
436 replicate((Replicate) message);
437 } else if (message instanceof InstallSnapshotReply) {
438 handleInstallSnapshotReply((InstallSnapshotReply) message);
440 return super.handleMessage(sender, message);
446 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
447 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
449 String followerId = reply.getFollowerId();
450 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
452 if (followerToSnapshot == null) {
453 LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
454 logName(), followerId);
458 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
459 if(followerLogInformation == null) {
460 // This can happen during AddServer if it times out.
461 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
462 logName(), followerId);
463 mapFollowerToSnapshot.remove(followerId);
467 followerLogInformation.markFollowerActive();
469 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
470 boolean wasLastChunk = false;
471 if (reply.isSuccess()) {
472 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
473 //this was the last chunk reply
474 if(LOG.isDebugEnabled()) {
475 LOG.debug("{}: InstallSnapshotReply received, " +
476 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
477 logName(), reply.getChunkIndex(), followerId,
478 context.getReplicatedLog().getSnapshotIndex() + 1
482 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
483 followerLogInformation.setMatchIndex(followerMatchIndex);
484 followerLogInformation.setNextIndex(followerMatchIndex + 1);
485 mapFollowerToSnapshot.remove(followerId);
487 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
488 logName(), followerId, followerLogInformation.getMatchIndex(),
489 followerLogInformation.getNextIndex());
491 if (mapFollowerToSnapshot.isEmpty()) {
492 // once there are no pending followers receiving snapshots
493 // we can remove snapshot from the memory
497 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
498 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
499 new UnInitializedFollowerSnapshotReply(followerId);
500 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
501 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
504 followerToSnapshot.markSendStatus(true);
507 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
508 logName(), reply.getChunkIndex());
510 followerToSnapshot.markSendStatus(false);
513 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
514 // Since the follower is now caught up try to purge the log.
516 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
517 ActorSelection followerActor = context.getPeerActorSelection(followerId);
518 if(followerActor != null) {
519 sendSnapshotChunk(followerActor, followerId);
524 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
525 logName(), reply.getChunkIndex(), followerId,
526 followerToSnapshot.getChunkIndex());
528 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
529 // Since the Follower did not find this index to be valid we should reset the follower snapshot
530 // so that Installing the snapshot can resume from the beginning
531 followerToSnapshot.reset();
536 private void replicate(Replicate replicate) {
537 long logIndex = replicate.getReplicatedLogEntry().getIndex();
539 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}", logName(),
540 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass());
542 // Create a tracker entry we will use this later to notify the
544 if(replicate.getClientActor() != null) {
545 trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
549 boolean applyModificationToState = !context.anyVotingPeers()
550 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
552 if(applyModificationToState){
553 context.setCommitIndex(logIndex);
554 applyLogToStateMachine(logIndex);
557 if (!followerToLog.isEmpty()) {
558 sendAppendEntries(0, false);
562 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
563 // Send an AppendEntries to all followers
564 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
565 final String followerId = e.getKey();
566 final FollowerLogInformation followerLogInformation = e.getValue();
567 // This checks helps not to send a repeat message to the follower
568 if(!followerLogInformation.isFollowerActive() ||
569 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
570 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
577 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
578 * sending next snapshot chunk, and initiating a snapshot.
579 * @return true if any update is sent, false otherwise
582 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
583 boolean sendHeartbeat, boolean isHeartbeat) {
585 ActorSelection followerActor = context.getPeerActorSelection(followerId);
586 if (followerActor != null) {
587 long followerNextIndex = followerLogInformation.getNextIndex();
588 boolean isFollowerActive = followerLogInformation.isFollowerActive();
589 boolean sendAppendEntries = false;
590 List<ReplicatedLogEntry> entries = Collections.emptyList();
592 if (mapFollowerToSnapshot.get(followerId) != null) {
593 // if install snapshot is in process , then sent next chunk if possible
594 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
595 sendSnapshotChunk(followerActor, followerId);
596 } else if(sendHeartbeat) {
597 // we send a heartbeat even if we have not received a reply for the last chunk
598 sendAppendEntries = true;
601 long leaderLastIndex = context.getReplicatedLog().lastIndex();
602 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
604 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
605 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
606 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
609 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
611 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
612 followerNextIndex, followerId);
614 if(followerLogInformation.okToReplicate()) {
615 // Try to send all the entries in the journal but not exceeding the max data size
616 // for a single AppendEntries message.
617 int maxEntries = (int) context.getReplicatedLog().size();
618 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
619 context.getConfigParams().getSnapshotChunkSize());
620 sendAppendEntries = true;
622 } else if (isFollowerActive && followerNextIndex >= 0 &&
623 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
624 // if the followers next index is not present in the leaders log, and
625 // if the follower is just not starting and if leader's index is more than followers index
626 // then snapshot should be sent
628 if (LOG.isDebugEnabled()) {
629 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s, " +
630 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
631 "leader-last-index: %d", logName(), followerId,
632 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
635 // Send heartbeat to follower whenever install snapshot is initiated.
636 sendAppendEntries = true;
637 if (canInstallSnapshot(followerNextIndex)) {
638 initiateCaptureSnapshot(followerId);
641 } else if(sendHeartbeat) {
642 // we send an AppendEntries, even if the follower is inactive
643 // in-order to update the followers timestamp, in case it becomes active again
644 sendAppendEntries = true;
649 if(sendAppendEntries) {
650 sendAppendEntriesToFollower(followerActor, followerNextIndex,
651 entries, followerId);
656 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
657 List<ReplicatedLogEntry> entries, String followerId) {
658 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
659 getLogEntryIndex(followerNextIndex - 1),
660 getLogEntryTerm(followerNextIndex - 1), entries,
661 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
663 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
664 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
668 followerActor.tell(appendEntries, actor());
672 * Install Snapshot works as follows
673 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
674 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
675 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
676 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
677 * 4. On complete, Follower sends back a InstallSnapshotReply.
678 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
679 * and replenishes the memory by deleting the snapshot in Replicated log.
680 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
681 * then send the existing snapshot in chunks to the follower.
684 public boolean initiateCaptureSnapshot(String followerId) {
685 if (snapshot.isPresent()) {
686 // if a snapshot is present in the memory, most likely another install is in progress
687 // no need to capture snapshot.
688 // This could happen if another follower needs an install when one is going on.
689 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
690 sendSnapshotChunk(followerActor, followerId);
693 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
694 this.getReplicatedToAllIndex(), followerId);
698 private boolean canInstallSnapshot(long nextIndex){
699 // If the follower's nextIndex is -1 then we might as well send it a snapshot
700 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
702 return (nextIndex == -1 ||
703 (!context.getReplicatedLog().isPresent(nextIndex)
704 && context.getReplicatedLog().isInSnapshot(nextIndex)));
709 private void sendInstallSnapshot() {
710 LOG.debug("{}: sendInstallSnapshot", logName());
711 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
712 String followerId = e.getKey();
713 ActorSelection followerActor = context.getPeerActorSelection(followerId);
714 FollowerLogInformation followerLogInfo = e.getValue();
716 if (followerActor != null) {
717 long nextIndex = followerLogInfo.getNextIndex();
718 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
719 canInstallSnapshot(nextIndex)) {
720 sendSnapshotChunk(followerActor, followerId);
727 * Sends a snapshot chunk to a given follower
728 * InstallSnapshot should qualify as a heartbeat too.
730 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
732 if (snapshot.isPresent()) {
733 byte[] nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
735 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
736 // followerId to the followerToSnapshot map.
737 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
739 int nextChunkIndex = followerToSnapshot.incrementChunkIndex();
740 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
741 if(followerToSnapshot.isLastChunk(nextChunkIndex)) {
742 serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
746 new InstallSnapshot(currentTerm(), context.getId(),
747 snapshot.get().getLastIncludedIndex(),
748 snapshot.get().getLastIncludedTerm(),
751 followerToSnapshot.getTotalChunks(),
752 Optional.of(followerToSnapshot.getLastChunkHashCode()),
754 ).toSerializable(followerToLog.get(followerId).getRaftVersion()),
758 if(LOG.isDebugEnabled()) {
759 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
760 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
761 followerToSnapshot.getTotalChunks());
764 } catch (IOException e) {
765 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
770 * Acccepts snaphot as ByteString, enters into map for future chunks
771 * creates and return a ByteString chunk
773 private byte[] getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
774 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
775 if (followerToSnapshot == null) {
776 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
777 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
779 byte[] nextChunk = followerToSnapshot.getNextChunk();
781 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
786 private void sendHeartBeat() {
787 if (!followerToLog.isEmpty()) {
788 LOG.trace("{}: Sending heartbeat", logName());
789 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
793 private void stopHeartBeat() {
794 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
795 heartbeatSchedule.cancel();
799 private void scheduleHeartBeat(FiniteDuration interval) {
800 if (followerToLog.isEmpty()) {
801 // Optimization - do not bother scheduling a heartbeat as there are
808 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
809 // message is sent to itself.
810 // Scheduling the heartbeat only once here because heartbeats do not
811 // need to be sent if there are other messages being sent to the remote
813 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
814 interval, context.getActor(), SendHeartBeat.INSTANCE,
815 context.getActorSystem().dispatcher(), context.getActor());
819 public void close() {
824 public final String getLeaderId() {
825 return context.getId();
829 public final short getLeaderPayloadVersion() {
830 return context.getPayloadVersion();
833 protected boolean isLeaderIsolated() {
834 int minPresent = getMinIsolatedLeaderPeerCount();
835 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
836 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
837 if(peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
839 if (minPresent == 0) {
844 return (minPresent != 0);
848 * Encapsulates the snapshot bytestring and handles the logic of sending
851 protected class FollowerToSnapshot {
852 private final ByteString snapshotBytes;
853 private int offset = 0;
854 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
855 private int replyReceivedForOffset;
856 // if replyStatus is false, the previous chunk is attempted
857 private boolean replyStatus = false;
858 private int chunkIndex;
859 private final int totalChunks;
860 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
861 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
863 public FollowerToSnapshot(ByteString snapshotBytes) {
864 this.snapshotBytes = snapshotBytes;
865 int size = snapshotBytes.size();
866 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
867 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
868 if(LOG.isDebugEnabled()) {
869 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
870 logName(), size, totalChunks);
872 replyReceivedForOffset = -1;
873 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
876 public ByteString getSnapshotBytes() {
877 return snapshotBytes;
880 public int incrementOffset() {
882 // if prev chunk failed, we would want to sent the same chunk again
883 offset = offset + context.getConfigParams().getSnapshotChunkSize();
888 public int incrementChunkIndex() {
890 // if prev chunk failed, we would want to sent the same chunk again
891 chunkIndex = chunkIndex + 1;
896 public int getChunkIndex() {
900 public int getTotalChunks() {
904 public boolean canSendNextChunk() {
905 // we only send a false if a chunk is sent but we have not received a reply yet
906 return replyReceivedForOffset == offset;
909 public boolean isLastChunk(int chunkIndex) {
910 return totalChunks == chunkIndex;
913 public void markSendStatus(boolean success) {
915 // if the chunk sent was successful
916 replyReceivedForOffset = offset;
918 lastChunkHashCode = nextChunkHashCode;
920 // if the chunk sent was failure
921 replyReceivedForOffset = offset;
926 public byte[] getNextChunk() {
927 int snapshotLength = getSnapshotBytes().size();
928 int start = incrementOffset();
929 int size = context.getConfigParams().getSnapshotChunkSize();
930 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
931 size = snapshotLength;
932 } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
933 size = snapshotLength - start;
936 byte[] nextChunk = new byte[size];
937 getSnapshotBytes().copyTo(nextChunk, start, 0, size);
938 nextChunkHashCode = Arrays.hashCode(nextChunk);
940 LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
941 snapshotLength, start, size, nextChunkHashCode);
946 * reset should be called when the Follower needs to be sent the snapshot from the beginning
951 replyReceivedForOffset = offset;
952 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
953 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
956 public int getLastChunkHashCode() {
957 return lastChunkHashCode;
961 // called from example-actor for printing the follower-states
962 public String printFollowerStates() {
963 final StringBuilder sb = new StringBuilder();
966 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
968 sb.append(followerLogInformation.getId());
969 sb.append(" state:");
970 sb.append(followerLogInformation.isFollowerActive());
975 return sb.toString();
979 public FollowerLogInformation getFollower(String followerId) {
980 return followerToLog.get(followerId);
984 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
985 mapFollowerToSnapshot.put(followerId, snapshot);
989 public int followerSnapshotSize() {
990 return mapFollowerToSnapshot.size();
994 public int followerLogSize() {
995 return followerToLog.size();
998 private static class SnapshotHolder {
999 private final long lastIncludedTerm;
1000 private final long lastIncludedIndex;
1001 private final ByteString snapshotBytes;
1003 SnapshotHolder(Snapshot snapshot) {
1004 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
1005 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
1006 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
1009 long getLastIncludedTerm() {
1010 return lastIncludedTerm;
1013 long getLastIncludedIndex() {
1014 return lastIncludedIndex;
1017 ByteString getSnapshotBytes() {
1018 return snapshotBytes;