2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.raft.behaviors;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Optional;
16 import com.google.common.base.Preconditions;
17 import com.google.protobuf.ByteString;
18 import java.io.IOException;
19 import java.util.Arrays;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.LinkedList;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Queue;
29 import javax.annotation.Nullable;
30 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
31 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
32 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
33 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
34 import org.opendaylight.controller.cluster.raft.PeerInfo;
35 import org.opendaylight.controller.cluster.raft.RaftActorContext;
36 import org.opendaylight.controller.cluster.raft.RaftState;
37 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
38 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
39 import org.opendaylight.controller.cluster.raft.Snapshot;
40 import org.opendaylight.controller.cluster.raft.VotingState;
41 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
42 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
43 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
44 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
45 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
46 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
47 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
48 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
49 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
50 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
51 import scala.concurrent.duration.FiniteDuration;
54 * The behavior of a RaftActor when it is in the Leader state
58 * <li> Upon election: send initial empty AppendEntries RPCs
59 * (heartbeat) to each server; repeat during idle periods to
60 * prevent election timeouts (§5.2)
61 * <li> If command received from client: append entry to local log,
62 * respond after entry applied to state machine (§5.3)
63 * <li> If last log index ≥ nextIndex for a follower: send
64 * AppendEntries RPC with log entries starting at nextIndex
66 * <li> If successful: update nextIndex and matchIndex for
68 * <li> If AppendEntries fails because of log inconsistency:
69 * decrement nextIndex and retry (§5.3)
71 * <li> If there exists an N such that N > commitIndex, a majority
72 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
73 * set commitIndex = N (§5.3, §5.4).
75 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
77 // The index of the first chunk that is sent when installing a snapshot
78 public static final int FIRST_CHUNK_INDEX = 1;
80 // The index that the follower should respond with if it needs the install snapshot to be reset
81 public static final int INVALID_CHUNK_INDEX = -1;
83 // This would be passed as the hash code of the last chunk when sending the first chunk
84 public static final int INITIAL_LAST_CHUNK_HASH_CODE = -1;
86 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
87 private final Map<String, FollowerToSnapshot> mapFollowerToSnapshot = new HashMap<>();
90 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
91 * expect the entries to be modified in sequence, hence we open-code the lookup.
93 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
94 * but we already expect those to be far from frequent.
96 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
98 private Cancellable heartbeatSchedule = null;
99 private Optional<SnapshotHolder> snapshot;
100 private int minReplicationCount;
102 protected AbstractLeader(RaftActorContext context, RaftState state) {
103 super(context, state);
105 for(PeerInfo peerInfo: context.getPeers()) {
106 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
107 followerToLog.put(peerInfo.getId(), followerLogInformation);
110 LOG.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
112 updateMinReplicaCount();
114 snapshot = Optional.absent();
116 // Immediately schedule a heartbeat
117 // Upon election: send initial empty AppendEntries RPCs
118 // (heartbeat) to each server; repeat during idle periods to
119 // prevent election timeouts (§5.2)
120 sendAppendEntries(0, false);
122 // It is important to schedule this heartbeat here
123 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
127 * Return an immutable collection of follower identifiers.
129 * @return Collection of follower IDs
131 public final Collection<String> getFollowerIds() {
132 return followerToLog.keySet();
135 public void addFollower(String followerId) {
136 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
137 context.getPeerInfo(followerId), -1, context);
138 followerToLog.put(followerId, followerLogInformation);
140 if(heartbeatSchedule == null) {
141 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
145 public void removeFollower(String followerId) {
146 followerToLog.remove(followerId);
147 mapFollowerToSnapshot.remove(followerId);
150 public void updateMinReplicaCount() {
152 for(PeerInfo peer: context.getPeers()) {
153 if(peer.isVoting()) {
158 minReplicationCount = getMajorityVoteCount(numVoting);
161 protected int getMinIsolatedLeaderPeerCount(){
162 //the isolated Leader peer count will be 1 less than the majority vote count.
163 //this is because the vote count has the self vote counted in it
165 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
166 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
167 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
169 return minReplicationCount > 0 ? (minReplicationCount - 1) : 0;
173 void setSnapshot(@Nullable Snapshot snapshot) {
174 if(snapshot != null) {
175 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
177 this.snapshot = Optional.absent();
182 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
183 AppendEntries appendEntries) {
185 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
191 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
192 AppendEntriesReply appendEntriesReply) {
194 if(LOG.isTraceEnabled()) {
195 LOG.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
198 // Update the FollowerLogInformation
199 String followerId = appendEntriesReply.getFollowerId();
200 FollowerLogInformation followerLogInformation =
201 followerToLog.get(followerId);
203 if(followerLogInformation == null){
204 LOG.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
208 if(followerLogInformation.timeSinceLastActivity() >
209 context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
210 LOG.warn("{} : handleAppendEntriesReply delayed beyond election timeout, " +
211 "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
212 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
213 context.getLastApplied(), context.getCommitIndex());
216 followerLogInformation.markFollowerActive();
217 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
218 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
220 boolean updated = false;
221 if (appendEntriesReply.isSuccess()) {
222 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
224 LOG.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
226 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
227 ReplicatedLogEntry followersLastLogEntry = context.getReplicatedLog().get(followerLastLogIndex);
228 if(appendEntriesReply.isForceInstallSnapshot()) {
229 // Reset the followers match and next index. This is to signal that this follower has nothing
230 // in common with this Leader and so would require a snapshot to be installed
231 followerLogInformation.setMatchIndex(-1);
232 followerLogInformation.setNextIndex(-1);
234 // Force initiate a snapshot capture
235 initiateCaptureSnapshot(followerId);
236 } else if(followerLastLogIndex < 0 || (followersLastLogEntry != null &&
237 followersLastLogEntry.getTerm() == appendEntriesReply.getLogLastTerm())) {
238 // The follower's log is empty or the last entry is present in the leader's journal
239 // and the terms match so the follower is just behind the leader's journal from
240 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
241 // follower's last log index.
243 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
245 // TODO: When we find that the follower is out of sync with the
246 // Leader we simply decrement that followers next index by 1.
247 // Would it be possible to do better than this? The RAFT spec
248 // does not explicitly deal with it but may be something for us to
251 followerLogInformation.decrNextIndex();
255 // Now figure out if this reply warrants a change in the commitIndex
256 // If there exists an N such that N > commitIndex, a majority
257 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
258 // set commitIndex = N (§5.3, §5.4).
259 if(LOG.isTraceEnabled()) {
260 LOG.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
261 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
264 for (long N = context.getCommitIndex() + 1; ; N++) {
265 int replicatedCount = 1;
267 LOG.trace("{}: checking Nth index {}", logName(), N);
268 for (FollowerLogInformation info : followerToLog.values()) {
269 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
270 if(info.getMatchIndex() >= N && (peerInfo != null && peerInfo.isVoting())) {
272 } else if(LOG.isTraceEnabled()) {
273 LOG.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
274 info.getMatchIndex(), peerInfo);
278 if(LOG.isTraceEnabled()) {
279 LOG.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount, minReplicationCount);
282 if (replicatedCount >= minReplicationCount) {
283 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(N);
284 if (replicatedLogEntry == null) {
285 LOG.debug("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
286 logName(), N, context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().size());
290 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
291 // "Raft never commits log entries from previous terms by counting replicas".
292 // However we keep looping so we can make progress when new entries in the current term
293 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
294 // counting replicas, then all prior entries are committed indirectly".
295 if (replicatedLogEntry.getTerm() == currentTerm()) {
296 LOG.trace("{}: Setting commit index to {}", logName(), N);
297 context.setCommitIndex(N);
299 LOG.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, term {} does not match the current term {}",
300 logName(), N, replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
303 LOG.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
308 // Apply the change to the state machine
309 if (context.getCommitIndex() > context.getLastApplied()) {
310 if(LOG.isDebugEnabled()) {
311 LOG.debug("{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
312 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
315 applyLogToStateMachine(context.getCommitIndex());
318 if (!context.getSnapshotManager().isCapturing()) {
322 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
323 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
327 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
328 AppendEntriesReply appendEntriesReply) {
329 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
330 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
332 if(updated && LOG.isDebugEnabled()) {
333 LOG.debug("{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
334 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
335 followerLogInformation.getNextIndex());
340 private void purgeInMemoryLog() {
341 //find the lowest index across followers which has been replicated to all.
342 // lastApplied if there are no followers, so that we keep clearing the log for single-node
343 // we would delete the in-mem log from that index on, in-order to minimize mem usage
344 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
345 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
346 for (FollowerLogInformation info : followerToLog.values()) {
347 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
350 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
354 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
355 final Iterator<ClientRequestTracker> it = trackers.iterator();
356 while (it.hasNext()) {
357 final ClientRequestTracker t = it.next();
358 if (t.getIndex() == logIndex) {
368 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
369 RequestVoteReply requestVoteReply) {
373 protected void beforeSendHeartbeat(){}
376 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
377 Preconditions.checkNotNull(sender, "sender should not be null");
379 Object message = fromSerializableMessage(originalMessage);
381 if (message instanceof RaftRPC) {
382 RaftRPC rpc = (RaftRPC) message;
383 // If RPC request or response contains term T > currentTerm:
384 // set currentTerm = T, convert to follower (§5.1)
385 // This applies to all RPC messages and responses
386 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
387 LOG.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
388 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
390 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
392 return internalSwitchBehavior(RaftState.Follower);
396 if (message instanceof SendHeartBeat) {
397 beforeSendHeartbeat();
399 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
400 } else if(message instanceof SendInstallSnapshot) {
401 // received from RaftActor
402 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
403 sendInstallSnapshot();
404 } else if (message instanceof Replicate) {
405 replicate((Replicate) message);
406 } else if (message instanceof InstallSnapshotReply) {
407 handleInstallSnapshotReply((InstallSnapshotReply) message);
409 return super.handleMessage(sender, message);
415 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
416 LOG.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
418 String followerId = reply.getFollowerId();
419 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
421 if (followerToSnapshot == null) {
422 LOG.error("{}: FollowerToSnapshot not found for follower {} in InstallSnapshotReply",
423 logName(), followerId);
427 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
428 if(followerLogInformation == null) {
429 // This can happen during AddServer if it times out.
430 LOG.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
431 logName(), followerId);
432 mapFollowerToSnapshot.remove(followerId);
436 followerLogInformation.markFollowerActive();
438 if (followerToSnapshot.getChunkIndex() == reply.getChunkIndex()) {
439 boolean wasLastChunk = false;
440 if (reply.isSuccess()) {
441 if(followerToSnapshot.isLastChunk(reply.getChunkIndex())) {
442 //this was the last chunk reply
443 if(LOG.isDebugEnabled()) {
444 LOG.debug("{}: InstallSnapshotReply received, " +
445 "last chunk received, Chunk: {}. Follower: {} Setting nextIndex: {}",
446 logName(), reply.getChunkIndex(), followerId,
447 context.getReplicatedLog().getSnapshotIndex() + 1
451 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
452 followerLogInformation.setMatchIndex(followerMatchIndex);
453 followerLogInformation.setNextIndex(followerMatchIndex + 1);
454 mapFollowerToSnapshot.remove(followerId);
456 LOG.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
457 logName(), followerId, followerLogInformation.getMatchIndex(),
458 followerLogInformation.getNextIndex());
460 if (mapFollowerToSnapshot.isEmpty()) {
461 // once there are no pending followers receiving snapshots
462 // we can remove snapshot from the memory
466 if(context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED){
467 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
468 new UnInitializedFollowerSnapshotReply(followerId);
469 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
470 LOG.debug("Sent message UnInitializedFollowerSnapshotReply to self");
473 followerToSnapshot.markSendStatus(true);
476 LOG.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
477 logName(), reply.getChunkIndex());
479 followerToSnapshot.markSendStatus(false);
482 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
483 // Since the follower is now caught up try to purge the log.
485 } else if (!wasLastChunk && followerToSnapshot.canSendNextChunk()) {
486 ActorSelection followerActor = context.getPeerActorSelection(followerId);
487 if(followerActor != null) {
488 sendSnapshotChunk(followerActor, followerId);
493 LOG.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
494 logName(), reply.getChunkIndex(), followerId,
495 followerToSnapshot.getChunkIndex());
497 if(reply.getChunkIndex() == INVALID_CHUNK_INDEX){
498 // Since the Follower did not find this index to be valid we should reset the follower snapshot
499 // so that Installing the snapshot can resume from the beginning
500 followerToSnapshot.reset();
505 private void replicate(Replicate replicate) {
506 long logIndex = replicate.getReplicatedLogEntry().getIndex();
508 LOG.debug("{}: Replicate message: identifier: {}, logIndex: {}", logName(),
509 replicate.getIdentifier(), logIndex);
511 // Create a tracker entry we will use this later to notify the
514 new ClientRequestTrackerImpl(replicate.getClientActor(),
515 replicate.getIdentifier(),
519 boolean applyModificationToState = followerToLog.isEmpty()
520 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
522 if(applyModificationToState){
523 context.setCommitIndex(logIndex);
524 applyLogToStateMachine(logIndex);
527 if (!followerToLog.isEmpty()) {
528 sendAppendEntries(0, false);
532 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
533 // Send an AppendEntries to all followers
534 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
535 final String followerId = e.getKey();
536 final FollowerLogInformation followerLogInformation = e.getValue();
537 // This checks helps not to send a repeat message to the follower
538 if(!followerLogInformation.isFollowerActive() ||
539 followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
540 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
547 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
548 * sending next snapshot chunk, and initiating a snapshot.
549 * @return true if any update is sent, false otherwise
552 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
553 boolean sendHeartbeat, boolean isHeartbeat) {
555 ActorSelection followerActor = context.getPeerActorSelection(followerId);
556 if (followerActor != null) {
557 long followerNextIndex = followerLogInformation.getNextIndex();
558 boolean isFollowerActive = followerLogInformation.isFollowerActive();
559 boolean sendAppendEntries = false;
560 List<ReplicatedLogEntry> entries = Collections.emptyList();
562 if (mapFollowerToSnapshot.get(followerId) != null) {
563 // if install snapshot is in process , then sent next chunk if possible
564 if (isFollowerActive && mapFollowerToSnapshot.get(followerId).canSendNextChunk()) {
565 sendSnapshotChunk(followerActor, followerId);
566 } else if(sendHeartbeat) {
567 // we send a heartbeat even if we have not received a reply for the last chunk
568 sendAppendEntries = true;
571 long leaderLastIndex = context.getReplicatedLog().lastIndex();
572 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
574 if((!isHeartbeat && LOG.isDebugEnabled()) || LOG.isTraceEnabled()) {
575 LOG.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, leaderLastIndex: {}, leaderSnapShotIndex: {}",
576 logName(), followerId, isFollowerActive, followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
579 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
581 LOG.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
582 followerNextIndex, followerId);
584 if(followerLogInformation.okToReplicate()) {
585 // Try to send all the entries in the journal but not exceeding the max data size
586 // for a single AppendEntries message.
587 int maxEntries = (int) context.getReplicatedLog().size();
588 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
589 context.getConfigParams().getSnapshotChunkSize());
590 sendAppendEntries = true;
592 } else if (isFollowerActive && followerNextIndex >= 0 &&
593 leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
594 // if the followers next index is not present in the leaders log, and
595 // if the follower is just not starting and if leader's index is more than followers index
596 // then snapshot should be sent
598 if (LOG.isDebugEnabled()) {
599 LOG.debug(String.format("%s: InitiateInstallSnapshot to follower: %s," +
600 "follower-nextIndex: %d, leader-snapshot-index: %d, " +
601 "leader-last-index: %d", logName(), followerId,
602 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
605 // Send heartbeat to follower whenever install snapshot is initiated.
606 sendAppendEntries = true;
607 if (canInstallSnapshot(followerNextIndex)) {
608 initiateCaptureSnapshot(followerId);
611 } else if(sendHeartbeat) {
612 // we send an AppendEntries, even if the follower is inactive
613 // in-order to update the followers timestamp, in case it becomes active again
614 sendAppendEntries = true;
619 if(sendAppendEntries) {
620 sendAppendEntriesToFollower(followerActor, followerNextIndex,
621 entries, followerId);
626 private void sendAppendEntriesToFollower(ActorSelection followerActor, long followerNextIndex,
627 List<ReplicatedLogEntry> entries, String followerId) {
628 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
629 prevLogIndex(followerNextIndex),
630 prevLogTerm(followerNextIndex), entries,
631 context.getCommitIndex(), super.getReplicatedToAllIndex(), context.getPayloadVersion());
633 if(!entries.isEmpty() || LOG.isTraceEnabled()) {
634 LOG.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerId,
638 followerActor.tell(appendEntries, actor());
642 * Install Snapshot works as follows
643 * 1. Leader initiates the capture snapshot by sending a CaptureSnapshot message to actor
644 * 2. RaftActor on receipt of the CaptureSnapshotReply (from Shard), stores the received snapshot in the replicated log
645 * and makes a call to Leader's handleMessage , with SendInstallSnapshot message.
646 * 3. Leader , picks the snapshot from im-mem ReplicatedLog and sends it in chunks to the Follower
647 * 4. On complete, Follower sends back a InstallSnapshotReply.
648 * 5. On receipt of the InstallSnapshotReply for the last chunk, Leader marks the install complete for that follower
649 * and replenishes the memory by deleting the snapshot in Replicated log.
650 * 6. If another follower requires a snapshot and a snapshot has been collected (via CaptureSnapshotReply)
651 * then send the existing snapshot in chunks to the follower.
654 public boolean initiateCaptureSnapshot(String followerId) {
655 if (snapshot.isPresent()) {
656 // if a snapshot is present in the memory, most likely another install is in progress
657 // no need to capture snapshot.
658 // This could happen if another follower needs an install when one is going on.
659 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
660 sendSnapshotChunk(followerActor, followerId);
663 return context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
664 this.getReplicatedToAllIndex(), followerId);
668 private boolean canInstallSnapshot(long nextIndex){
669 // If the follower's nextIndex is -1 then we might as well send it a snapshot
670 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
672 return (nextIndex == -1 ||
673 (!context.getReplicatedLog().isPresent(nextIndex)
674 && context.getReplicatedLog().isInSnapshot(nextIndex)));
679 private void sendInstallSnapshot() {
680 LOG.debug("{}: sendInstallSnapshot", logName());
681 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
682 String followerId = e.getKey();
683 ActorSelection followerActor = context.getPeerActorSelection(followerId);
684 FollowerLogInformation followerLogInfo = e.getValue();
686 if (followerActor != null) {
687 long nextIndex = followerLogInfo.getNextIndex();
688 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED ||
689 canInstallSnapshot(nextIndex)) {
690 sendSnapshotChunk(followerActor, followerId);
697 * Sends a snapshot chunk to a given follower
698 * InstallSnapshot should qualify as a heartbeat too.
700 private void sendSnapshotChunk(ActorSelection followerActor, String followerId) {
702 if (snapshot.isPresent()) {
703 byte[] nextSnapshotChunk = getNextSnapshotChunk(followerId, snapshot.get().getSnapshotBytes());
705 // Note: the previous call to getNextSnapshotChunk has the side-effect of adding
706 // followerId to the followerToSnapshot map.
707 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
709 int nextChunkIndex = followerToSnapshot.incrementChunkIndex();
710 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
711 if(followerToSnapshot.isLastChunk(nextChunkIndex)) {
712 serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
716 new InstallSnapshot(currentTerm(), context.getId(),
717 snapshot.get().getLastIncludedIndex(),
718 snapshot.get().getLastIncludedTerm(),
721 followerToSnapshot.getTotalChunks(),
722 Optional.of(followerToSnapshot.getLastChunkHashCode()),
724 ).toSerializable(followerToLog.get(followerId).getRaftVersion()),
728 if(LOG.isDebugEnabled()) {
729 LOG.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}",
730 logName(), followerActor.path(), followerToSnapshot.getChunkIndex(),
731 followerToSnapshot.getTotalChunks());
734 } catch (IOException e) {
735 LOG.error("{}: InstallSnapshot failed for Leader.", logName(), e);
740 * Acccepts snaphot as ByteString, enters into map for future chunks
741 * creates and return a ByteString chunk
743 private byte[] getNextSnapshotChunk(String followerId, ByteString snapshotBytes) throws IOException {
744 FollowerToSnapshot followerToSnapshot = mapFollowerToSnapshot.get(followerId);
745 if (followerToSnapshot == null) {
746 followerToSnapshot = new FollowerToSnapshot(snapshotBytes);
747 mapFollowerToSnapshot.put(followerId, followerToSnapshot);
749 byte[] nextChunk = followerToSnapshot.getNextChunk();
751 LOG.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerId, nextChunk.length);
756 private void sendHeartBeat() {
757 if (!followerToLog.isEmpty()) {
758 LOG.trace("{}: Sending heartbeat", logName());
759 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
763 private void stopHeartBeat() {
764 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
765 heartbeatSchedule.cancel();
769 private void scheduleHeartBeat(FiniteDuration interval) {
770 if (followerToLog.isEmpty()) {
771 // Optimization - do not bother scheduling a heartbeat as there are
778 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
779 // message is sent to itself.
780 // Scheduling the heartbeat only once here because heartbeats do not
781 // need to be sent if there are other messages being sent to the remote
783 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
784 interval, context.getActor(), SendHeartBeat.INSTANCE,
785 context.getActorSystem().dispatcher(), context.getActor());
789 public void close() {
794 public final String getLeaderId() {
795 return context.getId();
799 public final short getLeaderPayloadVersion() {
800 return context.getPayloadVersion();
803 protected boolean isLeaderIsolated() {
804 int minPresent = getMinIsolatedLeaderPeerCount();
805 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
806 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
807 if(peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
809 if (minPresent == 0) {
814 return (minPresent != 0);
818 * Encapsulates the snapshot bytestring and handles the logic of sending
821 protected class FollowerToSnapshot {
822 private final ByteString snapshotBytes;
823 private int offset = 0;
824 // the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
825 private int replyReceivedForOffset;
826 // if replyStatus is false, the previous chunk is attempted
827 private boolean replyStatus = false;
828 private int chunkIndex;
829 private final int totalChunks;
830 private int lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
831 private int nextChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
833 public FollowerToSnapshot(ByteString snapshotBytes) {
834 this.snapshotBytes = snapshotBytes;
835 int size = snapshotBytes.size();
836 totalChunks = ( size / context.getConfigParams().getSnapshotChunkSize()) +
837 ((size % context.getConfigParams().getSnapshotChunkSize()) > 0 ? 1 : 0);
838 if(LOG.isDebugEnabled()) {
839 LOG.debug("{}: Snapshot {} bytes, total chunks to send:{}",
840 logName(), size, totalChunks);
842 replyReceivedForOffset = -1;
843 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
846 public ByteString getSnapshotBytes() {
847 return snapshotBytes;
850 public int incrementOffset() {
852 // if prev chunk failed, we would want to sent the same chunk again
853 offset = offset + context.getConfigParams().getSnapshotChunkSize();
858 public int incrementChunkIndex() {
860 // if prev chunk failed, we would want to sent the same chunk again
861 chunkIndex = chunkIndex + 1;
866 public int getChunkIndex() {
870 public int getTotalChunks() {
874 public boolean canSendNextChunk() {
875 // we only send a false if a chunk is sent but we have not received a reply yet
876 return replyReceivedForOffset == offset;
879 public boolean isLastChunk(int chunkIndex) {
880 return totalChunks == chunkIndex;
883 public void markSendStatus(boolean success) {
885 // if the chunk sent was successful
886 replyReceivedForOffset = offset;
888 lastChunkHashCode = nextChunkHashCode;
890 // if the chunk sent was failure
891 replyReceivedForOffset = offset;
896 public byte[] getNextChunk() {
897 int snapshotLength = getSnapshotBytes().size();
898 int start = incrementOffset();
899 int size = context.getConfigParams().getSnapshotChunkSize();
900 if (context.getConfigParams().getSnapshotChunkSize() > snapshotLength) {
901 size = snapshotLength;
902 } else if ((start + context.getConfigParams().getSnapshotChunkSize()) > snapshotLength) {
903 size = snapshotLength - start;
906 byte[] nextChunk = new byte[size];
907 getSnapshotBytes().copyTo(nextChunk, start, 0, size);
908 nextChunkHashCode = Arrays.hashCode(nextChunk);
910 LOG.debug("{}: Next chunk: total length={}, offset={}, size={}, hashCode={}", logName(),
911 snapshotLength, start, size, nextChunkHashCode);
916 * reset should be called when the Follower needs to be sent the snapshot from the beginning
921 replyReceivedForOffset = offset;
922 chunkIndex = AbstractLeader.FIRST_CHUNK_INDEX;
923 lastChunkHashCode = AbstractLeader.INITIAL_LAST_CHUNK_HASH_CODE;
926 public int getLastChunkHashCode() {
927 return lastChunkHashCode;
931 // called from example-actor for printing the follower-states
932 public String printFollowerStates() {
933 final StringBuilder sb = new StringBuilder();
936 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
938 sb.append(followerLogInformation.getId());
939 sb.append(" state:");
940 sb.append(followerLogInformation.isFollowerActive());
945 return sb.toString();
949 public FollowerLogInformation getFollower(String followerId) {
950 return followerToLog.get(followerId);
954 protected void setFollowerSnapshot(String followerId, FollowerToSnapshot snapshot) {
955 mapFollowerToSnapshot.put(followerId, snapshot);
959 public int followerSnapshotSize() {
960 return mapFollowerToSnapshot.size();
964 public int followerLogSize() {
965 return followerToLog.size();
968 private static class SnapshotHolder {
969 private final long lastIncludedTerm;
970 private final long lastIncludedIndex;
971 private final ByteString snapshotBytes;
973 SnapshotHolder(Snapshot snapshot) {
974 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
975 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
976 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
979 long getLastIncludedTerm() {
980 return lastIncludedTerm;
983 long getLastIncludedIndex() {
984 return lastIncludedIndex;
987 ByteString getSnapshotBytes() {
988 return snapshotBytes;