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.util.Collection;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.Iterator;
22 import java.util.LinkedList;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Queue;
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 org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
49 import scala.concurrent.duration.FiniteDuration;
52 * The behavior of a RaftActor when it is in the Leader state
56 * <li> Upon election: send initial empty AppendEntries RPCs
57 * (heartbeat) to each server; repeat during idle periods to
58 * prevent election timeouts (§5.2)
59 * <li> If command received from client: append entry to local log,
60 * respond after entry applied to state machine (§5.3)
61 * <li> If last log index ≥ nextIndex for a follower: send
62 * 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)
67 * <li> If there exists an N such that N > commitIndex, a majority
68 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
69 * set commitIndex = N (§5.3, §5.4).
72 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
73 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
76 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
77 * expect the entries to be modified in sequence, hence we open-code the lookup.
78 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
79 * but we already expect those to be far from frequent.
81 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
83 private Cancellable heartbeatSchedule = null;
84 private Optional<SnapshotHolder> snapshot = Optional.absent();
85 private int minReplicationCount;
87 protected AbstractLeader(RaftActorContext context, RaftState state,
88 @Nullable AbstractLeader initializeFromLeader) {
89 super(context, state);
91 if (initializeFromLeader != null) {
92 followerToLog.putAll(initializeFromLeader.followerToLog);
93 snapshot = initializeFromLeader.snapshot;
94 trackers.addAll(initializeFromLeader.trackers);
96 for (PeerInfo peerInfo: context.getPeers()) {
97 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
98 followerToLog.put(peerInfo.getId(), followerLogInformation);
102 log.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
104 updateMinReplicaCount();
106 // Immediately schedule a heartbeat
107 // Upon election: send initial empty AppendEntries RPCs
108 // (heartbeat) to each server; repeat during idle periods to
109 // prevent election timeouts (§5.2)
110 sendAppendEntries(0, false);
112 // It is important to schedule this heartbeat here
113 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
116 protected AbstractLeader(RaftActorContext context, RaftState state) {
117 this(context, state, null);
121 * Return an immutable collection of follower identifiers.
123 * @return Collection of follower IDs
125 public final Collection<String> getFollowerIds() {
126 return followerToLog.keySet();
129 public void addFollower(String followerId) {
130 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
131 context.getPeerInfo(followerId), -1, context);
132 followerToLog.put(followerId, followerLogInformation);
134 if (heartbeatSchedule == null) {
135 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
139 public void removeFollower(String followerId) {
140 followerToLog.remove(followerId);
143 public void updateMinReplicaCount() {
145 for (PeerInfo peer: context.getPeers()) {
146 if (peer.isVoting()) {
151 minReplicationCount = getMajorityVoteCount(numVoting);
154 protected int getMinIsolatedLeaderPeerCount() {
155 //the isolated Leader peer count will be 1 less than the majority vote count.
156 //this is because the vote count has the self vote counted in it
158 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
159 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
160 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
162 return minReplicationCount > 0 ? minReplicationCount - 1 : 0;
166 void setSnapshot(@Nullable Snapshot snapshot) {
167 if (snapshot != null) {
168 this.snapshot = Optional.of(new SnapshotHolder(snapshot));
170 this.snapshot = Optional.absent();
175 boolean hasSnapshot() {
176 return snapshot.isPresent();
180 protected RaftActorBehavior handleAppendEntries(ActorRef sender,
181 AppendEntries appendEntries) {
183 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
189 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender, AppendEntriesReply appendEntriesReply) {
190 log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
192 // Update the FollowerLogInformation
193 String followerId = appendEntriesReply.getFollowerId();
194 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
196 if (followerLogInformation == null) {
197 log.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
201 if (followerLogInformation.timeSinceLastActivity()
202 > context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
203 log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
204 + "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
205 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
206 context.getLastApplied(), context.getCommitIndex());
209 followerLogInformation.markFollowerActive();
210 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
211 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
213 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
214 long followersLastLogTermInLeadersLog = getLogEntryTerm(followerLastLogIndex);
215 boolean updated = false;
216 if (appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
217 // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
218 // in raft as a node cannot become leader if it's log is behind another's. However, the
219 // non-voting semantics deviate a bit from raft. Only voting members participate in
220 // elections and can become leader so it's possible for a non-voting follower to be ahead
221 // of the leader. This can happen if persistence is disabled and all voting members are
222 // restarted. In this case, the voting leader will start out with an empty log however
223 // the non-voting followers still retain the previous data in memory. On the first
224 // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
225 // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
226 // lastLogIndex may be higher in which case we want to reset the follower by installing a
227 // snapshot. It's also possible that the follower's last log index is behind the leader's.
228 // However in this case the log terms won't match and the logs will conflict - this is handled
230 log.debug("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} - "
231 + "forcing install snaphot", logName(), followerLogInformation.getId(),
232 appendEntriesReply.getLogLastIndex(), context.getReplicatedLog().lastIndex());
234 followerLogInformation.setMatchIndex(-1);
235 followerLogInformation.setNextIndex(-1);
237 initiateCaptureSnapshot(followerId);
240 } else if (appendEntriesReply.isSuccess()) {
241 if (followerLastLogIndex >= 0 && followersLastLogTermInLeadersLog >= 0
242 && followersLastLogTermInLeadersLog != appendEntriesReply.getLogLastTerm()) {
243 // The follower's last entry is present in the leader's journal but the terms don't match so the
244 // follower has a conflicting entry. Since the follower didn't report that it's out of sync, this means
245 // either the previous leader entry sent didn't conflict or the previous leader entry is in the snapshot
246 // and no longer in the journal. Either way, we set the follower's next index to 1 less than the last
247 // index reported by the follower. For the former case, the leader will send all entries starting with
248 // the previous follower's index and the follower will remove and replace the conflicting entries as
249 // needed. For the latter, the leader will initiate an install snapshot.
251 followerLogInformation.setNextIndex(followerLastLogIndex - 1);
254 log.debug("{}: handleAppendEntriesReply: follower {} last log term {} for index {} conflicts with the "
255 + "leader's {} - set the follower's next index to {}", logName(),
256 followerId, appendEntriesReply.getLogLastTerm(), appendEntriesReply.getLogLastIndex(),
257 followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
259 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
262 log.debug("{}: handleAppendEntriesReply: received unsuccessful reply: {}", logName(), appendEntriesReply);
264 if (appendEntriesReply.isForceInstallSnapshot()) {
265 // Reset the followers match and next index. This is to signal that this follower has nothing
266 // in common with this Leader and so would require a snapshot to be installed
267 followerLogInformation.setMatchIndex(-1);
268 followerLogInformation.setNextIndex(-1);
270 // Force initiate a snapshot capture
271 initiateCaptureSnapshot(followerId);
272 } else if (followerLastLogIndex < 0 || followersLastLogTermInLeadersLog >= 0
273 && followersLastLogTermInLeadersLog == appendEntriesReply.getLogLastTerm()) {
274 // The follower's log is empty or the last entry is present in the leader's journal
275 // and the terms match so the follower is just behind the leader's journal from
276 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
277 // follower's last log index.
279 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
281 // The follower's log conflicts with leader's log so decrement follower's next index by 1
282 // in an attempt to find where the logs match.
284 followerLogInformation.decrNextIndex();
287 log.debug("{}: follower's last log term {} conflicts with the leader's {} - dec next index to {}",
288 logName(), appendEntriesReply.getLogLastTerm(), followersLastLogTermInLeadersLog,
289 followerLogInformation.getNextIndex());
293 // Now figure out if this reply warrants a change in the commitIndex
294 // If there exists an N such that N > commitIndex, a majority
295 // of matchIndex[i] ≥ N, and log[N].term == currentTerm:
296 // set commitIndex = N (§5.3, §5.4).
297 if (log.isTraceEnabled()) {
298 log.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
299 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
302 for (long index = context.getCommitIndex() + 1; ; index++) {
303 int replicatedCount = 1;
305 log.trace("{}: checking Nth index {}", logName(), index);
306 for (FollowerLogInformation info : followerToLog.values()) {
307 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
308 if (info.getMatchIndex() >= index && peerInfo != null && peerInfo.isVoting()) {
310 } else if (log.isTraceEnabled()) {
311 log.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
312 info.getMatchIndex(), peerInfo);
316 if (log.isTraceEnabled()) {
317 log.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount,
318 minReplicationCount);
321 if (replicatedCount >= minReplicationCount) {
322 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(index);
323 if (replicatedLogEntry == null) {
324 log.debug("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
325 logName(), index, context.getReplicatedLog().getSnapshotIndex(),
326 context.getReplicatedLog().size());
330 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
331 // "Raft never commits log entries from previous terms by counting replicas".
332 // However we keep looping so we can make progress when new entries in the current term
333 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
334 // counting replicas, then all prior entries are committed indirectly".
335 if (replicatedLogEntry.getTerm() == currentTerm()) {
336 log.trace("{}: Setting commit index to {}", logName(), index);
337 context.setCommitIndex(index);
339 log.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, "
340 + "term {} does not match the current term {}", logName(), index,
341 replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
344 log.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
349 // Apply the change to the state machine
350 if (context.getCommitIndex() > context.getLastApplied()) {
351 if (log.isDebugEnabled()) {
353 "{}: handleAppendEntriesReply from {}: applying to log - commitIndex: {}, lastAppliedIndex: {}",
354 logName(), followerId, context.getCommitIndex(), context.getLastApplied());
357 applyLogToStateMachine(context.getCommitIndex());
360 if (!context.getSnapshotManager().isCapturing()) {
364 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
365 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
370 private boolean updateFollowerLogInformation(FollowerLogInformation followerLogInformation,
371 AppendEntriesReply appendEntriesReply) {
372 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
373 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
375 if (updated && log.isDebugEnabled()) {
377 "{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
378 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
379 followerLogInformation.getNextIndex());
384 private void purgeInMemoryLog() {
385 //find the lowest index across followers which has been replicated to all.
386 // lastApplied if there are no followers, so that we keep clearing the log for single-node
387 // we would delete the in-mem log from that index on, in-order to minimize mem usage
388 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
389 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
390 for (FollowerLogInformation info : followerToLog.values()) {
391 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
394 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
398 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
399 final Iterator<ClientRequestTracker> it = trackers.iterator();
400 while (it.hasNext()) {
401 final ClientRequestTracker t = it.next();
402 if (t.getIndex() == logIndex) {
412 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
413 RequestVoteReply requestVoteReply) {
417 protected void beforeSendHeartbeat(){}
420 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
421 Preconditions.checkNotNull(sender, "sender should not be null");
423 if (message instanceof RaftRPC) {
424 RaftRPC rpc = (RaftRPC) message;
425 // If RPC request or response contains term T > currentTerm:
426 // set currentTerm = T, convert to follower (§5.1)
427 // This applies to all RPC messages and responses
428 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
429 log.debug("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
430 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
432 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
434 return internalSwitchBehavior(RaftState.Follower);
438 if (message instanceof SendHeartBeat) {
439 beforeSendHeartbeat();
441 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
442 } else if (message instanceof SendInstallSnapshot) {
443 // received from RaftActor
444 setSnapshot(((SendInstallSnapshot) message).getSnapshot());
445 sendInstallSnapshot();
446 } else if (message instanceof Replicate) {
447 replicate((Replicate) message);
448 } else if (message instanceof InstallSnapshotReply) {
449 handleInstallSnapshotReply((InstallSnapshotReply) message);
451 return super.handleMessage(sender, message);
457 private void handleInstallSnapshotReply(InstallSnapshotReply reply) {
458 log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
460 String followerId = reply.getFollowerId();
461 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
462 if (followerLogInformation == null) {
463 // This can happen during AddServer if it times out.
464 log.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
465 logName(), followerId);
469 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
470 if (installSnapshotState == null) {
471 log.error("{}: LeaderInstallSnapshotState not found for follower {} in InstallSnapshotReply",
472 logName(), followerId);
476 followerLogInformation.markFollowerActive();
478 if (installSnapshotState.getChunkIndex() == reply.getChunkIndex()) {
479 boolean wasLastChunk = false;
480 if (reply.isSuccess()) {
481 if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
482 //this was the last chunk reply
483 log.debug("{}: InstallSnapshotReply received, last chunk received, Chunk: {}. Follower: {} -"
484 + " Setting nextIndex: {}", logName(), reply.getChunkIndex(), followerId,
485 context.getReplicatedLog().getSnapshotIndex() + 1);
487 long followerMatchIndex = snapshot.get().getLastIncludedIndex();
488 followerLogInformation.setMatchIndex(followerMatchIndex);
489 followerLogInformation.setNextIndex(followerMatchIndex + 1);
490 followerLogInformation.clearLeaderInstallSnapshotState();
492 log.debug("{}: follower: {}, matchIndex set to {}, nextIndex set to {}",
493 logName(), followerId, followerLogInformation.getMatchIndex(),
494 followerLogInformation.getNextIndex());
496 if (!anyFollowersInstallingSnapshot()) {
497 // once there are no pending followers receiving snapshots
498 // we can remove snapshot from the memory
503 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
504 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
505 new UnInitializedFollowerSnapshotReply(followerId);
506 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
507 log.debug("Sent message UnInitializedFollowerSnapshotReply to self");
510 installSnapshotState.markSendStatus(true);
513 log.info("{}: InstallSnapshotReply received sending snapshot chunk failed, Will retry, Chunk: {}",
514 logName(), reply.getChunkIndex());
516 installSnapshotState.markSendStatus(false);
519 if (wasLastChunk && !context.getSnapshotManager().isCapturing()) {
520 // Since the follower is now caught up try to purge the log.
522 } else if (!wasLastChunk && installSnapshotState.canSendNextChunk()) {
523 ActorSelection followerActor = context.getPeerActorSelection(followerId);
524 if (followerActor != null) {
525 sendSnapshotChunk(followerActor, followerLogInformation);
530 log.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
531 logName(), reply.getChunkIndex(), followerId,
532 installSnapshotState.getChunkIndex());
534 if (reply.getChunkIndex() == LeaderInstallSnapshotState.INVALID_CHUNK_INDEX) {
535 // Since the Follower did not find this index to be valid we should reset the follower snapshot
536 // so that Installing the snapshot can resume from the beginning
537 installSnapshotState.reset();
542 private boolean anyFollowersInstallingSnapshot() {
543 for (FollowerLogInformation info: followerToLog.values()) {
544 if (info.getInstallSnapshotState() != null) {
553 private void replicate(Replicate replicate) {
554 long logIndex = replicate.getReplicatedLogEntry().getIndex();
556 log.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}", logName(),
557 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass());
559 // Create a tracker entry we will use this later to notify the
561 if (replicate.getClientActor() != null) {
562 trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
566 boolean applyModificationToState = !context.anyVotingPeers()
567 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
569 if (applyModificationToState) {
570 context.setCommitIndex(logIndex);
571 applyLogToStateMachine(logIndex);
574 if (!followerToLog.isEmpty()) {
575 sendAppendEntries(0, false);
579 protected void sendAppendEntries(long timeSinceLastActivityInterval, boolean isHeartbeat) {
580 // Send an AppendEntries to all followers
581 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
582 final String followerId = e.getKey();
583 final FollowerLogInformation followerLogInformation = e.getValue();
584 // This checks helps not to send a repeat message to the follower
585 if (!followerLogInformation.isFollowerActive()
586 || followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
587 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
593 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
594 * sending next snapshot chunk, and initiating a snapshot.
596 * @return true if any update is sent, false otherwise
598 private void sendUpdatesToFollower(String followerId, FollowerLogInformation followerLogInformation,
599 boolean sendHeartbeat, boolean isHeartbeat) {
601 ActorSelection followerActor = context.getPeerActorSelection(followerId);
602 if (followerActor != null) {
603 long followerNextIndex = followerLogInformation.getNextIndex();
604 boolean isFollowerActive = followerLogInformation.isFollowerActive();
605 boolean sendAppendEntries = false;
606 List<ReplicatedLogEntry> entries = Collections.emptyList();
608 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
609 if (installSnapshotState != null) {
610 // if install snapshot is in process , then sent next chunk if possible
611 if (isFollowerActive && installSnapshotState.canSendNextChunk()) {
612 sendSnapshotChunk(followerActor, followerLogInformation);
613 } else if (sendHeartbeat) {
614 // we send a heartbeat even if we have not received a reply for the last chunk
615 sendAppendEntries = true;
618 long leaderLastIndex = context.getReplicatedLog().lastIndex();
619 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
621 if (!isHeartbeat && log.isDebugEnabled() || log.isTraceEnabled()) {
622 log.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, "
623 + "leaderLastIndex: {}, leaderSnapShotIndex: {}", logName(), followerId, isFollowerActive,
624 followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
627 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
629 log.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
630 followerNextIndex, followerId);
632 if (followerLogInformation.okToReplicate()) {
633 // Try to send all the entries in the journal but not exceeding the max data size
634 // for a single AppendEntries message.
635 int maxEntries = (int) context.getReplicatedLog().size();
636 entries = context.getReplicatedLog().getFrom(followerNextIndex, maxEntries,
637 context.getConfigParams().getSnapshotChunkSize());
638 sendAppendEntries = true;
640 } else if (isFollowerActive && followerNextIndex >= 0
641 && leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
642 // if the followers next index is not present in the leaders log, and
643 // if the follower is just not starting and if leader's index is more than followers index
644 // then snapshot should be sent
646 if (log.isDebugEnabled()) {
647 log.debug(String.format("%s: InitiateInstallSnapshot to follower: %s, "
648 + "follower-nextIndex: %d, leader-snapshot-index: %d, "
649 + "leader-last-index: %d", logName(), followerId,
650 followerNextIndex, leaderSnapShotIndex, leaderLastIndex));
653 // Send heartbeat to follower whenever install snapshot is initiated.
654 sendAppendEntries = true;
655 if (canInstallSnapshot(followerNextIndex)) {
656 initiateCaptureSnapshot(followerId);
659 } else if (sendHeartbeat) {
660 // we send an AppendEntries, even if the follower is inactive
661 // in-order to update the followers timestamp, in case it becomes active again
662 sendAppendEntries = true;
667 if (sendAppendEntries) {
668 sendAppendEntriesToFollower(followerActor, entries, followerLogInformation);
673 private void sendAppendEntriesToFollower(ActorSelection followerActor, List<ReplicatedLogEntry> entries,
674 FollowerLogInformation followerLogInformation) {
675 // In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
676 // possibly committing and applying conflicting entries (those with same index, different term) from a prior
677 // term that weren't replicated to a majority, which would be a violation of raft.
678 // - if the follower isn't active. In this case we don't know the state of the follower and we send an
679 // empty AppendEntries as a heart beat to prevent election.
680 // - if we're in the process of installing a snapshot. In this case we don't send any new entries but still
681 // need to send AppendEntries to prevent election.
682 boolean isInstallingSnaphot = followerLogInformation.getInstallSnapshotState() != null;
683 long leaderCommitIndex = isInstallingSnaphot || !followerLogInformation.isFollowerActive() ? -1 :
684 context.getCommitIndex();
686 long followerNextIndex = followerLogInformation.getNextIndex();
687 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
688 getLogEntryIndex(followerNextIndex - 1),
689 getLogEntryTerm(followerNextIndex - 1), entries,
690 leaderCommitIndex, super.getReplicatedToAllIndex(), context.getPayloadVersion());
692 if (!entries.isEmpty() || log.isTraceEnabled()) {
693 log.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerLogInformation.getId(),
697 followerActor.tell(appendEntries, actor());
701 * Initiates a snapshot capture to install on a follower.
703 * Install Snapshot works as follows
704 * 1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
705 * 2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
706 * the Leader's handleMessage with a SendInstallSnapshot message.
707 * 3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
708 * the Follower via InstallSnapshot messages.
709 * 4. For each chunk, the Follower sends back an InstallSnapshotReply.
710 * 5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
712 * 6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
713 * then send the existing snapshot in chunks to the follower.
715 * @param followerId the id of the follower.
716 * @return true if capture was initiated, false otherwise.
718 public boolean initiateCaptureSnapshot(String followerId) {
719 FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
720 if (snapshot.isPresent()) {
721 // If a snapshot is present in the memory, most likely another install is in progress no need to capture
722 // snapshot. This could happen if another follower needs an install when one is going on.
723 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
725 // Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
726 sendSnapshotChunk(followerActor, followerLogInfo);
729 boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
730 this.getReplicatedToAllIndex(), followerId);
731 if (captureInitiated) {
732 followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
733 context.getConfigParams().getSnapshotChunkSize(), logName()));
736 return captureInitiated;
740 private boolean canInstallSnapshot(long nextIndex) {
741 // If the follower's nextIndex is -1 then we might as well send it a snapshot
742 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
744 return nextIndex == -1 || !context.getReplicatedLog().isPresent(nextIndex)
745 && context.getReplicatedLog().isInSnapshot(nextIndex);
750 private void sendInstallSnapshot() {
751 log.debug("{}: sendInstallSnapshot", logName());
752 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
753 String followerId = e.getKey();
754 ActorSelection followerActor = context.getPeerActorSelection(followerId);
755 FollowerLogInformation followerLogInfo = e.getValue();
757 if (followerActor != null) {
758 long nextIndex = followerLogInfo.getNextIndex();
759 if (followerLogInfo.getInstallSnapshotState() != null
760 || context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
761 || canInstallSnapshot(nextIndex)) {
762 sendSnapshotChunk(followerActor, followerLogInfo);
769 * Sends a snapshot chunk to a given follower
770 * InstallSnapshot should qualify as a heartbeat too.
772 private void sendSnapshotChunk(ActorSelection followerActor, FollowerLogInformation followerLogInfo) {
773 if (snapshot.isPresent()) {
774 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
775 if (installSnapshotState == null) {
776 installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
778 followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
781 // Ensure the snapshot bytes are set - this is a no-op.
782 installSnapshotState.setSnapshotBytes(snapshot.get().getSnapshotBytes());
784 byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();
786 log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
787 nextSnapshotChunk.length);
789 int nextChunkIndex = installSnapshotState.incrementChunkIndex();
790 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
791 if (installSnapshotState.isLastChunk(nextChunkIndex)) {
792 serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
796 new InstallSnapshot(currentTerm(), context.getId(),
797 snapshot.get().getLastIncludedIndex(),
798 snapshot.get().getLastIncludedTerm(),
801 installSnapshotState.getTotalChunks(),
802 Optional.of(installSnapshotState.getLastChunkHashCode()),
804 ).toSerializable(followerLogInfo.getRaftVersion()),
808 log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
809 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
813 private void sendHeartBeat() {
814 if (!followerToLog.isEmpty()) {
815 log.trace("{}: Sending heartbeat", logName());
816 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
820 private void stopHeartBeat() {
821 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
822 heartbeatSchedule.cancel();
826 private void scheduleHeartBeat(FiniteDuration interval) {
827 if (followerToLog.isEmpty()) {
828 // Optimization - do not bother scheduling a heartbeat as there are
835 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
836 // message is sent to itself.
837 // Scheduling the heartbeat only once here because heartbeats do not
838 // need to be sent if there are other messages being sent to the remote
840 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
841 interval, context.getActor(), SendHeartBeat.INSTANCE,
842 context.getActorSystem().dispatcher(), context.getActor());
846 public void close() {
851 public final String getLeaderId() {
852 return context.getId();
856 public final short getLeaderPayloadVersion() {
857 return context.getPayloadVersion();
860 protected boolean isLeaderIsolated() {
861 int minPresent = getMinIsolatedLeaderPeerCount();
862 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
863 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
864 if (peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
866 if (minPresent == 0) {
871 return minPresent != 0;
874 // called from example-actor for printing the follower-states
875 public String printFollowerStates() {
876 final StringBuilder sb = new StringBuilder();
879 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
881 sb.append(followerLogInformation.getId());
882 sb.append(" state:");
883 sb.append(followerLogInformation.isFollowerActive());
888 return sb.toString();
892 public FollowerLogInformation getFollower(String followerId) {
893 return followerToLog.get(followerId);
897 public int followerLogSize() {
898 return followerToLog.size();
901 private static class SnapshotHolder {
902 private final long lastIncludedTerm;
903 private final long lastIncludedIndex;
904 private final ByteString snapshotBytes;
906 SnapshotHolder(Snapshot snapshot) {
907 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
908 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
909 this.snapshotBytes = ByteString.copyFrom(snapshot.getState());
912 long getLastIncludedTerm() {
913 return lastIncludedTerm;
916 long getLastIncludedIndex() {
917 return lastIncludedIndex;
920 ByteString getSnapshotBytes() {
921 return snapshotBytes;