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 scala.concurrent.duration.FiniteDuration;
53 * The behavior of a RaftActor when it is in the Leader state
57 * <li> Upon election: send initial empty AppendEntries RPCs
58 * (heartbeat) to each server; repeat during idle periods to
59 * prevent election timeouts (§5.2)
60 * <li> If command received from client: append entry to local log,
61 * respond after entry applied to state machine (§5.3)
62 * <li> If last log index ≥ nextIndex for a follower: send
63 * AppendEntries RPC with log entries starting at nextIndex
65 * <li> If successful: update nextIndex and matchIndex for
67 * <li> If AppendEntries fails because of log inconsistency:
68 * decrement nextIndex and retry (§5.3)
70 * <li> If there exists an N such that N > commitIndex, a majority
71 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
72 * set commitIndex = N (§5.3, §5.4).
74 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
76 // The index of the first chunk that is sent when installing a snapshot
77 public static final int FIRST_CHUNK_INDEX = 1;
79 // The index that the follower should respond with if it needs the install snapshot to be reset
80 public static final int INVALID_CHUNK_INDEX = -1;
82 // This would be passed as the hash code of the last chunk when sending the first chunk
83 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
85 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
86 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
89 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
90 * expect the entries to be modified in sequence, hence we open-code the lookup.
92 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
93 * but we already expect those to be far from frequent.
95 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
97 private Cancellable heartbeatSchedule = null;
98 private Optional<SnapshotHolder> snapshot;
99 private int minReplicationCount;
101 protected AbstractLeader(RaftActorContext context, RaftState state) {
102 super(context, state);
104 for(PeerInfo peerInfo: context.getPeers()) {
105 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
106 followerToLog.put(peerInfo.getId(), followerLogInformation);
109 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
111 updateMinReplicaCount();
113 snapshot = Optional.absent();
115 // Immediately schedule a heartbeat
116 // Upon election: send initial empty AppendEntries RPCs
117 // (heartbeat) to each server; repeat during idle periods to
118 // prevent election timeouts (§5.2)
119 sendAppendEntries(0, false);
121 // It is important to schedule this heartbeat here
122 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
126 * Return an immutable collection of follower identifiers.
128 * @return Collection of follower IDs
130 public final Collection<String> getFollowerIds() {
131 return followerToLog.keySet();
134 public void addFollower(String followerId) {
135 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
136 context.getPeerInfo(followerId), -1, context);
137 followerToLog.put(followerId, followerLogInformation);
139 if(heartbeatSchedule == null) {
140 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
144 public void removeFollower(String followerId) {
145 followerToLog.remove(followerId);
146 mapFollowerToSnapshot.remove(followerId);
149 public void updateMinReplicaCount() {
151 for(PeerInfo peer: context.getPeers()) {
152 if(peer.isVoting()) {
157 minReplicationCount = getMajorityVoteCount(numVoting);
160 protected int getMinIsolatedLeaderPeerCount(){
161 //the isolated Leader peer count will be 1 less than the majority vote count.
162 //this is because the vote count has the self vote counted in it
164 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
165 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
166 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
168 return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
172 void setSnapshot(@Nullable Snapshot snapshot) {
173 if(snapshot != null) {
174 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
176 this.snapshot = Optional.absent();
181 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
182 AppendEntries appendEntries) {
184 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
190 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
191 AppendEntriesReply appendEntriesReply) {
193 if(LOG.isTraceEnabled()) {
194 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
197 // Update the FollowerLogInformation
198 String followerId = appendEntriesReply.getFollowerId();
199 FollowerLogInformation followerLogInformation =
200 followerToLog.get(followerId);
202 if(followerLogInformation == null){
203 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
207 if(followerLogInformation.timeSinceLastActivity() >
208 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
209 LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
210 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
211 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
212 context.getLastApplied(), context.getCommitIndex());
215 followerLogInformation.markFollowerActive();
216 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
217 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
219 boolean updated = false;
220 if (appendEntriesReply.isSuccess()) {
221 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
223 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
225 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
226 ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
227 if(appendEntriesReply.isForceInstallSnapshot()) {
228 // Reset the followers match and next index. This is to signal that this follower has nothing
229 // in common with this Leader and so would require a snapshot to be installed
230 followerLogInformation.setMatchIndex(-1);
231 followerLogInformation.setNextIndex(-1);
233 // Force initiate a snapshot capture
234 initiateCaptureSnapshot(followerId);
235 } else if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
236 followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
237 // The follower's log is empty or the last entry is present in the leader's journal
238 // and the terms match so the follower is just behind the leader's journal from
239 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
240 // follower's last log index.
242 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
244 // TODO: When we find that the follower is out of sync with the
245 // Leader we simply decrement that followers next index by 1.
246 // Would it be possible to do better than this? The RAFT spec
247 // does not explicitly deal with it but may be something for us to
250 followerLogInformation.decrNextIndex();
254 // Now figure out if this reply warrants a change in the commitIndex
255 // If there exists an N such that N > commitIndex, a majority
256 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
257 // set commitIndex = N (§5.3, §5.4).
258 for (long N = context.getCommitIndex() + 1; ; N++) {
259 int replicatedCount = 1;
261 for (FollowerLogInformation info : followerToLog.values()) {
262 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
263 if(info.getMatchIndex() >= N && (peerInfo != null && peerInfo.isVoting())) {
268 if (replicatedCount >= minReplicationCount) {
269 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
270 if (replicatedLogEntry == null) {
274 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
275 // "Raft never commits log entries from previous terms by counting replicas".
276 // However we keep looping so we can make progress when new entries in the current term
277 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
278 // counting replicas, then all prior entries are committed indirectly".
279 if (replicatedLogEntry.getTerm() == currentTerm()) {
280 context.setCommitIndex(N);
287 // Apply the change to the state machine
288 if (context.getCommitIndex() > context.getLastApplied()) {
289 if(LOG.isDebugEnabled()) {
290 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
291 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
294 applyLogToStateMachine(context.getCommitIndex());
297 if (!context.getSnapshotManager().isCapturing()) {
301 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
302 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
306 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
307 AppendEntriesReply appendEntriesReply) {
308 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
309 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
311 if(updated && LOG.isDebugEnabled()) {
312 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
313 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
314 followerLogInformation.getNextIndex());
319 private void purgeInMemoryLog() {
320 //find the lowest index across followers which has been replicated to all.
321 // lastApplied if there are no followers, so that we keep clearing the log for single-node
322 // we would delete the in-mem log from that index on, in-order to minimize mem usage
323 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
324 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
325 for (FollowerLogInformation info : followerToLog.values()) {
326 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
329 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
333 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
334 final Iterator<ClientRequestTracker> it = trackers.iterator();
335 while (it.hasNext()) {
336 final ClientRequestTracker t = it.next();
337 if (t.getIndex() == logIndex) {
347 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
348 RequestVoteReply requestVoteReply) {
352 protected void beforeSendHeartbeat(){}
355 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
356 Preconditions.checkNotNull(sender, "sender should not be null");
358 Object message = fromSerializableMessage(originalMessage);
360 if (message instanceof RaftRPC) {
361 RaftRPC rpc = (RaftRPC) message;
362 // If RPC request or response contains term T > currentTerm:
363 // set currentTerm = T, convert to follower (§5.1)
364 // This applies to all RPC messages and responses
365 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
366 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
367 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
369 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
371 return internalSwitchBehavior(RaftState.Follower);
375 if (message instanceof SendHeartBeat) {
376 beforeSendHeartbeat();
378 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
379 } else if(message instanceof SendInstallSnapshot) {
380 // received from RaftActor
381 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
382 sendInstallSnapshot();
383 } else if (message instanceof Replicate) {
384 replicate((Replicate) message);
385 } else if (message instanceof InstallSnapshotReply) {
386 handleInstallSnapshotReply((InstallSnapshotReply) message);
388 return super.handleMessage(sender, message);
394 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
395 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
397 String followerId = reply.getFollowerId();
398 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
400 if (followerToSnapshot == null) {
401 LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
402 logName(), followerId);
406 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
407 if(followerLogInformation == null) {
408 // This can happen during AddServer if it times out.
409 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
410 logName(), followerId);
411 mapFollowerToSnapshot.remove(followerId);
415 followerLogInformation.markFollowerActive();
417 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
418 boolean wasLastChunk = false;
419 if (reply.isSuccess()) {
420 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
421 //this was the last chunk reply
422 if(LOG.isDebugEnabled()) {
423 LOG.debug("{}: InstallSnapshotReply received, " +
424 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
425 logName(), reply.getChunkIndex(), followerId,
426 context.getReplicatedLog().getSnapshotIndex() + 1
430 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
431 followerLogInformation.setMatchIndex(followerMatchIndex);
432 followerLogInformation.setNextIndex(followerMatchIndex + 1);
433 mapFollowerToSnapshot.remove(followerId);
435 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
436 logName(), followerId, followerLogInformation.getMatchIndex(),
437 followerLogInformation.getNextIndex());
439 if (mapFollowerToSnapshot.isEmpty()) {
440 // once there are no pending followers receiving snapshots
441 // we can remove snapshot from the memory
445 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
446 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
447 new UnInitializedFollowerSnapshotReply(followerId);
448 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
449 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
452 followerToSnapshot.markSendStatus(true);
455 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
456 logName(), reply.getChunkIndex());
458 followerToSnapshot.markSendStatus(false);
461 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
462 // Since the follower is now caught up try to purge the log.
464 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
465 ActorSelection followerActor = context.getPeerActorSelection(followerId);
466 if(followerActor != null) {
467 sendSnapshotChunk(followerActor, followerId);
472 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
473 logName(), reply.getChunkIndex(), followerId,
474 followerToSnapshot.getChunkIndex());
476 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
477 // Since the Follower did not find this index to be valid we should reset the follower snapshot
478 // so that Installing the snapshot can resume from the beginning
479 followerToSnapshot.reset();
484 private void replicate(Replicate replicate) {
485 long logIndex = replicate.getReplicatedLogEntry().getIndex();
487 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
488 replicate.getIdentifier(), logIndex);
490 // Create a tracker entry we will use this later to notify the
493 new ClientRequestTrackerImpl(replicate.getClientActor(),
494 replicate.getIdentifier(),
498 boolean applyModificationToState = followerToLog.isEmpty()
499 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
501 if(applyModificationToState){
502 context.setCommitIndex(logIndex);
503 applyLogToStateMachine(logIndex);
506 if (!followerToLog.isEmpty()) {
507 sendAppendEntries(0, false);
511 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
512 // Send an AppendEntries to all followers
513 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
514 final String followerId = e.getKey();
515 final FollowerLogInformation followerLogInformation = e.getValue();
516 // This checks helps not to send a repeat message to the follower
517 if(!followerLogInformation.isFollowerActive() ||
518 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
519 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
526 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
527 * sending next snapshot chunk, and initiating a snapshot.
528 * @return true if any update is sent, false otherwise
531 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
532 boolean sendHeartbeat, boolean isHeartbeat) {
534 ActorSelection followerActor = context.getPeerActorSelection(followerId);
535 if (followerActor != null) {
536 long followerNextIndex = followerLogInformation.getNextIndex();
537 boolean isFollowerActive = followerLogInformation.isFollowerActive();
538 boolean sendAppendEntries = false;
539 List<ReplicatedLogEntry> entries = Collections.emptyList();
541 if (mapFollowerToSnapshot.get(followerId) != null) {
542 // if install snapshot is in process , then sent next chunk if possible
543 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
544 sendSnapshotChunk(followerActor, followerId);
545 } else if(sendHeartbeat) {
546 // we send a heartbeat even if we have not received a reply for the last chunk
547 sendAppendEntries = true;
550 long leaderLastIndex = context.getReplicatedLog().lastIndex();
551 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
553 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
554 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
555 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
558 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
560 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
561 followerNextIndex, followerId);
563 if(followerLogInformation.okToReplicate()) {
564 // Try to send all the entries in the journal but not exceeding the max data size
565 // for a single AppendEntries message.
566 int maxEntries = (int) context.getReplicatedLog().size();
567 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
568 context.getConfigParams().getSnapshotChunkSize());
569 sendAppendEntries = true;
571 } else if (isFollowerActive && followerNextIndex >= 0 &&
572 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
573 // if the followers next index is not present in the leaders log, and
574 // if the follower is just not starting and if leader's index is more than followers index
575 // then snapshot should be sent
577 if (LOG.isDebugEnabled()) {
578 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
579 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
580 "leader-last-index: %d", logName(), followerId,
581 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
584 // Send heartbeat to follower whenever install snapshot is initiated.
585 sendAppendEntries = true;
586 if (canInstallSnapshot(followerNextIndex)) {
587 initiateCaptureSnapshot(followerId);
590 } else if(sendHeartbeat) {
591 // we send an AppendEntries, even if the follower is inactive
592 // in-order to update the followers timestamp, in case it becomes active again
593 sendAppendEntries = true;
598 if(sendAppendEntries) {
599 sendAppendEntriesToFollower(followerActor, followerNextIndex,
600 entries, followerId);
605 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
606 List<ReplicatedLogEntry> entries, String followerId) {
607 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
608 prevLogIndex(followerNextIndex),
609 prevLogTerm(followerNextIndex), entries,
610 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
612 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
613 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
617 followerActor.tell(appendEntries, actor());
621 * Install Snapshot works as follows
622 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
623 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
624 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
625 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
626 * 4. On complete, Follower sends back a InstallSnapshotReply.
627 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
628 * and replenishes the memory by deleting the snapshot in Replicated log.
629 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
630 * then send the existing snapshot in chunks to the follower.
633 public boolean initiateCaptureSnapshot(String followerId) {
634 if (snapshot.isPresent()) {
635 // if a snapshot is present in the memory, most likely another install is in progress
636 // no need to capture snapshot.
637 // This could happen if another follower needs an install when one is going on.
638 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
639 sendSnapshotChunk(followerActor, followerId);
642 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
643 this.getReplicatedToAllIndex(), followerId);
647 private boolean canInstallSnapshot(long nextIndex){
648 // If the follower's nextIndex is -1 then we might as well send it a snapshot
649 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
651 return (nextIndex == -1 ||
652 (!context.getReplicatedLog().isPresent(nextIndex)
653 && context.getReplicatedLog().isInSnapshot(nextIndex)));
658 private void sendInstallSnapshot() {
659 LOG.debug("{}: sendInstallSnapshot", logName());
660 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
661 String followerId = e.getKey();
662 ActorSelection followerActor = context.getPeerActorSelection(followerId);
663 FollowerLogInformation followerLogInfo = e.getValue();
665 if (followerActor != null) {
666 long nextIndex = followerLogInfo.getNextIndex();
667 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
668 canInstallSnapshot(nextIndex)) {
669 sendSnapshotChunk(followerActor, followerId);
676 * Sends a snapshot chunk to a given follower
677 * InstallSnapshot should qualify as a heartbeat too.
679 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
681 if (snapshot.isPresent()) {
682 byte[] nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
684 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
685 // followerId to the followerToSnapshot map.
686 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
689 new InstallSnapshot(currentTerm(), context.getId(),
690 snapshot.get().getLastIncludedIndex(),
691 snapshot.get().getLastIncludedTerm(),
693 followerToSnapshot.incrementChunkIndex(),
694 followerToSnapshot.getTotalChunks(),
695 Optional.of(followerToSnapshot.getLastChunkHashCode())
696 ).toSerializable(followerToLog.get(followerId).getRaftVersion()),
700 if(LOG.isDebugEnabled()) {
701 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
702 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
703 followerToSnapshot.getTotalChunks());
706 } catch (IOException e) {
707 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
712 * Acccepts snaphot as ByteString, enters into map for future chunks
713 * creates and return a ByteString chunk
715 private byte[] getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
716 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
717 if (followerToSnapshot == null) {
718 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
719 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
721 byte[] nextChunk = followerToSnapshot.getNextChunk();
723 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
728 private void sendHeartBeat() {
729 if (!followerToLog.isEmpty()) {
730 LOG.trace("{}: Sending heartbeat", logName());
731 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
735 private void stopHeartBeat() {
736 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
737 heartbeatSchedule.cancel();
741 private void scheduleHeartBeat(FiniteDuration interval) {
742 if (followerToLog.isEmpty()) {
743 // Optimization - do not bother scheduling a heartbeat as there are
750 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
751 // message is sent to itself.
752 // Scheduling the heartbeat only once here because heartbeats do not
753 // need to be sent if there are other messages being sent to the remote
755 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
756 interval, context.getActor(), SendHeartBeat.INSTANCE,
757 context.getActorSystem().dispatcher(), context.getActor());
761 public void close() {
766 public final String getLeaderId() {
767 return context.getId();
771 public final short getLeaderPayloadVersion() {
772 return context.getPayloadVersion();
775 protected boolean isLeaderIsolated() {
776 int minPresent = getMinIsolatedLeaderPeerCount();
777 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
778 if (followerLogInformation.isFollowerActive()) {
780 if (minPresent == 0) {
785 return (minPresent != 0);
789 * Encapsulates the snapshot bytestring and handles the logic of sending
792 protected class FollowerToSnapshot {
793 private final ByteString snapshotBytes;
794 private int offset = 0;
795 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
796 private int replyReceivedForOffset;
797 // if replyStatus is false, the previous chunk is attempted
798 private boolean replyStatus = false;
799 private int chunkIndex;
800 private final int totalChunks;
801 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
802 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
804 public FollowerToSnapshot(ByteString snapshotBytes) {
805 this.snapshotBytes = snapshotBytes;
806 int size = snapshotBytes.size();
807 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
808 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
809 if(LOG.isDebugEnabled()) {
810 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
811 logName(), size, totalChunks);
813 replyReceivedForOffset = -1;
814 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
817 public ByteString getSnapshotBytes() {
818 return snapshotBytes;
821 public int incrementOffset() {
823 // if prev chunk failed, we would want to sent the same chunk again
824 offset = offset + context.getConfigParams().getSnapshotChunkSize();
829 public int incrementChunkIndex() {
831 // if prev chunk failed, we would want to sent the same chunk again
832 chunkIndex = chunkIndex + 1;
837 public int getChunkIndex() {
841 public int getTotalChunks() {
845 public boolean canSendNextChunk() {
846 // we only send a false if a chunk is sent but we have not received a reply yet
847 return replyReceivedForOffset == offset;
850 public boolean isLastChunk(int chunkIndex) {
851 return totalChunks == chunkIndex;
854 public void markSendStatus(boolean success) {
856 // if the chunk sent was successful
857 replyReceivedForOffset = offset;
859 lastChunkHashCode = nextChunkHashCode;
861 // if the chunk sent was failure
862 replyReceivedForOffset = offset;
867 public byte[] getNextChunk() {
868 int snapshotLength = getSnapshotBytes().size();
869 int start = incrementOffset();
870 int size = context.getConfigParams().getSnapshotChunkSize();
871 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
872 size = snapshotLength;
873 } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
874 size = snapshotLength - start;
877 byte[] nextChunk = new byte[size];
878 getSnapshotBytes().copyTo(nextChunk, start, 0, size);
879 nextChunkHashCode = Arrays.hashCode(nextChunk);
881 LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
882 snapshotLength, start, size, nextChunkHashCode);
887 * reset should be called when the Follower needs to be sent the snapshot from the beginning
892 replyReceivedForOffset = offset;
893 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
894 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
897 public int getLastChunkHashCode() {
898 return lastChunkHashCode;
902 // called from example-actor for printing the follower-states
903 public String printFollowerStates() {
904 final StringBuilder sb = new StringBuilder();
907 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
909 sb.append(followerLogInformation.getId());
910 sb.append(" state:");
911 sb.append(followerLogInformation.isFollowerActive());
916 return sb.toString();
920 public FollowerLogInformation getFollower(String followerId) {
921 return followerToLog.get(followerId);
925 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
926 mapFollowerToSnapshot.put(followerId, snapshot);
930 public int followerSnapshotSize() {
931 return mapFollowerToSnapshot.size();
935 public int followerLogSize() {
936 return followerToLog.size();
939 private static class SnapshotHolder {
940 private final long lastIncludedTerm;
941 private final long lastIncludedIndex;
942 private final ByteString snapshotBytes;
944 SnapshotHolder(Snapshot snapshot) {
945 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
946 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
947 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
950 long getLastIncludedTerm() {
951 return lastIncludedTerm;
954 long getLastIncludedIndex() {
955 return lastIncludedIndex;
958 ByteString getSnapshotBytes() {
959 return snapshotBytes;