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.common.io.ByteSource;
18 import java.io.IOException;
19 import java.io.ObjectOutputStream;
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 java.util.concurrent.TimeUnit;
30 import javax.annotation.Nullable;
31 import org.opendaylight.controller.cluster.io.SharedFileBackedOutputStream;
32 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
33 import org.opendaylight.controller.cluster.messaging.SliceOptions;
34 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
35 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
36 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
37 import org.opendaylight.controller.cluster.raft.FollowerLogInformationImpl;
38 import org.opendaylight.controller.cluster.raft.PeerInfo;
39 import org.opendaylight.controller.cluster.raft.RaftActorContext;
40 import org.opendaylight.controller.cluster.raft.RaftState;
41 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
42 import org.opendaylight.controller.cluster.raft.VotingState;
43 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
44 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
45 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
46 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
47 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
48 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
49 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
50 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
51 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
52 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
53 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
54 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
55 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
56 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
57 import scala.concurrent.duration.FiniteDuration;
60 * The behavior of a RaftActor when it is in the Leader state
65 * <li> Upon election: send initial empty AppendEntries RPCs
66 * (heartbeat) to each server; repeat during idle periods to
67 * prevent election timeouts (§5.2)
68 * <li> If command received from client: append entry to local log,
69 * respond after entry applied to state machine (§5.3)
70 * <li> If last log index ≥ nextIndex for a follower: send
71 * AppendEntries RPC with log entries starting at nextIndex
72 * <li> If successful: update nextIndex and matchIndex for
74 * <li> If AppendEntries fails because of log inconsistency:
75 * decrement nextIndex and retry (§5.3)
76 * <li> If there exists an N such that N > commitIndex, a majority
77 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
78 * set commitIndex = N (§5.3, §5.4).
81 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
82 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
85 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
86 * expect the entries to be modified in sequence, hence we open-code the lookup.
87 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
88 * but we already expect those to be far from frequent.
90 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
93 * Map of serialized AppendEntries output streams keyed by log index. This is used in conjunction with the
94 * appendEntriesMessageSlicer for slicing single ReplicatedLogEntry payloads that exceed the message size threshold.
95 * This Map allows the SharedFileBackedOutputStreams to be reused for multiple followers.
97 private final Map<Long, SharedFileBackedOutputStream> sharedSerializedAppendEntriesStreams = new HashMap<>();
98 private final MessageSlicer appendEntriesMessageSlicer;
100 private Cancellable heartbeatSchedule = null;
101 private Optional<SnapshotHolder> snapshotHolder = Optional.absent();
102 private int minReplicationCount;
104 protected AbstractLeader(final RaftActorContext context, final RaftState state,
105 @Nullable final AbstractLeader initializeFromLeader) {
106 super(context, state);
108 appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName())
109 .messageSliceSize(context.getConfigParams().getSnapshotChunkSize())
110 .expireStateAfterInactivity(context.getConfigParams().getElectionTimeOutInterval().toMillis() * 3,
111 TimeUnit.MILLISECONDS).build();
113 if (initializeFromLeader != null) {
114 followerToLog.putAll(initializeFromLeader.followerToLog);
115 snapshotHolder = initializeFromLeader.snapshotHolder;
116 trackers.addAll(initializeFromLeader.trackers);
118 for (PeerInfo peerInfo: context.getPeers()) {
119 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(peerInfo, -1, context);
120 followerToLog.put(peerInfo.getId(), followerLogInformation);
124 log.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
126 updateMinReplicaCount();
128 // Immediately schedule a heartbeat
129 // Upon election: send initial empty AppendEntries RPCs
130 // (heartbeat) to each server; repeat during idle periods to
131 // prevent election timeouts (§5.2)
132 sendAppendEntries(0, false);
134 // It is important to schedule this heartbeat here
135 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
138 protected AbstractLeader(final RaftActorContext context, final RaftState state) {
139 this(context, state, null);
143 * Return an immutable collection of follower identifiers.
145 * @return Collection of follower IDs
147 public final Collection<String> getFollowerIds() {
148 return followerToLog.keySet();
151 public void addFollower(final String followerId) {
152 FollowerLogInformation followerLogInformation = new FollowerLogInformationImpl(
153 context.getPeerInfo(followerId), -1, context);
154 followerToLog.put(followerId, followerLogInformation);
156 if (heartbeatSchedule == null) {
157 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
161 public void removeFollower(final String followerId) {
162 followerToLog.remove(followerId);
165 public void updateMinReplicaCount() {
167 for (PeerInfo peer: context.getPeers()) {
168 if (peer.isVoting()) {
173 minReplicationCount = getMajorityVoteCount(numVoting);
176 protected int getMinIsolatedLeaderPeerCount() {
177 //the isolated Leader peer count will be 1 less than the majority vote count.
178 //this is because the vote count has the self vote counted in it
180 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
181 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
182 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
184 return minReplicationCount > 0 ? minReplicationCount - 1 : 0;
188 void setSnapshot(@Nullable final SnapshotHolder snapshotHolder) {
189 this.snapshotHolder = Optional.fromNullable(snapshotHolder);
193 boolean hasSnapshot() {
194 return snapshotHolder.isPresent();
198 protected RaftActorBehavior handleAppendEntries(final ActorRef sender,
199 final AppendEntries appendEntries) {
201 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
207 protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
208 final AppendEntriesReply appendEntriesReply) {
209 log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
211 // Update the FollowerLogInformation
212 String followerId = appendEntriesReply.getFollowerId();
213 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
215 if (followerLogInformation == null) {
216 log.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
220 if (followerLogInformation.timeSinceLastActivity()
221 > context.getConfigParams().getElectionTimeOutInterval().toMillis()) {
222 log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
223 + "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
224 logName(), appendEntriesReply, followerLogInformation.timeSinceLastActivity(),
225 context.getLastApplied(), context.getCommitIndex());
228 followerLogInformation.markFollowerActive();
229 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
230 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
232 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
233 long followersLastLogTermInLeadersLog = getLogEntryTerm(followerLastLogIndex);
234 boolean updated = false;
235 if (appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
236 // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
237 // in raft as a node cannot become leader if it's log is behind another's. However, the
238 // non-voting semantics deviate a bit from raft. Only voting members participate in
239 // elections and can become leader so it's possible for a non-voting follower to be ahead
240 // of the leader. This can happen if persistence is disabled and all voting members are
241 // restarted. In this case, the voting leader will start out with an empty log however
242 // the non-voting followers still retain the previous data in memory. On the first
243 // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
244 // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
245 // lastLogIndex may be higher in which case we want to reset the follower by installing a
246 // snapshot. It's also possible that the follower's last log index is behind the leader's.
247 // However in this case the log terms won't match and the logs will conflict - this is handled
249 log.info("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} "
250 + "(snapshotIndex {}) - forcing install snaphot", logName(), followerLogInformation.getId(),
251 appendEntriesReply.getLogLastIndex(), context.getReplicatedLog().lastIndex(),
252 context.getReplicatedLog().getSnapshotIndex());
254 followerLogInformation.setMatchIndex(-1);
255 followerLogInformation.setNextIndex(-1);
257 initiateCaptureSnapshot(followerId);
260 } else if (appendEntriesReply.isSuccess()) {
261 if (followerLastLogIndex >= 0 && followersLastLogTermInLeadersLog >= 0
262 && followersLastLogTermInLeadersLog != appendEntriesReply.getLogLastTerm()) {
263 // The follower's last entry is present in the leader's journal but the terms don't match so the
264 // follower has a conflicting entry. Since the follower didn't report that it's out of sync, this means
265 // either the previous leader entry sent didn't conflict or the previous leader entry is in the snapshot
266 // and no longer in the journal. Either way, we set the follower's next index to 1 less than the last
267 // index reported by the follower. For the former case, the leader will send all entries starting with
268 // the previous follower's index and the follower will remove and replace the conflicting entries as
269 // needed. For the latter, the leader will initiate an install snapshot.
271 followerLogInformation.setNextIndex(followerLastLogIndex - 1);
274 log.info("{}: handleAppendEntriesReply: follower {} last log term {} for index {} conflicts with the "
275 + "leader's {} - set the follower's next index to {}", logName(),
276 followerId, appendEntriesReply.getLogLastTerm(), appendEntriesReply.getLogLastIndex(),
277 followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
279 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
282 log.info("{}: handleAppendEntriesReply - received unsuccessful reply: {}, leader snapshotIndex: {}",
283 logName(), appendEntriesReply, context.getReplicatedLog().getSnapshotIndex());
285 if (appendEntriesReply.isForceInstallSnapshot()) {
286 // Reset the followers match and next index. This is to signal that this follower has nothing
287 // in common with this Leader and so would require a snapshot to be installed
288 followerLogInformation.setMatchIndex(-1);
289 followerLogInformation.setNextIndex(-1);
291 // Force initiate a snapshot capture
292 initiateCaptureSnapshot(followerId);
293 } else if (followerLastLogIndex < 0 || followersLastLogTermInLeadersLog >= 0
294 && followersLastLogTermInLeadersLog == appendEntriesReply.getLogLastTerm()) {
295 // The follower's log is empty or the last entry is present in the leader's journal
296 // and the terms match so the follower is just behind the leader's journal from
297 // the last snapshot, if any. We'll catch up the follower quickly by starting at the
298 // follower's last log index.
300 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
302 log.info("{}: follower {} appears to be behind the leader from the last snapshot - "
303 + "updated: matchIndex: {}, nextIndex: {}", logName(), followerId,
304 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
306 // The follower's log conflicts with leader's log so decrement follower's next index by 1
307 // in an attempt to find where the logs match.
309 if (followerLogInformation.decrNextIndex()) {
312 log.info("{}: follower {} last log term {} conflicts with the leader's {} - dec next index to {}",
313 logName(), followerId, appendEntriesReply.getLogLastTerm(),
314 followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
319 if (log.isTraceEnabled()) {
320 log.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
321 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
324 possiblyUpdateCommitIndex();
326 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
327 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
332 private void possiblyUpdateCommitIndex() {
333 // Figure out if we can update the the commitIndex as follows:
334 // If there exists an index N such that N > commitIndex, a majority of matchIndex[i] ≥ N,
335 // and log[N].term == currentTerm:
336 // set commitIndex = N (§5.3, §5.4).
337 for (long index = context.getCommitIndex() + 1; ; index++) {
338 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(index);
339 if (replicatedLogEntry == null) {
340 log.trace("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
341 logName(), index, context.getReplicatedLog().getSnapshotIndex(),
342 context.getReplicatedLog().size());
346 // Count our entry if it has been persisted.
347 int replicatedCount = replicatedLogEntry.isPersistencePending() ? 0 : 1;
349 if (replicatedCount == 0) {
350 // We don't commit and apply a log entry until we've gotten the ack from our local persistence,
351 // even though there *shouldn't* be any issue with updating the commit index if we get a consensus
352 // amongst the followers w/o the local persistence ack.
356 log.trace("{}: checking Nth index {}", logName(), index);
357 for (FollowerLogInformation info : followerToLog.values()) {
358 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
359 if (info.getMatchIndex() >= index && peerInfo != null && peerInfo.isVoting()) {
361 } else if (log.isTraceEnabled()) {
362 log.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
363 info.getMatchIndex(), peerInfo);
367 if (log.isTraceEnabled()) {
368 log.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount,
369 minReplicationCount);
372 if (replicatedCount >= minReplicationCount) {
373 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
374 // "Raft never commits log entries from previous terms by counting replicas".
375 // However we keep looping so we can make progress when new entries in the current term
376 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
377 // counting replicas, then all prior entries are committed indirectly".
378 if (replicatedLogEntry.getTerm() == currentTerm()) {
379 log.trace("{}: Setting commit index to {}", logName(), index);
380 context.setCommitIndex(index);
382 log.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, "
383 + "term {} does not match the current term {}", logName(), index,
384 replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
387 log.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
392 // Apply the change to the state machine
393 if (context.getCommitIndex() > context.getLastApplied()) {
394 log.debug("{}: Applying to log - commitIndex: {}, lastAppliedIndex: {}", logName(),
395 context.getCommitIndex(), context.getLastApplied());
397 applyLogToStateMachine(context.getCommitIndex());
400 if (!context.getSnapshotManager().isCapturing()) {
405 private boolean updateFollowerLogInformation(final FollowerLogInformation followerLogInformation,
406 final AppendEntriesReply appendEntriesReply) {
407 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
408 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
410 if (updated && log.isDebugEnabled()) {
412 "{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
413 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
414 followerLogInformation.getNextIndex());
419 private void purgeInMemoryLog() {
420 //find the lowest index across followers which has been replicated to all.
421 // lastApplied if there are no followers, so that we keep clearing the log for single-node
422 // we would delete the in-mem log from that index on, in-order to minimize mem usage
423 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
424 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
425 for (FollowerLogInformation info : followerToLog.values()) {
426 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
429 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
433 protected ClientRequestTracker removeClientRequestTracker(final long logIndex) {
434 final Iterator<ClientRequestTracker> it = trackers.iterator();
435 while (it.hasNext()) {
436 final ClientRequestTracker t = it.next();
437 if (t.getIndex() == logIndex) {
447 protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender,
448 final RequestVoteReply requestVoteReply) {
452 protected void beforeSendHeartbeat(){}
455 public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
456 Preconditions.checkNotNull(sender, "sender should not be null");
458 if (appendEntriesMessageSlicer.handleMessage(message)) {
462 if (message instanceof RaftRPC) {
463 RaftRPC rpc = (RaftRPC) message;
464 // If RPC request or response contains term T > currentTerm:
465 // set currentTerm = T, convert to follower (§5.1)
466 // This applies to all RPC messages and responses
467 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
468 log.info("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
469 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
471 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
473 // This is a special case. Normally when stepping down as leader we don't process and reply to the
474 // RaftRPC as per raft. But if we're in the process of transferring leadership and we get a
475 // RequestVote, process the RequestVote before switching to Follower. This enables the requesting
476 // candidate node to be elected the leader faster and avoids us possibly timing out in the Follower
477 // state and starting a new election and grabbing leadership back before the other candidate node can
478 // start a new election due to lack of responses. This case would only occur if there isn't a majority
479 // of other nodes available that can elect the requesting candidate. Since we're transferring
480 // leadership, we should make every effort to get the requesting node elected.
481 if (message instanceof RequestVote && context.getRaftActorLeadershipTransferCohort() != null) {
482 log.debug("{}: Leadership transfer in progress - processing RequestVote", logName());
483 super.handleMessage(sender, message);
486 return internalSwitchBehavior(RaftState.Follower);
490 if (message instanceof SendHeartBeat) {
491 beforeSendHeartbeat();
493 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
494 } else if (message instanceof SendInstallSnapshot) {
495 SendInstallSnapshot sendInstallSnapshot = (SendInstallSnapshot) message;
496 setSnapshot(new SnapshotHolder(sendInstallSnapshot.getSnapshot(), sendInstallSnapshot.getSnapshotBytes()));
497 sendInstallSnapshot();
498 } else if (message instanceof Replicate) {
499 replicate((Replicate) message);
500 } else if (message instanceof InstallSnapshotReply) {
501 handleInstallSnapshotReply((InstallSnapshotReply) message);
502 } else if (message instanceof CheckConsensusReached) {
503 possiblyUpdateCommitIndex();
505 return super.handleMessage(sender, message);
511 private void handleInstallSnapshotReply(final InstallSnapshotReply reply) {
512 log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
514 String followerId = reply.getFollowerId();
515 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
516 if (followerLogInformation == null) {
517 // This can happen during AddServer if it times out.
518 log.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
519 logName(), followerId);
523 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
524 if (installSnapshotState == null) {
525 log.error("{}: LeaderInstallSnapshotState not found for follower {} in InstallSnapshotReply",
526 logName(), followerId);
530 followerLogInformation.markFollowerActive();
532 if (installSnapshotState.getChunkIndex() == reply.getChunkIndex()) {
533 boolean wasLastChunk = false;
534 if (reply.isSuccess()) {
535 if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
536 //this was the last chunk reply
538 long followerMatchIndex = snapshotHolder.get().getLastIncludedIndex();
539 followerLogInformation.setMatchIndex(followerMatchIndex);
540 followerLogInformation.setNextIndex(followerMatchIndex + 1);
541 followerLogInformation.clearLeaderInstallSnapshotState();
543 log.info("{}: Snapshot successfully installed on follower {} (last chunk {}) - "
544 + "matchIndex set to {}, nextIndex set to {}", logName(), followerId, reply.getChunkIndex(),
545 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
547 if (!anyFollowersInstallingSnapshot()) {
548 // once there are no pending followers receiving snapshots
549 // we can remove snapshot from the memory
554 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
555 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
556 new UnInitializedFollowerSnapshotReply(followerId);
557 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
558 log.debug("Sent message UnInitializedFollowerSnapshotReply to self");
561 installSnapshotState.markSendStatus(true);
564 log.warn("{}: Received failed InstallSnapshotReply - will retry: {}", logName(), reply);
566 installSnapshotState.markSendStatus(false);
570 if (!context.getSnapshotManager().isCapturing()) {
571 // Since the follower is now caught up try to purge the log.
575 ActorSelection followerActor = context.getPeerActorSelection(followerId);
576 if (followerActor != null) {
577 sendSnapshotChunk(followerActor, followerLogInformation);
582 log.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
583 logName(), reply.getChunkIndex(), followerId,
584 installSnapshotState.getChunkIndex());
586 if (reply.getChunkIndex() == LeaderInstallSnapshotState.INVALID_CHUNK_INDEX) {
587 // Since the Follower did not find this index to be valid we should reset the follower snapshot
588 // so that Installing the snapshot can resume from the beginning
589 installSnapshotState.reset();
594 private boolean anyFollowersInstallingSnapshot() {
595 for (FollowerLogInformation info: followerToLog.values()) {
596 if (info.getInstallSnapshotState() != null) {
605 private void replicate(final Replicate replicate) {
606 long logIndex = replicate.getReplicatedLogEntry().getIndex();
608 log.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}, isSendImmediate: {}", logName(),
609 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass(),
610 replicate.isSendImmediate());
612 // Create a tracker entry we will use this later to notify the
614 if (replicate.getClientActor() != null) {
615 trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
619 boolean applyModificationToState = !context.anyVotingPeers()
620 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
622 if (applyModificationToState) {
623 context.setCommitIndex(logIndex);
624 applyLogToStateMachine(logIndex);
627 if (replicate.isSendImmediate() && !followerToLog.isEmpty()) {
628 sendAppendEntries(0, false);
632 protected void sendAppendEntries(final long timeSinceLastActivityInterval, final boolean isHeartbeat) {
633 // Send an AppendEntries to all followers
634 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
635 final String followerId = e.getKey();
636 final FollowerLogInformation followerLogInformation = e.getValue();
637 // This checks helps not to send a repeat message to the follower
638 if (!followerLogInformation.isFollowerActive()
639 || followerLogInformation.timeSinceLastActivity() >= timeSinceLastActivityInterval) {
640 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
646 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
647 * sending next snapshot chunk, and initiating a snapshot.
649 private void sendUpdatesToFollower(final String followerId, final FollowerLogInformation followerLogInformation,
650 final boolean sendHeartbeat, final boolean isHeartbeat) {
652 ActorSelection followerActor = context.getPeerActorSelection(followerId);
653 if (followerActor != null) {
654 long followerNextIndex = followerLogInformation.getNextIndex();
655 boolean isFollowerActive = followerLogInformation.isFollowerActive();
656 boolean sendAppendEntries = false;
657 List<ReplicatedLogEntry> entries = Collections.emptyList();
659 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
660 if (installSnapshotState != null) {
661 // if install snapshot is in process , then sent next chunk if possible
662 if (isFollowerActive && installSnapshotState.canSendNextChunk()) {
663 sendSnapshotChunk(followerActor, followerLogInformation);
664 } else if (sendHeartbeat) {
665 // we send a heartbeat even if we have not received a reply for the last chunk
666 sendAppendEntries = true;
668 } else if (followerLogInformation.isLogEntrySlicingInProgress()) {
669 sendAppendEntries = sendHeartbeat;
671 long leaderLastIndex = context.getReplicatedLog().lastIndex();
672 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
674 if (!isHeartbeat && log.isDebugEnabled() || log.isTraceEnabled()) {
675 log.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, "
676 + "leaderLastIndex: {}, leaderSnapShotIndex: {}", logName(), followerId, isFollowerActive,
677 followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
680 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
682 log.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
683 followerNextIndex, followerId);
685 if (followerLogInformation.okToReplicate()) {
686 entries = getEntriesToSend(followerLogInformation, followerActor);
687 sendAppendEntries = true;
689 } else if (isFollowerActive && followerNextIndex >= 0
690 && leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
691 // if the followers next index is not present in the leaders log, and
692 // if the follower is just not starting and if leader's index is more than followers index
693 // then snapshot should be sent
695 // Send heartbeat to follower whenever install snapshot is initiated.
696 sendAppendEntries = true;
697 if (canInstallSnapshot(followerNextIndex)) {
698 log.info("{}: Initiating install snapshot to follower {}: follower nextIndex: {}, leader "
699 + "snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(), followerId,
700 followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
701 context.getReplicatedLog().size());
703 initiateCaptureSnapshot(followerId);
705 // It doesn't seem like we should ever reach here - most likely indicates sonething is
707 log.info("{}: Follower {} is behind but cannot install snapshot: follower nextIndex: {}, "
708 + "leader snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(),
709 followerId, followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
710 context.getReplicatedLog().size());
713 } else if (sendHeartbeat) {
714 // we send an AppendEntries, even if the follower is inactive
715 // in-order to update the followers timestamp, in case it becomes active again
716 sendAppendEntries = true;
721 if (sendAppendEntries) {
722 sendAppendEntriesToFollower(followerActor, entries, followerLogInformation);
727 private List<ReplicatedLogEntry> getEntriesToSend(FollowerLogInformation followerLogInfo,
728 ActorSelection followerActor) {
729 // Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
731 int maxEntries = (int) context.getReplicatedLog().size();
732 final int maxDataSize = context.getConfigParams().getSnapshotChunkSize();
733 final long followerNextIndex = followerLogInfo.getNextIndex();
734 List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex,
735 maxEntries, maxDataSize);
737 // If the first entry's size exceeds the max data size threshold, it will be returned from the call above. If
738 // that is the case, then we need to slice it into smaller chunks.
739 if (!(entries.size() == 1 && entries.get(0).getData().size() > maxDataSize)) {
740 // Don't need to slice.
744 log.debug("{}: Log entry size {} exceeds max payload size {}", logName(), entries.get(0).getData().size(),
747 // If an AppendEntries has already been serialized for the log index then reuse the
748 // SharedFileBackedOutputStream.
749 final Long logIndex = entries.get(0).getIndex();
750 SharedFileBackedOutputStream fileBackedStream = sharedSerializedAppendEntriesStreams.get(logIndex);
751 if (fileBackedStream == null) {
752 fileBackedStream = context.getFileBackedOutputStreamFactory().newSharedInstance();
754 final AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
755 getLogEntryIndex(followerNextIndex - 1), getLogEntryTerm(followerNextIndex - 1), entries,
756 context.getCommitIndex(), getReplicatedToAllIndex(), context.getPayloadVersion());
758 log.debug("{}: Serializing {} for slicing for follower {}", logName(), appendEntries,
759 followerLogInfo.getId());
761 try (ObjectOutputStream out = new ObjectOutputStream(fileBackedStream)) {
762 out.writeObject(appendEntries);
763 } catch (IOException e) {
764 log.error("{}: Error serializing {}", logName(), appendEntries, e);
765 fileBackedStream.cleanup();
766 return Collections.emptyList();
769 sharedSerializedAppendEntriesStreams.put(logIndex, fileBackedStream);
771 fileBackedStream.setOnCleanupCallback(index -> {
772 log.debug("{}: On SharedFileBackedOutputStream cleanup for index {}", logName(), index);
773 sharedSerializedAppendEntriesStreams.remove(index);
776 log.debug("{}: Reusing SharedFileBackedOutputStream for follower {}", logName(), followerLogInfo.getId());
777 fileBackedStream.incrementUsageCount();
780 log.debug("{}: Slicing stream for index {}, follower {}", logName(), logIndex, followerLogInfo.getId());
782 // Record that slicing is in progress for the follower.
783 followerLogInfo.setSlicedLogEntryIndex(logIndex);
785 final FollowerIdentifier identifier = new FollowerIdentifier(followerLogInfo.getId());
786 appendEntriesMessageSlicer.slice(SliceOptions.builder().identifier(identifier)
787 .fileBackedOutputStream(fileBackedStream).sendTo(followerActor).replyTo(actor())
788 .onFailureCallback(failure -> {
789 log.error("{}: Error slicing AppendEntries for follower {}", logName(),
790 followerLogInfo.getId(), failure);
791 followerLogInfo.setSlicedLogEntryIndex(FollowerLogInformation.NO_INDEX);
794 return Collections.emptyList();
797 private void sendAppendEntriesToFollower(ActorSelection followerActor, List<ReplicatedLogEntry> entries,
798 FollowerLogInformation followerLogInformation) {
799 // In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
800 // possibly committing and applying conflicting entries (those with same index, different term) from a prior
801 // term that weren't replicated to a majority, which would be a violation of raft.
802 // - if the follower isn't active. In this case we don't know the state of the follower and we send an
803 // empty AppendEntries as a heart beat to prevent election.
804 // - if we're in the process of installing a snapshot. In this case we don't send any new entries but still
805 // need to send AppendEntries to prevent election.
806 // - if we're in the process of slicing an AppendEntries with a large log entry payload. In this case we
807 // need to send an empty AppendEntries to prevent election.
808 boolean isInstallingSnaphot = followerLogInformation.getInstallSnapshotState() != null;
809 long leaderCommitIndex = isInstallingSnaphot || followerLogInformation.isLogEntrySlicingInProgress()
810 || !followerLogInformation.isFollowerActive() ? -1 : context.getCommitIndex();
812 long followerNextIndex = followerLogInformation.getNextIndex();
813 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
814 getLogEntryIndex(followerNextIndex - 1),
815 getLogEntryTerm(followerNextIndex - 1), entries,
816 leaderCommitIndex, super.getReplicatedToAllIndex(), context.getPayloadVersion());
818 if (!entries.isEmpty() || log.isTraceEnabled()) {
819 log.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerLogInformation.getId(),
823 followerActor.tell(appendEntries, actor());
827 * Initiates a snapshot capture to install on a follower.
830 * Install Snapshot works as follows
831 * 1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
832 * 2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
833 * the Leader's handleMessage with a SendInstallSnapshot message.
834 * 3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
835 * the Follower via InstallSnapshot messages.
836 * 4. For each chunk, the Follower sends back an InstallSnapshotReply.
837 * 5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
839 * 6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
840 * then send the existing snapshot in chunks to the follower.
842 * @param followerId the id of the follower.
843 * @return true if capture was initiated, false otherwise.
845 public boolean initiateCaptureSnapshot(final String followerId) {
846 FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
847 if (snapshotHolder.isPresent()) {
848 // If a snapshot is present in the memory, most likely another install is in progress no need to capture
849 // snapshot. This could happen if another follower needs an install when one is going on.
850 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
852 // Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
853 sendSnapshotChunk(followerActor, followerLogInfo);
857 boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
858 this.getReplicatedToAllIndex(), followerId);
859 if (captureInitiated) {
860 followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
861 context.getConfigParams().getSnapshotChunkSize(), logName()));
864 return captureInitiated;
867 private boolean canInstallSnapshot(final long nextIndex) {
868 // If the follower's nextIndex is -1 then we might as well send it a snapshot
869 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
871 return nextIndex == -1 || !context.getReplicatedLog().isPresent(nextIndex)
872 && context.getReplicatedLog().isInSnapshot(nextIndex);
877 private void sendInstallSnapshot() {
878 log.debug("{}: sendInstallSnapshot", logName());
879 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
880 String followerId = e.getKey();
881 ActorSelection followerActor = context.getPeerActorSelection(followerId);
882 FollowerLogInformation followerLogInfo = e.getValue();
884 if (followerActor != null) {
885 long nextIndex = followerLogInfo.getNextIndex();
886 if (followerLogInfo.getInstallSnapshotState() != null
887 || context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
888 || canInstallSnapshot(nextIndex)) {
889 sendSnapshotChunk(followerActor, followerLogInfo);
896 * Sends a snapshot chunk to a given follower
897 * InstallSnapshot should qualify as a heartbeat too.
899 private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) {
900 if (snapshotHolder.isPresent()) {
901 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
902 if (installSnapshotState == null) {
903 installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
905 followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
909 // Ensure the snapshot bytes are set - this is a no-op.
910 installSnapshotState.setSnapshotBytes(snapshotHolder.get().getSnapshotBytes());
912 if (!installSnapshotState.canSendNextChunk()) {
916 byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();
918 log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
919 nextSnapshotChunk.length);
921 int nextChunkIndex = installSnapshotState.incrementChunkIndex();
922 Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
923 if (installSnapshotState.isLastChunk(nextChunkIndex)) {
924 serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
928 new InstallSnapshot(currentTerm(), context.getId(),
929 snapshotHolder.get().getLastIncludedIndex(),
930 snapshotHolder.get().getLastIncludedTerm(),
933 installSnapshotState.getTotalChunks(),
934 Optional.of(installSnapshotState.getLastChunkHashCode()),
936 ).toSerializable(followerLogInfo.getRaftVersion()),
940 } catch (IOException e) {
941 throw new RuntimeException(e);
944 log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
945 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
949 private void sendHeartBeat() {
950 if (!followerToLog.isEmpty()) {
951 log.trace("{}: Sending heartbeat", logName());
952 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toMillis(), true);
954 appendEntriesMessageSlicer.checkExpiredSlicedMessageState();
958 private void stopHeartBeat() {
959 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
960 heartbeatSchedule.cancel();
964 private void scheduleHeartBeat(final FiniteDuration interval) {
965 if (followerToLog.isEmpty()) {
966 // Optimization - do not bother scheduling a heartbeat as there are
973 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
974 // message is sent to itself.
975 // Scheduling the heartbeat only once here because heartbeats do not
976 // need to be sent if there are other messages being sent to the remote
978 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
979 interval, context.getActor(), SendHeartBeat.INSTANCE,
980 context.getActorSystem().dispatcher(), context.getActor());
984 public void close() {
986 appendEntriesMessageSlicer.close();
990 public final String getLeaderId() {
991 return context.getId();
995 public final short getLeaderPayloadVersion() {
996 return context.getPayloadVersion();
999 protected boolean isLeaderIsolated() {
1000 int minPresent = getMinIsolatedLeaderPeerCount();
1001 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1002 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
1003 if (peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
1005 if (minPresent == 0) {
1010 return minPresent != 0;
1013 // called from example-actor for printing the follower-states
1014 public String printFollowerStates() {
1015 final StringBuilder sb = new StringBuilder();
1018 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1020 sb.append(followerLogInformation.getId());
1021 sb.append(" state:");
1022 sb.append(followerLogInformation.isFollowerActive());
1027 return sb.toString();
1031 public FollowerLogInformation getFollower(final String followerId) {
1032 return followerToLog.get(followerId);
1036 public int followerLogSize() {
1037 return followerToLog.size();
1040 static class SnapshotHolder {
1041 private final long lastIncludedTerm;
1042 private final long lastIncludedIndex;
1043 private final ByteSource snapshotBytes;
1045 SnapshotHolder(final Snapshot snapshot, final ByteSource snapshotBytes) {
1046 this.lastIncludedTerm = snapshot.getLastAppliedTerm();
1047 this.lastIncludedIndex = snapshot.getLastAppliedIndex();
1048 this.snapshotBytes = snapshotBytes;
1051 long getLastIncludedTerm() {
1052 return lastIncludedTerm;
1055 long getLastIncludedIndex() {
1056 return lastIncludedIndex;
1059 ByteSource getSnapshotBytes() {
1060 return snapshotBytes;