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 && 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("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
403 logName(), followerId);
407 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
408 if(followerLogInformation == null) {
409 // This can happen during AddServer if it times out.
410 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
411 logName(), followerId);
412 mapFollowerToSnapshot.remove(followerId);
416 followerLogInformation.markFollowerActive();
418 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
419 boolean wasLastChunk = false;
420 if (reply.isSuccess()) {
421 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
422 //this was the last chunk reply
423 if(LOG.isDebugEnabled()) {
424 LOG.debug("{}: InstallSnapshotReply received, " +
425 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
426 logName(), reply.getChunkIndex(), followerId,
427 context.getReplicatedLog().getSnapshotIndex() + 1
431 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
432 followerLogInformation.setMatchIndex(followerMatchIndex);
433 followerLogInformation.setNextIndex(followerMatchIndex + 1);
434 mapFollowerToSnapshot.remove(followerId);
436 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
437 logName(), followerId, followerLogInformation.getMatchIndex(),
438 followerLogInformation.getNextIndex());
440 if (mapFollowerToSnapshot.isEmpty()) {
441 // once there are no pending followers receiving snapshots
442 // we can remove snapshot from the memory
446 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
447 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
448 new UnInitializedFollowerSnapshotReply(followerId);
449 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
450 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
453 followerToSnapshot.markSendStatus(true);
456 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
457 logName(), reply.getChunkIndex());
459 followerToSnapshot.markSendStatus(false);
462 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
463 // Since the follower is now caught up try to purge the log.
465 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
466 ActorSelection followerActor = context.getPeerActorSelection(followerId);
467 if(followerActor != null) {
468 sendSnapshotChunk(followerActor, followerId);
473 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
474 logName(), reply.getChunkIndex(), followerId,
475 followerToSnapshot.getChunkIndex());
477 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
478 // Since the Follower did not find this index to be valid we should reset the follower snapshot
479 // so that Installing the snapshot can resume from the beginning
480 followerToSnapshot.reset();
485 private void replicate(Replicate replicate) {
486 long logIndex = replicate.getReplicatedLogEntry().getIndex();
488 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
489 replicate.getIdentifier(), logIndex);
491 // Create a tracker entry we will use this later to notify the
494 new ClientRequestTrackerImpl(replicate.getClientActor(),
495 replicate.getIdentifier(),
499 boolean applyModificationToState = followerToLog.isEmpty()
500 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
502 if(applyModificationToState){
503 context.setCommitIndex(logIndex);
504 applyLogToStateMachine(logIndex);
507 if (!followerToLog.isEmpty()) {
508 sendAppendEntries(0, false);
512 private void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
513 // Send an AppendEntries to all followers
514 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
515 final String followerId = e.getKey();
516 final FollowerLogInformation followerLogInformation = e.getValue();
517 // This checks helps not to send a repeat message to the follower
518 if(!followerLogInformation.isFollowerActive() ||
519 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
520 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
527 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
528 * sending next snapshot chunk, and initiating a snapshot.
529 * @return true if any update is sent, false otherwise
532 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
533 boolean sendHeartbeat, boolean isHeartbeat) {
535 ActorSelection followerActor = context.getPeerActorSelection(followerId);
536 if (followerActor != null) {
537 long followerNextIndex = followerLogInformation.getNextIndex();
538 boolean isFollowerActive = followerLogInformation.isFollowerActive();
539 boolean sendAppendEntries = false;
540 List<ReplicatedLogEntry> entries = Collections.emptyList();
542 if (mapFollowerToSnapshot.get(followerId) != null) {
543 // if install snapshot is in process , then sent next chunk if possible
544 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
545 sendSnapshotChunk(followerActor, followerId);
546 } else if(sendHeartbeat) {
547 // we send a heartbeat even if we have not received a reply for the last chunk
548 sendAppendEntries = true;
551 long leaderLastIndex = context.getReplicatedLog().lastIndex();
552 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
554 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
555 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
556 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
559 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
561 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
562 followerNextIndex, followerId);
564 if(followerLogInformation.okToReplicate()) {
565 // Try to send all the entries in the journal but not exceeding the max data size
566 // for a single AppendEntries message.
567 int maxEntries = (int) context.getReplicatedLog().size();
568 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
569 context.getConfigParams().getSnapshotChunkSize());
570 sendAppendEntries = true;
572 } else if (isFollowerActive && followerNextIndex >= 0 &&
573 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
574 // if the followers next index is not present in the leaders log, and
575 // if the follower is just not starting and if leader's index is more than followers index
576 // then snapshot should be sent
578 if (LOG.isDebugEnabled()) {
579 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
580 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
581 "leader-last-index: %d", logName(), followerId,
582 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
585 // Send heartbeat to follower whenever install snapshot is initiated.
586 sendAppendEntries = true;
587 if (canInstallSnapshot(followerNextIndex)) {
588 initiateCaptureSnapshot(followerId);
591 } else if(sendHeartbeat) {
592 // we send an AppendEntries, even if the follower is inactive
593 // in-order to update the followers timestamp, in case it becomes active again
594 sendAppendEntries = true;
599 if(sendAppendEntries) {
600 sendAppendEntriesToFollower(followerActor, followerNextIndex,
601 entries, followerId);
606 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
607 List<ReplicatedLogEntry> entries, String followerId) {
608 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
609 prevLogIndex(followerNextIndex),
610 prevLogTerm(followerNextIndex), entries,
611 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
613 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
614 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
618 followerActor.tell(appendEntries.toSerializable(), actor());
622 * Install Snapshot works as follows
623 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
624 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
625 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
626 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
627 * 4. On complete, Follower sends back a InstallSnapshotReply.
628 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
629 * and replenishes the memory by deleting the snapshot in Replicated log.
630 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
631 * then send the existing snapshot in chunks to the follower.
634 public boolean initiateCaptureSnapshot(String followerId) {
635 if (snapshot.isPresent()) {
636 // if a snapshot is present in the memory, most likely another install is in progress
637 // no need to capture snapshot.
638 // This could happen if another follower needs an install when one is going on.
639 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
640 sendSnapshotChunk(followerActor, followerId);
643 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
644 this.getReplicatedToAllIndex(), followerId);
648 private boolean canInstallSnapshot(long nextIndex){
649 // If the follower's nextIndex is -1 then we might as well send it a snapshot
650 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
652 return (nextIndex == -1 ||
653 (!context.getReplicatedLog().isPresent(nextIndex)
654 && context.getReplicatedLog().isInSnapshot(nextIndex)));
659 private void sendInstallSnapshot() {
660 LOG.debug("{}: sendInstallSnapshot", logName());
661 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
662 String followerId = e.getKey();
663 ActorSelection followerActor = context.getPeerActorSelection(followerId);
664 FollowerLogInformation followerLogInfo = e.getValue();
666 if (followerActor != null) {
667 long nextIndex = followerLogInfo.getNextIndex();
668 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
669 canInstallSnapshot(nextIndex)) {
670 sendSnapshotChunk(followerActor, followerId);
677 * Sends a snapshot chunk to a given follower
678 * InstallSnapshot should qualify as a heartbeat too.
680 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
682 if (snapshot.isPresent()) {
683 ByteString nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
685 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
686 // followerId to the followerToSnapshot map.
687 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
690 new InstallSnapshot(currentTerm(), context.getId(),
691 snapshot.get().getLastIncludedIndex(),
692 snapshot.get().getLastIncludedTerm(),
694 followerToSnapshot.incrementChunkIndex(),
695 followerToSnapshot.getTotalChunks(),
696 Optional.of(followerToSnapshot.getLastChunkHashCode())
701 if(LOG.isDebugEnabled()) {
702 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
703 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
704 followerToSnapshot.getTotalChunks());
707 } catch (IOException e) {
708 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
713 * Acccepts snaphot as ByteString, enters into map for future chunks
714 * creates and return a ByteString chunk
716 private ByteString getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
717 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
718 if (followerToSnapshot == null) {
719 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
720 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
722 ByteString nextChunk = followerToSnapshot.getNextChunk();
724 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.size());
729 private void sendHeartBeat() {
730 if (!followerToLog.isEmpty()) {
731 LOG.trace("{}: Sending heartbeat", logName());
732 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
736 private void stopHeartBeat() {
737 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
738 heartbeatSchedule.cancel();
742 private void scheduleHeartBeat(FiniteDuration interval) {
743 if (followerToLog.isEmpty()) {
744 // Optimization - do not bother scheduling a heartbeat as there are
751 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
752 // message is sent to itself.
753 // Scheduling the heartbeat only once here because heartbeats do not
754 // need to be sent if there are other messages being sent to the remote
756 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
757 interval, context.getActor(), new SendHeartBeat(),
758 context.getActorSystem().dispatcher(), context.getActor());
762 public void close() throws Exception {
767 public String getLeaderId() {
768 return context.getId();
771 protected boolean isLeaderIsolated() {
772 int minPresent = getMinIsolatedLeaderPeerCount();
773 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
774 if (followerLogInformation.isFollowerActive()) {
776 if (minPresent == 0) {
781 return (minPresent != 0);
785 * Encapsulates the snapshot bytestring and handles the logic of sending
788 protected class FollowerToSnapshot {
789 private final ByteString snapshotBytes;
790 private int offset = 0;
791 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
792 private int replyReceivedForOffset;
793 // if replyStatus is false, the previous chunk is attempted
794 private boolean replyStatus = false;
795 private int chunkIndex;
796 private final int totalChunks;
797 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
798 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
800 public FollowerToSnapshot(ByteString snapshotBytes) {
801 this.snapshotBytes = snapshotBytes;
802 int size = snapshotBytes.size();
803 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
804 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
805 if(LOG.isDebugEnabled()) {
806 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
807 logName(), size, totalChunks);
809 replyReceivedForOffset = -1;
810 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
813 public ByteString getSnapshotBytes() {
814 return snapshotBytes;
817 public int incrementOffset() {
819 // if prev chunk failed, we would want to sent the same chunk again
820 offset = offset + context.getConfigParams().getSnapshotChunkSize();
825 public int incrementChunkIndex() {
827 // if prev chunk failed, we would want to sent the same chunk again
828 chunkIndex = chunkIndex + 1;
833 public int getChunkIndex() {
837 public int getTotalChunks() {
841 public boolean canSendNextChunk() {
842 // we only send a false if a chunk is sent but we have not received a reply yet
843 return replyReceivedForOffset == offset;
846 public boolean isLastChunk(int chunkIndex) {
847 return totalChunks == chunkIndex;
850 public void markSendStatus(boolean success) {
852 // if the chunk sent was successful
853 replyReceivedForOffset = offset;
855 lastChunkHashCode = nextChunkHashCode;
857 // if the chunk sent was failure
858 replyReceivedForOffset = offset;
863 public ByteString getNextChunk() {
864 int snapshotLength = getSnapshotBytes().size();
865 int start = incrementOffset();
866 int size = context.getConfigParams().getSnapshotChunkSize();
867 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
868 size = snapshotLength;
870 if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
871 size = snapshotLength - start;
876 LOG.debug("{}: Next chunk: length={}, offset={},size={}", logName(),
877 snapshotLength, start, size);
879 ByteString substring = getSnapshotBytes().substring(start, start + size);
880 nextChunkHashCode = substring.hashCode();
885 * reset should be called when the Follower needs to be sent the snapshot from the beginning
890 replyReceivedForOffset = offset;
891 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
892 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
895 public int getLastChunkHashCode() {
896 return lastChunkHashCode;
900 // called from example-actor for printing the follower-states
901 public String printFollowerStates() {
902 final StringBuilder sb = new StringBuilder();
905 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
907 sb.append(followerLogInformation.getId());
908 sb.append(" state:");
909 sb.append(followerLogInformation.isFollowerActive());
914 return sb.toString();
918 public FollowerLogInformation getFollower(String followerId) {
919 return followerToLog.get(followerId);
923 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
924 mapFollowerToSnapshot.put(followerId, snapshot);
928 public int followerSnapshotSize() {
929 return mapFollowerToSnapshot.size();
933 public int followerLogSize() {
934 return followerToLog.size();
937 private static class SnapshotHolder {
938 private final long lastIncludedTerm;
939 private final long lastIncludedIndex;
940 private final ByteString snapshotBytes;
942 SnapshotHolder(Snapshot snapshot) {
943 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
944 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
945 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
948 long getLastIncludedTerm() {
949 return lastIncludedTerm;
952 long getLastIncludedIndex() {
953 return lastIncludedIndex;
956 ByteString getSnapshotBytes() {
957 return snapshotBytes;