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) {
262 if (replicatedCount >= minReplicationCount) {
263 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
264 if (replicatedLogEntry != null && replicatedLogEntry.getTerm() == currentTerm()) {
265 context.setCommitIndex(N);
274 // Apply the change to the state machine
275 if (context.getCommitIndex() > context.getLastApplied()) {
276 if(LOG.isDebugEnabled()) {
277 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
278 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
281 applyLogToStateMachine(context.getCommitIndex());
284 if (!context.getSnapshotManager().isCapturing()) {
288 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
289 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
293 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
294 AppendEntriesReply appendEntriesReply) {
295 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
296 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
298 if(updated && LOG.isDebugEnabled()) {
299 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
300 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
301 followerLogInformation.getNextIndex());
306 private void purgeInMemoryLog() {
307 //find the lowest index across followers which has been replicated to all.
308 // lastApplied if there are no followers, so that we keep clearing the log for single-node
309 // we would delete the in-mem log from that index on, in-order to minimize mem usage
310 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
311 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
312 for (FollowerLogInformation info : followerToLog.values()) {
313 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
316 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
320 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
321 final Iterator<ClientRequestTracker> it = trackerList.iterator();
322 while (it.hasNext()) {
323 final ClientRequestTracker t = it.next();
324 if (t.getIndex() == logIndex) {
334 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
335 for (ClientRequestTracker tracker : trackerList) {
336 if (tracker.getIndex() == logIndex) {
344 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
345 RequestVoteReply requestVoteReply) {
349 protected void beforeSendHeartbeat(){}
352 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
353 Preconditions.checkNotNull(sender, "sender should not be null");
355 Object message = fromSerializableMessage(originalMessage);
357 if (message instanceof RaftRPC) {
358 RaftRPC rpc = (RaftRPC) message;
359 // If RPC request or response contains term T > currentTerm:
360 // set currentTerm = T, convert to follower (§5.1)
361 // This applies to all RPC messages and responses
362 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
363 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
364 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
366 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
368 return internalSwitchBehavior(RaftState.Follower);
372 if (message instanceof SendHeartBeat) {
373 beforeSendHeartbeat();
375 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
378 } else if(message instanceof SendInstallSnapshot) {
379 // received from RaftActor
380 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
381 sendInstallSnapshot();
383 } else if (message instanceof Replicate) {
384 replicate((Replicate) message);
386 } else if (message instanceof InstallSnapshotReply){
387 handleInstallSnapshotReply((InstallSnapshotReply) message);
392 return super.handleMessage(sender, message);
395 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
396 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
398 String followerId = reply.getFollowerId();
399 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
401 if (followerToSnapshot == null) {
402 LOG.error("{}: FollowerId {} in InstallSnapshotReply not known to Leader",
403 logName(), followerId);
407 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
408 followerLogInformation.markFollowerActive();
410 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
411 boolean wasLastChunk = false;
412 if (reply.isSuccess()) {
413 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
414 //this was the last chunk reply
415 if(LOG.isDebugEnabled()) {
416 LOG.debug("{}: InstallSnapshotReply received, " +
417 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
418 logName(), reply.getChunkIndex(), followerId,
419 context.getReplicatedLog().getSnapshotIndex() + 1
423 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
424 followerLogInformation.setMatchIndex(followerMatchIndex);
425 followerLogInformation.setNextIndex(followerMatchIndex + 1);
426 mapFollowerToSnapshot.remove(followerId);
428 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
429 logName(), followerId, followerLogInformation.getMatchIndex(),
430 followerLogInformation.getNextIndex());
432 if (mapFollowerToSnapshot.isEmpty()) {
433 // once there are no pending followers receiving snapshots
434 // we can remove snapshot from the memory
438 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
439 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
440 new UnInitializedFollowerSnapshotReply(followerId);
441 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
442 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
445 followerToSnapshot.markSendStatus(true);
448 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
449 logName(), reply.getChunkIndex());
451 followerToSnapshot.markSendStatus(false);
454 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
455 // Since the follower is now caught up try to purge the log.
457 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
458 ActorSelection followerActor = context.getPeerActorSelection(followerId);
459 if(followerActor != null) {
460 sendSnapshotChunk(followerActor, followerId);
465 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
466 logName(), reply.getChunkIndex(), followerId,
467 followerToSnapshot.getChunkIndex());
469 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
470 // Since the Follower did not find this index to be valid we should reset the follower snapshot
471 // so that Installing the snapshot can resume from the beginning
472 followerToSnapshot.reset();
477 private void replicate(Replicate replicate) {
478 long logIndex = replicate.getReplicatedLogEntry().getIndex();
480 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
481 replicate.getIdentifier(), logIndex);
483 // Create a tracker entry we will use this later to notify the
486 new ClientRequestTrackerImpl(replicate.getClientActor(),
487 replicate.getIdentifier(),
491 boolean applyModificationToState = followerToLog.isEmpty()
492 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
494 if(applyModificationToState){
495 context.setCommitIndex(logIndex);
496 applyLogToStateMachine(logIndex);
499 if (!followerToLog.isEmpty()) {
500 sendAppendEntries(0, false);
504 private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
505 // Send an AppendEntries to all followers
506 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
507 final String followerId = e.getKey();
508 final FollowerLogInformation followerLogInformation = e.getValue();
509 // This checks helps not to send a repeat message to the follower
510 if(!followerLogInformation.isFollowerActive() ||
511 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
512 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
519 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
520 * sending next snapshot chunk, and initiating a snapshot.
521 * @return true if any update is sent, false otherwise
524 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
525 boolean sendHeartbeat, boolean isHeartbeat) {
527 ActorSelection followerActor = context.getPeerActorSelection(followerId);
528 if (followerActor != null) {
529 long followerNextIndex = followerLogInformation.getNextIndex();
530 boolean isFollowerActive = followerLogInformation.isFollowerActive();
531 boolean sendAppendEntries = false;
532 List<ReplicatedLogEntry> entries = Collections.emptyList();
534 if (mapFollowerToSnapshot.get(followerId) != null) {
535 // if install snapshot is in process , then sent next chunk if possible
536 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
537 sendSnapshotChunk(followerActor, followerId);
538 } else if(sendHeartbeat) {
539 // we send a heartbeat even if we have not received a reply for the last chunk
540 sendAppendEntries = true;
543 long leaderLastIndex = context.getReplicatedLog().lastIndex();
544 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
546 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
547 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
548 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
551 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
553 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
554 followerNextIndex, followerId);
556 if(followerLogInformation.okToReplicate()) {
557 // Try to send all the entries in the journal but not exceeding the max data size
558 // for a single AppendEntries message.
559 int maxEntries = (int) context.getReplicatedLog().size();
560 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
561 context.getConfigParams().getSnapshotChunkSize());
562 sendAppendEntries = true;
564 } else if (isFollowerActive && followerNextIndex >= 0 &&
565 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
566 // if the followers next index is not present in the leaders log, and
567 // if the follower is just not starting and if leader's index is more than followers index
568 // then snapshot should be sent
570 if (LOG.isDebugEnabled()) {
571 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
572 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
573 "leader-last-index: %d", logName(), followerId,
574 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
577 // Send heartbeat to follower whenever install snapshot is initiated.
578 sendAppendEntries = true;
579 if (canInstallSnapshot(followerNextIndex)) {
580 initiateCaptureSnapshot(followerId);
583 } else if(sendHeartbeat) {
584 // we send an AppendEntries, even if the follower is inactive
585 // in-order to update the followers timestamp, in case it becomes active again
586 sendAppendEntries = true;
591 if(sendAppendEntries) {
592 sendAppendEntriesToFollower(followerActor, followerNextIndex,
593 entries, followerId);
598 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
599 List<ReplicatedLogEntry> entries, String followerId) {
600 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
601 prevLogIndex(followerNextIndex),
602 prevLogTerm(followerNextIndex), entries,
603 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
605 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
606 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
610 followerActor.tell(appendEntries.toSerializable(), actor());
614 * Install Snapshot works as follows
615 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
616 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
617 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
618 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
619 * 4. On complete, Follower sends back a InstallSnapshotReply.
620 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
621 * and replenishes the memory by deleting the snapshot in Replicated log.
622 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
623 * then send the existing snapshot in chunks to the follower.
626 public void initiateCaptureSnapshot(String followerId) {
627 if (snapshot.isPresent()) {
628 // if a snapshot is present in the memory, most likely another install is in progress
629 // no need to capture snapshot.
630 // This could happen if another follower needs an install when one is going on.
631 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
632 sendSnapshotChunk(followerActor, followerId);
636 context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
637 this.getReplicatedToAllIndex(), followerId);
641 private boolean canInstallSnapshot(long nextIndex){
642 // If the follower's nextIndex is -1 then we might as well send it a snapshot
643 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
645 return (nextIndex == -1 ||
646 (!context.getReplicatedLog().isPresent(nextIndex)
647 && context.getReplicatedLog().isInSnapshot(nextIndex)));
652 private void sendInstallSnapshot() {
653 LOG.debug("{}: sendInstallSnapshot", logName());
654 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
655 String followerId = e.getKey();
656 ActorSelection followerActor = context.getPeerActorSelection(followerId);
657 FollowerLogInformation followerLogInfo = e.getValue();
659 if (followerActor != null) {
660 long nextIndex = followerLogInfo.getNextIndex();
661 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
662 canInstallSnapshot(nextIndex)) {
663 sendSnapshotChunk(followerActor, followerId);
670 * Sends a snapshot chunk to a given follower
671 * InstallSnapshot should qualify as a heartbeat too.
673 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
675 if (snapshot.isPresent()) {
676 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
678 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
679 // followerId to the followerToSnapshot map.
680 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
683 new InstallSnapshot(currentTerm(), context.getId(),
684 snapshot.get().getLastIncludedIndex(),
685 snapshot.get().getLastIncludedTerm(),
687 followerToSnapshot.incrementChunkIndex(),
688 followerToSnapshot.getTotalChunks(),
689 Optional.of(followerToSnapshot.getLastChunkHashCode())
694 if(LOG.isDebugEnabled()) {
695 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
696 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
697 followerToSnapshot.getTotalChunks());
700 } catch (IOException e) {
701 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
706 * Acccepts snaphot as ByteString, enters into map for future chunks
707 * creates and return a ByteString chunk
709 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
710 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
711 if (followerToSnapshot == null) {
712 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
713 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
715 ByteString nextChunk = followerToSnapshot.getNextChunk();
717 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
722 private void sendHeartBeat() {
723 if (!followerToLog.isEmpty()) {
724 LOG.trace("{}: Sending heartbeat", logName());
725 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
729 private void stopHeartBeat() {
730 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
731 heartbeatSchedule.cancel();
735 private void scheduleHeartBeat(FiniteDuration interval) {
736 if (followerToLog.isEmpty()) {
737 // Optimization - do not bother scheduling a heartbeat as there are
744 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
745 // message is sent to itself.
746 // Scheduling the heartbeat only once here because heartbeats do not
747 // need to be sent if there are other messages being sent to the remote
749 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
750 interval, context.getActor(), new SendHeartBeat(),
751 context.getActorSystem().dispatcher(), context.getActor());
755 public void close() throws Exception {
760 public String getLeaderId() {
761 return context.getId();
764 protected boolean isLeaderIsolated() {
765 int minPresent = getMinIsolatedLeaderPeerCount();
766 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
767 if (followerLogInformation.isFollowerActive()) {
769 if (minPresent == 0) {
774 return (minPresent != 0);
778 * Encapsulates the snapshot bytestring and handles the logic of sending
781 protected class FollowerToSnapshot {
782 private final ByteString snapshotBytes;
783 private int offset = 0;
784 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
785 private int replyReceivedForOffset;
786 // if replyStatus is false, the previous chunk is attempted
787 private boolean replyStatus = false;
788 private int chunkIndex;
789 private final int totalChunks;
790 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
791 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
793 public FollowerToSnapshot(ByteString snapshotBytes) {
794 this.snapshotBytes = snapshotBytes;
795 int size = snapshotBytes.size();
796 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
797 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
798 if(LOG.isDebugEnabled()) {
799 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
800 logName(), size, totalChunks);
802 replyReceivedForOffset = -1;
803 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
806 public ByteString getSnapshotBytes() {
807 return snapshotBytes;
810 public int incrementOffset() {
812 // if prev chunk failed, we would want to sent the same chunk again
813 offset = offset + context.getConfigParams().getSnapshotChunkSize();
818 public int incrementChunkIndex() {
820 // if prev chunk failed, we would want to sent the same chunk again
821 chunkIndex = chunkIndex + 1;
826 public int getChunkIndex() {
830 public int getTotalChunks() {
834 public boolean canSendNextChunk() {
835 // we only send a false if a chunk is sent but we have not received a reply yet
836 return replyReceivedForOffset == offset;
839 public boolean isLastChunk(int chunkIndex) {
840 return totalChunks == chunkIndex;
843 public void markSendStatus(boolean success) {
845 // if the chunk sent was successful
846 replyReceivedForOffset = offset;
848 lastChunkHashCode = nextChunkHashCode;
850 // if the chunk sent was failure
851 replyReceivedForOffset = offset;
856 public ByteString getNextChunk() {
857 int snapshotLength = getSnapshotBytes().size();
858 int start = incrementOffset();
859 int size = context.getConfigParams().getSnapshotChunkSize();
860 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
861 size = snapshotLength;
863 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
864 size = snapshotLength - start;
869 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
870 snapshotLength, start, size);
872 ByteString substring = getSnapshotBytes().substring(start, start + size);
873 nextChunkHashCode = substring.hashCode();
878 * reset should be called when the Follower needs to be sent the snapshot from the beginning
883 replyReceivedForOffset = offset;
884 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
885 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
888 public int getLastChunkHashCode() {
889 return lastChunkHashCode;
893 // called from example-actor for printing the follower-states
894 public String printFollowerStates() {
895 final StringBuilder sb = new StringBuilder();
898 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
900 sb.append(followerLogInformation.getId());
901 sb.append(" state:");
902 sb.append(followerLogInformation.isFollowerActive());
907 return sb.toString();
911 public FollowerLogInformation getFollower(String followerId) {
912 return followerToLog.get(followerId);
916 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
917 mapFollowerToSnapshot.put(followerId, snapshot);
921 public int followerSnapshotSize() {
922 return mapFollowerToSnapshot.size();
926 public int followerLogSize() {
927 return followerToLog.size();
930 private static class SnapshotHolder {
931 private final long lastIncludedTerm;
932 private final long lastIncludedIndex;
933 private final ByteString snapshotBytes;
935 SnapshotHolder(Snapshot snapshot) {
936 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
937 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
938 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
941 long getLastIncludedTerm() {
942 return lastIncludedTerm;
945 long getLastIncludedIndex() {
946 return lastIncludedIndex;
949 ByteString getSnapshotBytes() {
950 return snapshotBytes;