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.ServerConfigurationPayload;
39 import org.opendaylight.controller.cluster.raft.Snapshot;
40 import org.opendaylight.controller.cluster.raft.VotingState;
41 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
42 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
43 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
44 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
45 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
46 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
47 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
48 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
49 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
50 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
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 originalMessage) {
410 Preconditions.checkNotNull(sender, "sender should not be null");
412 Object message = fromSerializableMessage(originalMessage);
414 if (message instanceof RaftRPC) {
415 RaftRPC rpc = (RaftRPC) message;
416 // If RPC request or response contains term T > currentTerm:
417 // set currentTerm = T, convert to follower (§5.1)
418 // This applies to all RPC messages and responses
419 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
420 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
421 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
423 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
425 return internalSwitchBehavior(RaftState.Follower);
429 if (message instanceof SendHeartBeat) {
430 beforeSendHeartbeat();
432 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
433 } else if(message instanceof SendInstallSnapshot) {
434 // received from RaftActor
435 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
436 sendInstallSnapshot();
437 } else if (message instanceof Replicate) {
438 replicate((Replicate) message);
439 } else if (message instanceof InstallSnapshotReply) {
440 handleInstallSnapshotReply((InstallSnapshotReply) message);
442 return super.handleMessage(sender, message);
448 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
449 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
451 String followerId = reply.getFollowerId();
452 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
454 if (followerToSnapshot == null) {
455 LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
456 logName(), followerId);
460 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
461 if(followerLogInformation == null) {
462 // This can happen during AddServer if it times out.
463 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
464 logName(), followerId);
465 mapFollowerToSnapshot.remove(followerId);
469 followerLogInformation.markFollowerActive();
471 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
472 boolean wasLastChunk = false;
473 if (reply.isSuccess()) {
474 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
475 //this was the last chunk reply
476 if(LOG.isDebugEnabled()) {
477 LOG.debug("{}: InstallSnapshotReply received, " +
478 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
479 logName(), reply.getChunkIndex(), followerId,
480 context.getReplicatedLog().getSnapshotIndex() + 1
484 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
485 followerLogInformation.setMatchIndex(followerMatchIndex);
486 followerLogInformation.setNextIndex(followerMatchIndex + 1);
487 mapFollowerToSnapshot.remove(followerId);
489 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
490 logName(), followerId, followerLogInformation.getMatchIndex(),
491 followerLogInformation.getNextIndex());
493 if (mapFollowerToSnapshot.isEmpty()) {
494 // once there are no pending followers receiving snapshots
495 // we can remove snapshot from the memory
499 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
500 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
501 new UnInitializedFollowerSnapshotReply(followerId);
502 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
503 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
506 followerToSnapshot.markSendStatus(true);
509 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
510 logName(), reply.getChunkIndex());
512 followerToSnapshot.markSendStatus(false);
515 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
516 // Since the follower is now caught up try to purge the log.
518 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
519 ActorSelection followerActor = context.getPeerActorSelection(followerId);
520 if(followerActor != null) {
521 sendSnapshotChunk(followerActor, followerId);
526 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
527 logName(), reply.getChunkIndex(), followerId,
528 followerToSnapshot.getChunkIndex());
530 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
531 // Since the Follower did not find this index to be valid we should reset the follower snapshot
532 // so that Installing the snapshot can resume from the beginning
533 followerToSnapshot.reset();
538 private void replicate(Replicate replicate) {
539 long logIndex = replicate.getReplicatedLogEntry().getIndex();
541 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}", logName(),
542 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass());
544 // Create a tracker entry we will use this later to notify the
546 if(replicate.getClientActor() != null) {
547 trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
551 boolean applyModificationToState = !context.anyVotingPeers()
552 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
554 if(applyModificationToState){
555 context.setCommitIndex(logIndex);
556 applyLogToStateMachine(logIndex);
559 if (!followerToLog.isEmpty()) {
560 sendAppendEntries(0, false);
564 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
565 // Send an AppendEntries to all followers
566 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
567 final String followerId = e.getKey();
568 final FollowerLogInformation followerLogInformation = e.getValue();
569 // This checks helps not to send a repeat message to the follower
570 if(!followerLogInformation.isFollowerActive() ||
571 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
572 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
579 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
580 * sending next snapshot chunk, and initiating a snapshot.
581 * @return true if any update is sent, false otherwise
584 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
585 boolean sendHeartbeat, boolean isHeartbeat) {
587 ActorSelection followerActor = context.getPeerActorSelection(followerId);
588 if (followerActor != null) {
589 long followerNextIndex = followerLogInformation.getNextIndex();
590 boolean isFollowerActive = followerLogInformation.isFollowerActive();
591 boolean sendAppendEntries = false;
592 List<ReplicatedLogEntry> entries = Collections.emptyList();
594 if (mapFollowerToSnapshot.get(followerId) != null) {
595 // if install snapshot is in process , then sent next chunk if possible
596 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
597 sendSnapshotChunk(followerActor, followerId);
598 } else if(sendHeartbeat) {
599 // we send a heartbeat even if we have not received a reply for the last chunk
600 sendAppendEntries = true;
603 long leaderLastIndex = context.getReplicatedLog().lastIndex();
604 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
606 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
607 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
608 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
611 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
613 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
614 followerNextIndex, followerId);
616 if(followerLogInformation.okToReplicate()) {
617 // Try to send all the entries in the journal but not exceeding the max data size
618 // for a single AppendEntries message.
619 int maxEntries = (int) context.getReplicatedLog().size();
620 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
621 context.getConfigParams().getSnapshotChunkSize());
622 sendAppendEntries = true;
624 } else if (isFollowerActive && followerNextIndex >= 0 &&
625 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
626 // if the followers next index is not present in the leaders log, and
627 // if the follower is just not starting and if leader's index is more than followers index
628 // then snapshot should be sent
630 if (LOG.isDebugEnabled()) {
631 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s, " +
632 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
633 "leader-last-index: %d", logName(), followerId,
634 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
637 // Send heartbeat to follower whenever install snapshot is initiated.
638 sendAppendEntries = true;
639 if (canInstallSnapshot(followerNextIndex)) {
640 initiateCaptureSnapshot(followerId);
643 } else if(sendHeartbeat) {
644 // we send an AppendEntries, even if the follower is inactive
645 // in-order to update the followers timestamp, in case it becomes active again
646 sendAppendEntries = true;
651 if(sendAppendEntries) {
652 sendAppendEntriesToFollower(followerActor, followerNextIndex,
653 entries, followerId);
658 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
659 List<ReplicatedLogEntry> entries, String followerId) {
660 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
661 getLogEntryIndex(followerNextIndex - 1),
662 getLogEntryTerm(followerNextIndex - 1), entries,
663 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
665 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
666 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
670 followerActor.tell(appendEntries, actor());
674 * Install Snapshot works as follows
675 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
676 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
677 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
678 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
679 * 4. On complete, Follower sends back a InstallSnapshotReply.
680 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
681 * and replenishes the memory by deleting the snapshot in Replicated log.
682 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
683 * then send the existing snapshot in chunks to the follower.
686 public boolean initiateCaptureSnapshot(String followerId) {
687 if (snapshot.isPresent()) {
688 // if a snapshot is present in the memory, most likely another install is in progress
689 // no need to capture snapshot.
690 // This could happen if another follower needs an install when one is going on.
691 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
692 sendSnapshotChunk(followerActor, followerId);
695 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
696 this.getReplicatedToAllIndex(), followerId);
700 private boolean canInstallSnapshot(long nextIndex){
701 // If the follower's nextIndex is -1 then we might as well send it a snapshot
702 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
704 return (nextIndex == -1 ||
705 (!context.getReplicatedLog().isPresent(nextIndex)
706 && context.getReplicatedLog().isInSnapshot(nextIndex)));
711 private void sendInstallSnapshot() {
712 LOG.debug("{}: sendInstallSnapshot", logName());
713 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
714 String followerId = e.getKey();
715 ActorSelection followerActor = context.getPeerActorSelection(followerId);
716 FollowerLogInformation followerLogInfo = e.getValue();
718 if (followerActor != null) {
719 long nextIndex = followerLogInfo.getNextIndex();
720 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
721 canInstallSnapshot(nextIndex)) {
722 sendSnapshotChunk(followerActor, followerId);
729 * Sends a snapshot chunk to a given follower
730 * InstallSnapshot should qualify as a heartbeat too.
732 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
734 if (snapshot.isPresent()) {
735 byte[] nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
737 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
738 // followerId to the followerToSnapshot map.
739 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
741 int nextChunkIndex = followerToSnapshot.incrementChunkIndex();
742 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
743 if(followerToSnapshot.isLastChunk(nextChunkIndex)) {
744 serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
748 new InstallSnapshot(currentTerm(), context.getId(),
749 snapshot.get().getLastIncludedIndex(),
750 snapshot.get().getLastIncludedTerm(),
753 followerToSnapshot.getTotalChunks(),
754 Optional.of(followerToSnapshot.getLastChunkHashCode()),
756 ).toSerializable(followerToLog.get(followerId).getRaftVersion()),
760 if(LOG.isDebugEnabled()) {
761 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
762 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
763 followerToSnapshot.getTotalChunks());
766 } catch (IOException e) {
767 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
772 * Acccepts snaphot as ByteString, enters into map for future chunks
773 * creates and return a ByteString chunk
775 private byte[] getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
776 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
777 if (followerToSnapshot == null) {
778 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
779 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
781 byte[] nextChunk = followerToSnapshot.getNextChunk();
783 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
788 private void sendHeartBeat() {
789 if (!followerToLog.isEmpty()) {
790 LOG.trace("{}: Sending heartbeat", logName());
791 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
795 private void stopHeartBeat() {
796 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
797 heartbeatSchedule.cancel();
801 private void scheduleHeartBeat(FiniteDuration interval) {
802 if (followerToLog.isEmpty()) {
803 // Optimization - do not bother scheduling a heartbeat as there are
810 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
811 // message is sent to itself.
812 // Scheduling the heartbeat only once here because heartbeats do not
813 // need to be sent if there are other messages being sent to the remote
815 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
816 interval, context.getActor(), SendHeartBeat.INSTANCE,
817 context.getActorSystem().dispatcher(), context.getActor());
821 public void close() {
826 public final String getLeaderId() {
827 return context.getId();
831 public final short getLeaderPayloadVersion() {
832 return context.getPayloadVersion();
835 protected boolean isLeaderIsolated() {
836 int minPresent = getMinIsolatedLeaderPeerCount();
837 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
838 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
839 if(peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
841 if (minPresent == 0) {
846 return (minPresent != 0);
850 * Encapsulates the snapshot bytestring and handles the logic of sending
853 protected class FollowerToSnapshot {
854 private final ByteString snapshotBytes;
855 private int offset = 0;
856 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
857 private int replyReceivedForOffset;
858 // if replyStatus is false, the previous chunk is attempted
859 private boolean replyStatus = false;
860 private int chunkIndex;
861 private final int totalChunks;
862 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
863 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
865 public FollowerToSnapshot(ByteString snapshotBytes) {
866 this.snapshotBytes = snapshotBytes;
867 int size = snapshotBytes.size();
868 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
869 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
870 if(LOG.isDebugEnabled()) {
871 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
872 logName(), size, totalChunks);
874 replyReceivedForOffset = -1;
875 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
878 public ByteString getSnapshotBytes() {
879 return snapshotBytes;
882 public int incrementOffset() {
884 // if prev chunk failed, we would want to sent the same chunk again
885 offset = offset + context.getConfigParams().getSnapshotChunkSize();
890 public int incrementChunkIndex() {
892 // if prev chunk failed, we would want to sent the same chunk again
893 chunkIndex = chunkIndex + 1;
898 public int getChunkIndex() {
902 public int getTotalChunks() {
906 public boolean canSendNextChunk() {
907 // we only send a false if a chunk is sent but we have not received a reply yet
908 return replyReceivedForOffset == offset;
911 public boolean isLastChunk(int chunkIndex) {
912 return totalChunks == chunkIndex;
915 public void markSendStatus(boolean success) {
917 // if the chunk sent was successful
918 replyReceivedForOffset = offset;
920 lastChunkHashCode = nextChunkHashCode;
922 // if the chunk sent was failure
923 replyReceivedForOffset = offset;
928 public byte[] getNextChunk() {
929 int snapshotLength = getSnapshotBytes().size();
930 int start = incrementOffset();
931 int size = context.getConfigParams().getSnapshotChunkSize();
932 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
933 size = snapshotLength;
934 } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
935 size = snapshotLength - start;
938 byte[] nextChunk = new byte[size];
939 getSnapshotBytes().copyTo(nextChunk, start, 0, size);
940 nextChunkHashCode = Arrays.hashCode(nextChunk);
942 LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
943 snapshotLength, start, size, nextChunkHashCode);
948 * reset should be called when the Follower needs to be sent the snapshot from the beginning
953 replyReceivedForOffset = offset;
954 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
955 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
958 public int getLastChunkHashCode() {
959 return lastChunkHashCode;
963 // called from example-actor for printing the follower-states
964 public String printFollowerStates() {
965 final StringBuilder sb = new StringBuilder();
968 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
970 sb.append(followerLogInformation.getId());
971 sb.append(" state:");
972 sb.append(followerLogInformation.isFollowerActive());
977 return sb.toString();
981 public FollowerLogInformation getFollower(String followerId) {
982 return followerToLog.get(followerId);
986 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
987 mapFollowerToSnapshot.put(followerId, snapshot);
991 public int followerSnapshotSize() {
992 return mapFollowerToSnapshot.size();
996 public int followerLogSize() {
997 return followerToLog.size();
1000 private static class SnapshotHolder {
1001 private final long lastIncludedTerm;
1002 private final long lastIncludedIndex;
1003 private final ByteString snapshotBytes;
1005 SnapshotHolder(Snapshot snapshot) {
1006 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
1007 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
1008 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
1011 long getLastIncludedTerm() {
1012 return lastIncludedTerm;
1015 long getLastIncludedIndex() {
1016 return lastIncludedIndex;
1019 ByteString getSnapshotBytes() {
1020 return snapshotBytes;