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.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.LinkedList;
24 import java.util.List;
26 import java.util.Map.Entry;
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.Replicate;
39 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
40 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
41 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
42 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
43 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
44 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
45 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
46 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
47 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
48 import scala.concurrent.duration.FiniteDuration;
51 * The behavior of a RaftActor when it is in the Leader state
55 * <li> Upon election: send initial empty AppendEntries RPCs
56 * (heartbeat) to each server; repeat during idle periods to
57 * prevent election timeouts (§5.2)
58 * <li> If command received from client: append entry to local log,
59 * respond after entry applied to state machine (§5.3)
60 * <li> If last log index ≥ nextIndex for a follower: send
61 * AppendEntries RPC with log entries starting at nextIndex
63 * <li> If successful: update nextIndex and matchIndex for
65 * <li> If AppendEntries fails because of log inconsistency:
66 * decrement nextIndex and retry (§5.3)
68 * <li> If there exists an N such that N > commitIndex, a majority
69 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
70 * set commitIndex = N (§5.3, §5.4).
72 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
74 // The index of the first chunk that is sent when installing a snapshot
75 public static final int FIRST_CHUNK_INDEX = 1;
77 // The index that the follower should respond with if it needs the install snapshot to be reset
78 public static final int INVALID_CHUNK_INDEX = -1;
80 // This would be passed as the hash code of the last chunk when sending the first chunk
81 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
83 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
84 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
86 private Cancellable heartbeatSchedule = null;
88 private final Collection<ClientRequestTracker> trackerList = new LinkedList<>();
90 private int minReplicationCount;
92 private Optional<SnapshotHolder> snapshot;
94 public AbstractLeader(RaftActorContext context) {
95 super(context, RaftState.Leader);
97 setLeaderPayloadVersion(context.getPayloadVersion());
99 for(PeerInfo peerInfo: context.getPeers()) {
100 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
101 followerToLog.put(peerInfo.getId(), followerLogInformation);
104 leaderId = context.getId();
106 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
108 updateMinReplicaCount();
110 snapshot = Optional.absent();
112 // Immediately schedule a heartbeat
113 // Upon election: send initial empty AppendEntries RPCs
114 // (heartbeat) to each server; repeat during idle periods to
115 // prevent election timeouts (§5.2)
116 sendAppendEntries(0, false);
118 // It is important to schedule this heartbeat here
119 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
123 * Return an immutable collection of follower identifiers.
125 * @return Collection of follower IDs
127 public final Collection<String> getFollowerIds() {
128 return followerToLog.keySet();
131 public void addFollower(String followerId) {
132 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
133 context.getPeerInfo(followerId), -1, context);
134 followerToLog.put(followerId, followerLogInformation);
136 if(heartbeatSchedule == null) {
137 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
141 public void removeFollower(String followerId) {
142 followerToLog.remove(followerId);
145 public void updateMinReplicaCount() {
147 for(PeerInfo peer: context.getPeers()) {
148 if(peer.isVoting()) {
153 minReplicationCount = getMajorityVoteCount(numVoting);
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
160 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
161 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
162 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
164 return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
168 void setSnapshot(@Nullable Snapshot snapshot) {
169 if(snapshot != null) {
170 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
172 this.snapshot = Optional.absent();
177 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
178 AppendEntries appendEntries) {
180 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
186 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
187 AppendEntriesReply appendEntriesReply) {
189 if(LOG.isTraceEnabled()) {
190 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
193 // Update the FollowerLogInformation
194 String followerId = appendEntriesReply.getFollowerId();
195 FollowerLogInformation followerLogInformation =
196 followerToLog.get(followerId);
198 if(followerLogInformation == null){
199 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
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());
211 followerLogInformation.markFollowerActive();
212 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
214 boolean updated = false;
215 if (appendEntriesReply.isSuccess()) {
216 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
218 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
220 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
221 ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
222 if(appendEntriesReply.isForceInstallSnapshot()) {
223 // Reset the followers match and next index. This is to signal that this follower has nothing
224 // in common with this Leader and so would require a snapshot to be installed
225 followerLogInformation.setMatchIndex(-1);
226 followerLogInformation.setNextIndex(-1);
228 // Force initiate a snapshot capture
229 initiateCaptureSnapshot(followerId);
230 } else if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
231 followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
232 // The follower's log is empty or the last entry is present in the leader's journal
233 // and the terms match so the follower is just behind the leader's journal from
234 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
235 // follower's last log index.
237 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
239 // TODO: When we find that the follower is out of sync with the
240 // Leader we simply decrement that followers next index by 1.
241 // Would it be possible to do better than this? The RAFT spec
242 // does not explicitly deal with it but may be something for us to
245 followerLogInformation.decrNextIndex();
249 // Now figure out if this reply warrants a change in the commitIndex
250 // If there exists an N such that N > commitIndex, a majority
251 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
252 // set commitIndex = N (§5.3, §5.4).
253 for (long N = context.getCommitIndex() + 1; ; N++) {
254 int replicatedCount = 1;
256 for (FollowerLogInformation info : followerToLog.values()) {
257 if ((info.getMatchIndex() >= N) && (context.getPeerInfo(followerId).isVoting())) {
262 if (replicatedCount >= minReplicationCount) {
263 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
264 if (replicatedLogEntry == null) {
268 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
269 // "Raft never commits log entries from previous terms by counting replicas".
270 // However we keep looping so we can make progress when new entries in the current term
271 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
272 // counting replicas, then all prior entries are committed indirectly".
273 if (replicatedLogEntry.getTerm() == currentTerm()) {
274 context.setCommitIndex(N);
281 // Apply the change to the state machine
282 if (context.getCommitIndex() > context.getLastApplied()) {
283 if(LOG.isDebugEnabled()) {
284 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
285 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
288 applyLogToStateMachine(context.getCommitIndex());
291 if (!context.getSnapshotManager().isCapturing()) {
295 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
296 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
300 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
301 AppendEntriesReply appendEntriesReply) {
302 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
303 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
305 if(updated && LOG.isDebugEnabled()) {
306 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
307 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
308 followerLogInformation.getNextIndex());
313 private void purgeInMemoryLog() {
314 //find the lowest index across followers which has been replicated to all.
315 // lastApplied if there are no followers, so that we keep clearing the log for single-node
316 // we would delete the in-mem log from that index on, in-order to minimize mem usage
317 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
318 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
319 for (FollowerLogInformation info : followerToLog.values()) {
320 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
323 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
327 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
328 final Iterator<ClientRequestTracker> it = trackerList.iterator();
329 while (it.hasNext()) {
330 final ClientRequestTracker t = it.next();
331 if (t.getIndex() == logIndex) {
341 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
342 for (ClientRequestTracker tracker : trackerList) {
343 if (tracker.getIndex() == logIndex) {
351 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
352 RequestVoteReply requestVoteReply) {
356 protected void beforeSendHeartbeat(){}
359 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
360 Preconditions.checkNotNull(sender, "sender should not be null");
362 Object message = fromSerializableMessage(originalMessage);
364 if (message instanceof RaftRPC) {
365 RaftRPC rpc = (RaftRPC) message;
366 // If RPC request or response contains term T > currentTerm:
367 // set currentTerm = T, convert to follower (§5.1)
368 // This applies to all RPC messages and responses
369 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
370 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
371 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
373 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
375 return internalSwitchBehavior(RaftState.Follower);
379 if (message instanceof SendHeartBeat) {
380 beforeSendHeartbeat();
382 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
385 } else if(message instanceof SendInstallSnapshot) {
386 // received from RaftActor
387 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
388 sendInstallSnapshot();
390 } else if (message instanceof Replicate) {
391 replicate((Replicate) message);
393 } else if (message instanceof InstallSnapshotReply){
394 handleInstallSnapshotReply((InstallSnapshotReply) message);
399 return super.handleMessage(sender, message);
402 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
403 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
405 String followerId = reply.getFollowerId();
406 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
408 if (followerToSnapshot == null) {
409 LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
410 logName(), followerId);
414 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
415 if(followerLogInformation == null) {
416 // This can happen during AddServer if it times out.
417 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
418 logName(), followerId);
419 mapFollowerToSnapshot.remove(followerId);
423 followerLogInformation.markFollowerActive();
425 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
426 boolean wasLastChunk = false;
427 if (reply.isSuccess()) {
428 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
429 //this was the last chunk reply
430 if(LOG.isDebugEnabled()) {
431 LOG.debug("{}: InstallSnapshotReply received, " +
432 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
433 logName(), reply.getChunkIndex(), followerId,
434 context.getReplicatedLog().getSnapshotIndex() + 1
438 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
439 followerLogInformation.setMatchIndex(followerMatchIndex);
440 followerLogInformation.setNextIndex(followerMatchIndex + 1);
441 mapFollowerToSnapshot.remove(followerId);
443 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
444 logName(), followerId, followerLogInformation.getMatchIndex(),
445 followerLogInformation.getNextIndex());
447 if (mapFollowerToSnapshot.isEmpty()) {
448 // once there are no pending followers receiving snapshots
449 // we can remove snapshot from the memory
453 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
454 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
455 new UnInitializedFollowerSnapshotReply(followerId);
456 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
457 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
460 followerToSnapshot.markSendStatus(true);
463 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
464 logName(), reply.getChunkIndex());
466 followerToSnapshot.markSendStatus(false);
469 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
470 // Since the follower is now caught up try to purge the log.
472 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
473 ActorSelection followerActor = context.getPeerActorSelection(followerId);
474 if(followerActor != null) {
475 sendSnapshotChunk(followerActor, followerId);
480 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
481 logName(), reply.getChunkIndex(), followerId,
482 followerToSnapshot.getChunkIndex());
484 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
485 // Since the Follower did not find this index to be valid we should reset the follower snapshot
486 // so that Installing the snapshot can resume from the beginning
487 followerToSnapshot.reset();
492 private void replicate(Replicate replicate) {
493 long logIndex = replicate.getReplicatedLogEntry().getIndex();
495 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
496 replicate.getIdentifier(), logIndex);
498 // Create a tracker entry we will use this later to notify the
501 new ClientRequestTrackerImpl(replicate.getClientActor(),
502 replicate.getIdentifier(),
506 boolean applyModificationToState = followerToLog.isEmpty()
507 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
509 if(applyModificationToState){
510 context.setCommitIndex(logIndex);
511 applyLogToStateMachine(logIndex);
514 if (!followerToLog.isEmpty()) {
515 sendAppendEntries(0, false);
519 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
520 // Send an AppendEntries to all followers
521 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
522 final String followerId = e.getKey();
523 final FollowerLogInformation followerLogInformation = e.getValue();
524 // This checks helps not to send a repeat message to the follower
525 if(!followerLogInformation.isFollowerActive() ||
526 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
527 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
534 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
535 * sending next snapshot chunk, and initiating a snapshot.
536 * @return true if any update is sent, false otherwise
539 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
540 boolean sendHeartbeat, boolean isHeartbeat) {
542 ActorSelection followerActor = context.getPeerActorSelection(followerId);
543 if (followerActor != null) {
544 long followerNextIndex = followerLogInformation.getNextIndex();
545 boolean isFollowerActive = followerLogInformation.isFollowerActive();
546 boolean sendAppendEntries = false;
547 List<ReplicatedLogEntry> entries = Collections.emptyList();
549 if (mapFollowerToSnapshot.get(followerId) != null) {
550 // if install snapshot is in process , then sent next chunk if possible
551 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
552 sendSnapshotChunk(followerActor, followerId);
553 } else if(sendHeartbeat) {
554 // we send a heartbeat even if we have not received a reply for the last chunk
555 sendAppendEntries = true;
558 long leaderLastIndex = context.getReplicatedLog().lastIndex();
559 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
561 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
562 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
563 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
566 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
568 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
569 followerNextIndex, followerId);
571 if(followerLogInformation.okToReplicate()) {
572 // Try to send all the entries in the journal but not exceeding the max data size
573 // for a single AppendEntries message.
574 int maxEntries = (int) context.getReplicatedLog().size();
575 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
576 context.getConfigParams().getSnapshotChunkSize());
577 sendAppendEntries = true;
579 } else if (isFollowerActive && followerNextIndex >= 0 &&
580 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
581 // if the followers next index is not present in the leaders log, and
582 // if the follower is just not starting and if leader's index is more than followers index
583 // then snapshot should be sent
585 if (LOG.isDebugEnabled()) {
586 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
587 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
588 "leader-last-index: %d", logName(), followerId,
589 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
592 // Send heartbeat to follower whenever install snapshot is initiated.
593 sendAppendEntries = true;
594 if (canInstallSnapshot(followerNextIndex)) {
595 initiateCaptureSnapshot(followerId);
598 } else if(sendHeartbeat) {
599 // we send an AppendEntries, even if the follower is inactive
600 // in-order to update the followers timestamp, in case it becomes active again
601 sendAppendEntries = true;
606 if(sendAppendEntries) {
607 sendAppendEntriesToFollower(followerActor, followerNextIndex,
608 entries, followerId);
613 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
614 List<ReplicatedLogEntry> entries, String followerId) {
615 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
616 prevLogIndex(followerNextIndex),
617 prevLogTerm(followerNextIndex), entries,
618 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
620 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
621 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
625 followerActor.tell(appendEntries.toSerializable(), actor());
629 * Install Snapshot works as follows
630 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
631 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
632 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
633 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
634 * 4. On complete, Follower sends back a InstallSnapshotReply.
635 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
636 * and replenishes the memory by deleting the snapshot in Replicated log.
637 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
638 * then send the existing snapshot in chunks to the follower.
641 public boolean initiateCaptureSnapshot(String followerId) {
642 if (snapshot.isPresent()) {
643 // if a snapshot is present in the memory, most likely another install is in progress
644 // no need to capture snapshot.
645 // This could happen if another follower needs an install when one is going on.
646 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
647 sendSnapshotChunk(followerActor, followerId);
650 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
651 this.getReplicatedToAllIndex(), followerId);
655 private boolean canInstallSnapshot(long nextIndex){
656 // If the follower's nextIndex is -1 then we might as well send it a snapshot
657 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
659 return (nextIndex == -1 ||
660 (!context.getReplicatedLog().isPresent(nextIndex)
661 && context.getReplicatedLog().isInSnapshot(nextIndex)));
666 private void sendInstallSnapshot() {
667 LOG.debug("{}: sendInstallSnapshot", logName());
668 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
669 String followerId = e.getKey();
670 ActorSelection followerActor = context.getPeerActorSelection(followerId);
671 FollowerLogInformation followerLogInfo = e.getValue();
673 if (followerActor != null) {
674 long nextIndex = followerLogInfo.getNextIndex();
675 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
676 canInstallSnapshot(nextIndex)) {
677 sendSnapshotChunk(followerActor, followerId);
684 * Sends a snapshot chunk to a given follower
685 * InstallSnapshot should qualify as a heartbeat too.
687 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
689 if (snapshot.isPresent()) {
690 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
692 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
693 // followerId to the followerToSnapshot map.
694 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
697 new InstallSnapshot(currentTerm(), context.getId(),
698 snapshot.get().getLastIncludedIndex(),
699 snapshot.get().getLastIncludedTerm(),
701 followerToSnapshot.incrementChunkIndex(),
702 followerToSnapshot.getTotalChunks(),
703 Optional.of(followerToSnapshot.getLastChunkHashCode())
708 if(LOG.isDebugEnabled()) {
709 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
710 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
711 followerToSnapshot.getTotalChunks());
714 } catch (IOException e) {
715 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
720 * Acccepts snaphot as ByteString, enters into map for future chunks
721 * creates and return a ByteString chunk
723 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
724 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
725 if (followerToSnapshot == null) {
726 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
727 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
729 ByteString nextChunk = followerToSnapshot.getNextChunk();
731 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
736 private void sendHeartBeat() {
737 if (!followerToLog.isEmpty()) {
738 LOG.trace("{}: Sending heartbeat", logName());
739 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
743 private void stopHeartBeat() {
744 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
745 heartbeatSchedule.cancel();
749 private void scheduleHeartBeat(FiniteDuration interval) {
750 if (followerToLog.isEmpty()) {
751 // Optimization - do not bother scheduling a heartbeat as there are
758 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
759 // message is sent to itself.
760 // Scheduling the heartbeat only once here because heartbeats do not
761 // need to be sent if there are other messages being sent to the remote
763 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
764 interval, context.getActor(), new SendHeartBeat(),
765 context.getActorSystem().dispatcher(), context.getActor());
769 public void close() throws Exception {
774 public String getLeaderId() {
775 return context.getId();
778 protected boolean isLeaderIsolated() {
779 int minPresent = getMinIsolatedLeaderPeerCount();
780 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
781 if (followerLogInformation.isFollowerActive()) {
783 if (minPresent == 0) {
788 return (minPresent != 0);
792 * Encapsulates the snapshot bytestring and handles the logic of sending
795 protected class FollowerToSnapshot {
796 private final ByteString snapshotBytes;
797 private int offset = 0;
798 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
799 private int replyReceivedForOffset;
800 // if replyStatus is false, the previous chunk is attempted
801 private boolean replyStatus = false;
802 private int chunkIndex;
803 private final int totalChunks;
804 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
805 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
807 public FollowerToSnapshot(ByteString snapshotBytes) {
808 this.snapshotBytes = snapshotBytes;
809 int size = snapshotBytes.size();
810 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
811 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
812 if(LOG.isDebugEnabled()) {
813 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
814 logName(), size, totalChunks);
816 replyReceivedForOffset = -1;
817 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
820 public ByteString getSnapshotBytes() {
821 return snapshotBytes;
824 public int incrementOffset() {
826 // if prev chunk failed, we would want to sent the same chunk again
827 offset = offset + context.getConfigParams().getSnapshotChunkSize();
832 public int incrementChunkIndex() {
834 // if prev chunk failed, we would want to sent the same chunk again
835 chunkIndex = chunkIndex + 1;
840 public int getChunkIndex() {
844 public int getTotalChunks() {
848 public boolean canSendNextChunk() {
849 // we only send a false if a chunk is sent but we have not received a reply yet
850 return replyReceivedForOffset == offset;
853 public boolean isLastChunk(int chunkIndex) {
854 return totalChunks == chunkIndex;
857 public void markSendStatus(boolean success) {
859 // if the chunk sent was successful
860 replyReceivedForOffset = offset;
862 lastChunkHashCode = nextChunkHashCode;
864 // if the chunk sent was failure
865 replyReceivedForOffset = offset;
870 public ByteString getNextChunk() {
871 int snapshotLength = getSnapshotBytes().size();
872 int start = incrementOffset();
873 int size = context.getConfigParams().getSnapshotChunkSize();
874 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
875 size = snapshotLength;
877 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
878 size = snapshotLength - start;
883 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
884 snapshotLength, start, size);
886 ByteString substring = getSnapshotBytes().substring(start, start + size);
887 nextChunkHashCode = substring.hashCode();
892 * reset should be called when the Follower needs to be sent the snapshot from the beginning
897 replyReceivedForOffset = offset;
898 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
899 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
902 public int getLastChunkHashCode() {
903 return lastChunkHashCode;
907 // called from example-actor for printing the follower-states
908 public String printFollowerStates() {
909 final StringBuilder sb = new StringBuilder();
912 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
914 sb.append(followerLogInformation.getId());
915 sb.append(" state:");
916 sb.append(followerLogInformation.isFollowerActive());
921 return sb.toString();
925 public FollowerLogInformation getFollower(String followerId) {
926 return followerToLog.get(followerId);
930 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
931 mapFollowerToSnapshot.put(followerId, snapshot);
935 public int followerSnapshotSize() {
936 return mapFollowerToSnapshot.size();
940 public int followerLogSize() {
941 return followerToLog.size();
944 private static class SnapshotHolder {
945 private final long lastIncludedTerm;
946 private final long lastIncludedIndex;
947 private final ByteString snapshotBytes;
949 SnapshotHolder(Snapshot snapshot) {
950 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
951 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
952 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
955 long getLastIncludedTerm() {
956 return lastIncludedTerm;
959 long getLastIncludedIndex() {
960 return lastIncludedIndex;
963 ByteString getSnapshotBytes() {
964 return snapshotBytes;