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
8 package org.opendaylight.controller.cluster.raft.behaviors;
10 import static java.util.Objects.requireNonNull;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.Cancellable;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.io.ByteSource;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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.Optional;
29 import java.util.OptionalInt;
30 import java.util.Queue;
31 import java.util.concurrent.TimeUnit;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.opendaylight.controller.cluster.io.SharedFileBackedOutputStream;
34 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
35 import org.opendaylight.controller.cluster.messaging.SliceOptions;
36 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
37 import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
38 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
39 import org.opendaylight.controller.cluster.raft.PeerInfo;
40 import org.opendaylight.controller.cluster.raft.RaftActorContext;
41 import org.opendaylight.controller.cluster.raft.RaftState;
42 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
43 import org.opendaylight.controller.cluster.raft.VotingState;
44 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
45 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
46 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
47 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
48 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
49 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
50 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
51 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
52 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
53 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
54 import org.opendaylight.controller.cluster.raft.messages.Payload;
55 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
56 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
57 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
58 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
59 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
60 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
61 import scala.concurrent.duration.FiniteDuration;
64 * The behavior of a RaftActor when it is in the Leader state.
69 * <li> Upon election: send initial empty AppendEntries RPCs
70 * (heartbeat) to each server; repeat during idle periods to
71 * prevent election timeouts (§5.2)
72 * <li> If command received from client: append entry to local log,
73 * respond after entry applied to state machine (§5.3)
74 * <li> If last log index ≥ nextIndex for a follower: send
75 * AppendEntries RPC with log entries starting at nextIndex
76 * <li> If successful: update nextIndex and matchIndex for
78 * <li> If AppendEntries fails because of log inconsistency:
79 * decrement nextIndex and retry (§5.3)
80 * <li> If there exists an N such that N > commitIndex, a majority
81 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
82 * set commitIndex = N (§5.3, §5.4).
85 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
86 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
89 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
90 * expect the entries to be modified in sequence, hence we open-code the lookup.
91 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
92 * but we already expect those to be far from frequent.
94 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
97 * Map of serialized AppendEntries output streams keyed by log index. This is used in conjunction with the
98 * appendEntriesMessageSlicer for slicing single ReplicatedLogEntry payloads that exceed the message size threshold.
99 * This Map allows the SharedFileBackedOutputStreams to be reused for multiple followers.
101 private final Map<Long, SharedFileBackedOutputStream> sharedSerializedAppendEntriesStreams = new HashMap<>();
102 private final MessageSlicer appendEntriesMessageSlicer;
104 private Cancellable heartbeatSchedule = null;
105 private Optional<SnapshotHolder> snapshotHolder = Optional.empty();
106 private int minReplicationCount;
108 protected AbstractLeader(final RaftActorContext context, final RaftState state,
109 final @Nullable AbstractLeader initializeFromLeader) {
110 super(context, state);
112 appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName())
113 .messageSliceSize(context.getConfigParams().getSnapshotChunkSize())
114 .expireStateAfterInactivity(context.getConfigParams().getElectionTimeOutInterval().toMillis() * 3,
115 TimeUnit.MILLISECONDS).build();
117 if (initializeFromLeader != null) {
118 followerToLog.putAll(initializeFromLeader.followerToLog);
119 snapshotHolder = initializeFromLeader.snapshotHolder;
120 trackers.addAll(initializeFromLeader.trackers);
122 for (PeerInfo peerInfo: context.getPeers()) {
123 FollowerLogInformation followerLogInformation = new FollowerLogInformation(peerInfo, context);
124 followerToLog.put(peerInfo.getId(), followerLogInformation);
128 log.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
130 updateMinReplicaCount();
132 // Immediately schedule a heartbeat
133 // Upon election: send initial empty AppendEntries RPCs
134 // (heartbeat) to each server; repeat during idle periods to
135 // prevent election timeouts (§5.2)
136 sendAppendEntries(0, false);
138 // It is important to schedule this heartbeat here
139 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
142 protected AbstractLeader(final RaftActorContext context, final RaftState state) {
143 this(context, state, null);
147 * Return an immutable collection of follower identifiers.
149 * @return Collection of follower IDs
151 public final Collection<String> getFollowerIds() {
152 return followerToLog.keySet();
155 public void addFollower(final String followerId) {
156 FollowerLogInformation followerLogInformation = new FollowerLogInformation(context.getPeerInfo(followerId),
158 followerToLog.put(followerId, followerLogInformation);
160 if (heartbeatSchedule == null) {
161 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
165 public void removeFollower(final String followerId) {
166 followerToLog.remove(followerId);
169 public final void updateMinReplicaCount() {
171 for (PeerInfo peer: context.getPeers()) {
172 if (peer.isVoting()) {
177 minReplicationCount = getMajorityVoteCount(numVoting);
180 protected int getMinIsolatedLeaderPeerCount() {
181 //the isolated Leader peer count will be 1 less than the majority vote count.
182 //this is because the vote count has the self vote counted in it
184 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
185 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
186 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
188 return minReplicationCount > 0 ? minReplicationCount - 1 : 0;
192 void setSnapshotHolder(final @Nullable SnapshotHolder snapshotHolder) {
193 this.snapshotHolder = Optional.ofNullable(snapshotHolder);
197 boolean hasSnapshot() {
198 return snapshotHolder.isPresent();
202 protected RaftActorBehavior handleAppendEntries(final ActorRef sender,
203 final AppendEntries appendEntries) {
205 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
211 protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
212 final AppendEntriesReply appendEntriesReply) {
213 log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
215 // Update the FollowerLogInformation
216 String followerId = appendEntriesReply.getFollowerId();
217 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
219 if (followerLogInformation == null) {
220 log.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
224 final long lastActivityNanos = followerLogInformation.nanosSinceLastActivity();
225 if (lastActivityNanos > context.getConfigParams().getElectionTimeOutInterval().toNanos()) {
226 log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
227 + "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
228 logName(), appendEntriesReply, TimeUnit.NANOSECONDS.toMillis(lastActivityNanos),
229 context.getLastApplied(), context.getCommitIndex());
232 followerLogInformation.markFollowerActive();
233 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
234 followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
235 followerLogInformation.setNeedsLeaderAddress(appendEntriesReply.isNeedsLeaderAddress());
237 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
238 boolean updated = false;
239 if (appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
240 // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
241 // in raft as a node cannot become leader if it's log is behind another's. However, the
242 // non-voting semantics deviate a bit from raft. Only voting members participate in
243 // elections and can become leader so it's possible for a non-voting follower to be ahead
244 // of the leader. This can happen if persistence is disabled and all voting members are
245 // restarted. In this case, the voting leader will start out with an empty log however
246 // the non-voting followers still retain the previous data in memory. On the first
247 // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
248 // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
249 // lastLogIndex may be higher in which case we want to reset the follower by installing a
250 // snapshot. It's also possible that the follower's last log index is behind the leader's.
251 // However in this case the log terms won't match and the logs will conflict - this is handled
253 log.info("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} "
254 + "(snapshotIndex {}, snapshotTerm {}) - forcing install snaphot", logName(),
255 followerLogInformation.getId(), appendEntriesReply.getLogLastIndex(),
256 context.getReplicatedLog().lastIndex(), context.getReplicatedLog().getSnapshotIndex(),
257 context.getReplicatedLog().getSnapshotTerm());
259 followerLogInformation.setMatchIndex(-1);
260 followerLogInformation.setNextIndex(-1);
262 initiateCaptureSnapshot(followerId);
265 } else if (appendEntriesReply.isSuccess()) {
266 long followersLastLogTermInLeadersLog = getLogEntryTerm(followerLastLogIndex);
267 if (followerLastLogIndex >= 0 && followersLastLogTermInLeadersLog >= 0
268 && followersLastLogTermInLeadersLog != appendEntriesReply.getLogLastTerm()) {
269 // The follower's last entry is present in the leader's journal but the terms don't match so the
270 // follower has a conflicting entry. Since the follower didn't report that it's out of sync, this means
271 // either the previous leader entry sent didn't conflict or the previous leader entry is in the snapshot
272 // and no longer in the journal. Either way, we set the follower's next index to 1 less than the last
273 // index reported by the follower. For the former case, the leader will send all entries starting with
274 // the previous follower's index and the follower will remove and replace the conflicting entries as
275 // needed. For the latter, the leader will initiate an install snapshot.
277 followerLogInformation.setNextIndex(followerLastLogIndex - 1);
280 log.info("{}: handleAppendEntriesReply: follower {} last log term {} for index {} conflicts with the "
281 + "leader's {} - set the follower's next index to {}", logName(),
282 followerId, appendEntriesReply.getLogLastTerm(), appendEntriesReply.getLogLastIndex(),
283 followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
285 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
288 log.info("{}: handleAppendEntriesReply - received unsuccessful reply: {}, leader snapshotIndex: {}, "
289 + "snapshotTerm: {}, replicatedToAllIndex: {}", logName(), appendEntriesReply,
290 context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm(),
291 getReplicatedToAllIndex());
293 long followersLastLogTermInLeadersLogOrSnapshot = getLogEntryOrSnapshotTerm(followerLastLogIndex);
294 if (appendEntriesReply.isForceInstallSnapshot()) {
295 // Reset the followers match and next index. This is to signal that this follower has nothing
296 // in common with this Leader and so would require a snapshot to be installed
297 followerLogInformation.setMatchIndex(-1);
298 followerLogInformation.setNextIndex(-1);
300 // Force initiate a snapshot capture
301 initiateCaptureSnapshot(followerId);
302 } else if (followerLastLogIndex < 0 || followersLastLogTermInLeadersLogOrSnapshot >= 0
303 && followersLastLogTermInLeadersLogOrSnapshot == appendEntriesReply.getLogLastTerm()) {
304 // The follower's log is empty or the follower's last entry is present in the leader's journal or
305 // snapshot and the terms match so the follower is just behind the leader's journal from the last
306 // snapshot, if any. We'll catch up the follower quickly by starting at the follower's last log index.
308 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
310 log.info("{}: follower {} appears to be behind the leader from the last snapshot - "
311 + "updated: matchIndex: {}, nextIndex: {}", logName(), followerId,
312 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
314 // The follower's log conflicts with leader's log so decrement follower's next index
315 // in an attempt to find where the logs match.
316 if (followerLogInformation.decrNextIndex(appendEntriesReply.getLogLastIndex())) {
319 log.info("{}: follower {} last log term {} conflicts with the leader's {} - dec next index to {}",
320 logName(), followerId, appendEntriesReply.getLogLastTerm(),
321 followersLastLogTermInLeadersLogOrSnapshot, followerLogInformation.getNextIndex());
326 if (log.isTraceEnabled()) {
327 log.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
328 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
331 possiblyUpdateCommitIndex();
333 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
334 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
339 private void possiblyUpdateCommitIndex() {
340 // Figure out if we can update the the commitIndex as follows:
341 // If there exists an index N such that N > commitIndex, a majority of matchIndex[i] ≥ N,
342 // and log[N].term == currentTerm:
343 // set commitIndex = N (§5.3, §5.4).
344 for (long index = context.getCommitIndex() + 1; ; index++) {
345 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(index);
346 if (replicatedLogEntry == null) {
347 log.trace("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
348 logName(), index, context.getReplicatedLog().getSnapshotIndex(),
349 context.getReplicatedLog().size());
353 // Count our entry if it has been persisted.
354 int replicatedCount = replicatedLogEntry.isPersistencePending() ? 0 : 1;
356 if (replicatedCount == 0) {
357 // We don't commit and apply a log entry until we've gotten the ack from our local persistence,
358 // even though there *shouldn't* be any issue with updating the commit index if we get a consensus
359 // amongst the followers w/o the local persistence ack.
363 log.trace("{}: checking Nth index {}", logName(), index);
364 for (FollowerLogInformation info : followerToLog.values()) {
365 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
366 if (info.getMatchIndex() >= index && peerInfo != null && peerInfo.isVoting()) {
368 } else if (log.isTraceEnabled()) {
369 log.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
370 info.getMatchIndex(), peerInfo);
374 if (log.isTraceEnabled()) {
375 log.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount,
376 minReplicationCount);
379 if (replicatedCount >= minReplicationCount) {
380 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
381 // "Raft never commits log entries from previous terms by counting replicas".
382 // However we keep looping so we can make progress when new entries in the current term
383 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
384 // counting replicas, then all prior entries are committed indirectly".
385 if (replicatedLogEntry.getTerm() == currentTerm()) {
386 log.trace("{}: Setting commit index to {}", logName(), index);
387 context.setCommitIndex(index);
389 log.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, "
390 + "term {} does not match the current term {}", logName(), index,
391 replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
394 log.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
399 // Apply the change to the state machine
400 if (context.getCommitIndex() > context.getLastApplied()) {
401 log.debug("{}: Applying to log - commitIndex: {}, lastAppliedIndex: {}", logName(),
402 context.getCommitIndex(), context.getLastApplied());
404 applyLogToStateMachine(context.getCommitIndex());
407 if (!context.getSnapshotManager().isCapturing()) {
412 private boolean updateFollowerLogInformation(final FollowerLogInformation followerLogInformation,
413 final AppendEntriesReply appendEntriesReply) {
414 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
415 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
417 if (updated && log.isDebugEnabled()) {
419 "{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
420 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
421 followerLogInformation.getNextIndex());
426 private void purgeInMemoryLog() {
427 //find the lowest index across followers which has been replicated to all.
428 // lastApplied if there are no followers, so that we keep clearing the log for single-node
429 // we would delete the in-mem log from that index on, in-order to minimize mem usage
430 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
431 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
432 for (FollowerLogInformation info : followerToLog.values()) {
433 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
436 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
440 * Removes and returns the ClientRequestTracker for the specified log index.
441 * @param logIndex the log index
442 * @return the ClientRequestTracker or null if none available
444 private ClientRequestTracker removeClientRequestTracker(final long logIndex) {
445 final Iterator<ClientRequestTracker> it = trackers.iterator();
446 while (it.hasNext()) {
447 final ClientRequestTracker t = it.next();
448 if (t.getIndex() == logIndex) {
458 final ApplyState getApplyStateFor(final ReplicatedLogEntry entry) {
459 // first check whether a ClientRequestTracker exists for this entry.
460 // If it does that means the leader wasn't dropped before the transaction applied.
461 // That means that this transaction can be safely applied as a local transaction since we
462 // have the ClientRequestTracker.
463 final ClientRequestTracker tracker = removeClientRequestTracker(entry.getIndex());
464 if (tracker != null) {
465 return new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), entry);
468 // Tracker is missing, this means that we switched behaviours between replicate and applystate
469 // and became the leader again,. We still want to apply this as a local modification because
470 // we have resumed leadership with that log entry having been committed.
471 final Payload payload = entry.getData();
472 if (payload instanceof IdentifiablePayload<?> identifiable) {
473 return new ApplyState(null, identifiable.getIdentifier(), entry);
476 return new ApplyState(null, null, entry);
480 protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender, final RequestVoteReply requestVoteReply) {
484 protected void beforeSendHeartbeat() {
489 public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
490 requireNonNull(sender, "sender should not be null");
492 if (appendEntriesMessageSlicer.handleMessage(message)) {
496 // If RPC request or response contains term T > currentTerm:
497 // set currentTerm = T, convert to follower (§5.1)
498 // This applies to all RPC messages and responses
499 if (message instanceof RaftRPC rpc && rpc.getTerm() > context.getTermInformation().getCurrentTerm()
500 && shouldUpdateTerm(rpc)) {
502 log.info("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
503 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
505 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
507 // This is a special case. Normally when stepping down as leader we don't process and reply to the
508 // RaftRPC as per raft. But if we're in the process of transferring leadership and we get a
509 // RequestVote, process the RequestVote before switching to Follower. This enables the requesting
510 // candidate node to be elected the leader faster and avoids us possibly timing out in the Follower
511 // state and starting a new election and grabbing leadership back before the other candidate node can
512 // start a new election due to lack of responses. This case would only occur if there isn't a majority
513 // of other nodes available that can elect the requesting candidate. Since we're transferring
514 // leadership, we should make every effort to get the requesting node elected.
515 if (rpc instanceof RequestVote requestVote && context.getRaftActorLeadershipTransferCohort() != null) {
516 log.debug("{}: Leadership transfer in progress - processing RequestVote", logName());
517 requestVote(sender, requestVote);
520 return internalSwitchBehavior(RaftState.Follower);
523 if (message instanceof SendHeartBeat) {
524 beforeSendHeartbeat();
526 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
527 } else if (message instanceof SendInstallSnapshot sendInstallSnapshot) {
528 setSnapshotHolder(new SnapshotHolder(sendInstallSnapshot.getSnapshot(),
529 sendInstallSnapshot.getSnapshotBytes()));
530 sendInstallSnapshot();
531 } else if (message instanceof Replicate replicate) {
532 replicate(replicate);
533 } else if (message instanceof InstallSnapshotReply installSnapshotReply) {
534 handleInstallSnapshotReply(installSnapshotReply);
535 } else if (message instanceof CheckConsensusReached) {
536 possiblyUpdateCommitIndex();
538 return super.handleMessage(sender, message);
544 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS",
545 justification = "JDT nullness with SpotBugs at setSnapshotHolder(null)")
546 private void handleInstallSnapshotReply(final InstallSnapshotReply reply) {
547 log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
549 String followerId = reply.getFollowerId();
550 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
551 if (followerLogInformation == null) {
552 // This can happen during AddServer if it times out.
553 log.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
554 logName(), followerId);
558 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
559 if (installSnapshotState == null) {
560 log.error("{}: LeaderInstallSnapshotState not found for follower {} in InstallSnapshotReply",
561 logName(), followerId);
565 installSnapshotState.resetChunkTimer();
566 followerLogInformation.markFollowerActive();
568 if (installSnapshotState.getChunkIndex() == reply.getChunkIndex()) {
569 boolean wasLastChunk = false;
570 if (reply.isSuccess()) {
571 if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
572 //this was the last chunk reply
574 long followerMatchIndex = snapshotHolder.get().getLastIncludedIndex();
575 followerLogInformation.setMatchIndex(followerMatchIndex);
576 followerLogInformation.setNextIndex(followerMatchIndex + 1);
577 followerLogInformation.clearLeaderInstallSnapshotState();
579 log.info("{}: Snapshot successfully installed on follower {} (last chunk {}) - "
580 + "matchIndex set to {}, nextIndex set to {}", logName(), followerId, reply.getChunkIndex(),
581 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
583 if (!anyFollowersInstallingSnapshot()) {
584 // once there are no pending followers receiving snapshots
585 // we can remove snapshot from the memory
586 setSnapshotHolder(null);
590 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
591 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
592 new UnInitializedFollowerSnapshotReply(followerId);
593 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
594 log.debug("Sent message UnInitializedFollowerSnapshotReply to self");
597 installSnapshotState.markSendStatus(true);
600 log.warn("{}: Received failed InstallSnapshotReply - will retry: {}", logName(), reply);
602 installSnapshotState.markSendStatus(false);
606 if (!context.getSnapshotManager().isCapturing()) {
607 // Since the follower is now caught up try to purge the log.
611 ActorSelection followerActor = context.getPeerActorSelection(followerId);
612 if (followerActor != null) {
613 sendSnapshotChunk(followerActor, followerLogInformation);
618 log.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
619 logName(), reply.getChunkIndex(), followerId,
620 installSnapshotState.getChunkIndex());
622 if (reply.getChunkIndex() == LeaderInstallSnapshotState.INVALID_CHUNK_INDEX) {
623 // Since the Follower did not find this index to be valid we should reset the follower snapshot
624 // so that Installing the snapshot can resume from the beginning
625 installSnapshotState.reset();
630 private boolean anyFollowersInstallingSnapshot() {
631 for (FollowerLogInformation info: followerToLog.values()) {
632 if (info.getInstallSnapshotState() != null) {
641 private void replicate(final Replicate replicate) {
642 long logIndex = replicate.getReplicatedLogEntry().getIndex();
644 log.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}, isSendImmediate: {}", logName(),
645 replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass(),
646 replicate.isSendImmediate());
648 // Create a tracker entry we will use this later to notify the
650 if (replicate.getClientActor() != null) {
651 trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
655 boolean applyModificationToState = !context.anyVotingPeers()
656 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
658 if (applyModificationToState) {
659 context.setCommitIndex(logIndex);
660 applyLogToStateMachine(logIndex);
663 if (replicate.isSendImmediate() && !followerToLog.isEmpty()) {
664 sendAppendEntries(0, false);
668 protected void sendAppendEntries(final long timeSinceLastActivityIntervalNanos, final boolean isHeartbeat) {
669 // Send an AppendEntries to all followers
670 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
671 final String followerId = e.getKey();
672 final FollowerLogInformation followerLogInformation = e.getValue();
673 // This checks helps not to send a repeat message to the follower
674 if (!followerLogInformation.isFollowerActive()
675 || followerLogInformation.nanosSinceLastActivity() >= timeSinceLastActivityIntervalNanos) {
676 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
682 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
683 * sending next snapshot chunk, and initiating a snapshot.
685 private void sendUpdatesToFollower(final String followerId, final FollowerLogInformation followerLogInformation,
686 final boolean sendHeartbeat, final boolean isHeartbeat) {
688 ActorSelection followerActor = context.getPeerActorSelection(followerId);
689 if (followerActor != null) {
690 long followerNextIndex = followerLogInformation.getNextIndex();
691 boolean isFollowerActive = followerLogInformation.isFollowerActive();
692 boolean sendAppendEntries = false;
693 List<ReplicatedLogEntry> entries = Collections.emptyList();
695 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
696 if (installSnapshotState != null) {
698 // if install snapshot is in process , then sent next chunk if possible
699 if (isFollowerActive) {
700 // 30 seconds with default settings, can be modified via heartbeat or election timeout factor
701 FiniteDuration snapshotReplyTimeout = context.getConfigParams().getHeartBeatInterval()
702 .$times(context.getConfigParams().getElectionTimeoutFactor() * 3);
704 if (installSnapshotState.isChunkTimedOut(snapshotReplyTimeout)) {
705 sendAppendEntries = !resendSnapshotChunk(followerActor, followerLogInformation);
706 } else if (installSnapshotState.canSendNextChunk()) {
707 sendSnapshotChunk(followerActor, followerLogInformation);
709 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
710 // we send a heartbeat even if we have not received a reply for the last chunk
711 sendAppendEntries = true;
713 } else if (followerLogInformation.isLogEntrySlicingInProgress()) {
714 sendAppendEntries = sendHeartbeat;
716 long leaderLastIndex = context.getReplicatedLog().lastIndex();
717 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
719 if (!isHeartbeat && log.isDebugEnabled() || log.isTraceEnabled()) {
720 log.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, "
721 + "leaderLastIndex: {}, leaderSnapShotIndex: {}", logName(), followerId, isFollowerActive,
722 followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
725 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
727 log.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
728 followerNextIndex, followerId);
730 if (followerLogInformation.okToReplicate(context.getCommitIndex())) {
731 entries = getEntriesToSend(followerLogInformation, followerActor);
732 sendAppendEntries = true;
734 } else if (isFollowerActive && followerNextIndex >= 0
735 && leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
736 // if the followers next index is not present in the leaders log, and
737 // if the follower is just not starting and if leader's index is more than followers index
738 // then snapshot should be sent
740 // Send heartbeat to follower whenever install snapshot is initiated.
741 sendAppendEntries = true;
742 if (canInstallSnapshot(followerNextIndex)) {
743 log.info("{}: Initiating install snapshot to follower {}: follower nextIndex: {}, leader "
744 + "snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(), followerId,
745 followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
746 context.getReplicatedLog().size());
748 initiateCaptureSnapshot(followerId);
750 // It doesn't seem like we should ever reach here - most likely indicates sonething is
752 log.info("{}: Follower {} is behind but cannot install snapshot: follower nextIndex: {}, "
753 + "leader snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(),
754 followerId, followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
755 context.getReplicatedLog().size());
758 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
759 // we send an AppendEntries, even if the follower is inactive
760 // in-order to update the followers timestamp, in case it becomes active again
761 sendAppendEntries = true;
766 if (sendAppendEntries) {
767 sendAppendEntriesToFollower(followerActor, entries, followerLogInformation);
772 private List<ReplicatedLogEntry> getEntriesToSend(final FollowerLogInformation followerLogInfo,
773 final ActorSelection followerActor) {
774 // Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
776 int maxEntries = (int) context.getReplicatedLog().size();
777 final int maxDataSize = context.getConfigParams().getSnapshotChunkSize();
778 final long followerNextIndex = followerLogInfo.getNextIndex();
779 List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex,
780 maxEntries, maxDataSize);
782 // If the first entry's size exceeds the max data size threshold, it will be returned from the call above. If
783 // that is the case, then we need to slice it into smaller chunks.
784 if (entries.size() != 1 || entries.get(0).getData().serializedSize() <= maxDataSize) {
785 // Don't need to slice.
789 log.debug("{}: Log entry size {} exceeds max payload size {}", logName(), entries.get(0).getData().size(),
792 // If an AppendEntries has already been serialized for the log index then reuse the
793 // SharedFileBackedOutputStream.
794 final Long logIndex = entries.get(0).getIndex();
795 SharedFileBackedOutputStream fileBackedStream = sharedSerializedAppendEntriesStreams.get(logIndex);
796 if (fileBackedStream == null) {
797 fileBackedStream = context.getFileBackedOutputStreamFactory().newSharedInstance();
799 final AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
800 getLogEntryIndex(followerNextIndex - 1), getLogEntryTerm(followerNextIndex - 1), entries,
801 context.getCommitIndex(), getReplicatedToAllIndex(), context.getPayloadVersion());
803 log.debug("{}: Serializing {} for slicing for follower {}", logName(), appendEntries,
804 followerLogInfo.getId());
806 try (ObjectOutputStream out = new ObjectOutputStream(fileBackedStream)) {
807 out.writeObject(appendEntries);
808 } catch (IOException e) {
809 log.error("{}: Error serializing {}", logName(), appendEntries, e);
810 fileBackedStream.cleanup();
811 return Collections.emptyList();
814 sharedSerializedAppendEntriesStreams.put(logIndex, fileBackedStream);
816 fileBackedStream.setOnCleanupCallback(index -> {
817 log.debug("{}: On SharedFileBackedOutputStream cleanup for index {}", logName(), index);
818 sharedSerializedAppendEntriesStreams.remove(index);
821 log.debug("{}: Reusing SharedFileBackedOutputStream for follower {}", logName(), followerLogInfo.getId());
822 fileBackedStream.incrementUsageCount();
825 log.debug("{}: Slicing stream for index {}, follower {}", logName(), logIndex, followerLogInfo.getId());
827 // Record that slicing is in progress for the follower.
828 followerLogInfo.setSlicedLogEntryIndex(logIndex);
830 final FollowerIdentifier identifier = new FollowerIdentifier(followerLogInfo.getId());
831 appendEntriesMessageSlicer.slice(SliceOptions.builder().identifier(identifier)
832 .fileBackedOutputStream(fileBackedStream).sendTo(followerActor).replyTo(actor())
833 .onFailureCallback(failure -> {
834 log.error("{}: Error slicing AppendEntries for follower {}", logName(),
835 followerLogInfo.getId(), failure);
836 followerLogInfo.setSlicedLogEntryIndex(FollowerLogInformation.NO_INDEX);
839 return Collections.emptyList();
842 private void sendAppendEntriesToFollower(final ActorSelection followerActor, final List<ReplicatedLogEntry> entries,
843 final FollowerLogInformation followerLogInformation) {
844 // In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
845 // possibly committing and applying conflicting entries (those with same index, different term) from a prior
846 // term that weren't replicated to a majority, which would be a violation of raft.
847 // - if the follower isn't active. In this case we don't know the state of the follower and we send an
848 // empty AppendEntries as a heart beat to prevent election.
849 // - if we're in the process of installing a snapshot. In this case we don't send any new entries but still
850 // need to send AppendEntries to prevent election.
851 // - if we're in the process of slicing an AppendEntries with a large log entry payload. In this case we
852 // need to send an empty AppendEntries to prevent election.
853 boolean isInstallingSnaphot = followerLogInformation.getInstallSnapshotState() != null;
854 long leaderCommitIndex = isInstallingSnaphot || followerLogInformation.isLogEntrySlicingInProgress()
855 || !followerLogInformation.isFollowerActive() ? -1 : context.getCommitIndex();
857 long followerNextIndex = followerLogInformation.getNextIndex();
858 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
859 getLogEntryIndex(followerNextIndex - 1),
860 getLogEntryTerm(followerNextIndex - 1), entries,
861 leaderCommitIndex, super.getReplicatedToAllIndex(), context.getPayloadVersion(),
862 followerLogInformation.getRaftVersion(), followerLogInformation.needsLeaderAddress(getId()));
864 if (!entries.isEmpty() || log.isTraceEnabled()) {
865 log.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerLogInformation.getId(),
869 followerLogInformation.setSentCommitIndex(leaderCommitIndex);
870 followerActor.tell(appendEntries, actor());
874 * Initiates a snapshot capture to install on a follower.
877 * Install Snapshot works as follows
878 * 1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
879 * 2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
880 * the Leader's handleMessage with a SendInstallSnapshot message.
881 * 3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
882 * the Follower via InstallSnapshot messages.
883 * 4. For each chunk, the Follower sends back an InstallSnapshotReply.
884 * 5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
886 * 6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
887 * then send the existing snapshot in chunks to the follower.
889 * @param followerId the id of the follower.
890 * @return true if capture was initiated, false otherwise.
892 public boolean initiateCaptureSnapshot(final String followerId) {
893 FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
894 if (snapshotHolder.isPresent()) {
895 // If a snapshot is present in the memory, most likely another install is in progress no need to capture
896 // snapshot. This could happen if another follower needs an install when one is going on.
897 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
899 // Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
900 sendSnapshotChunk(followerActor, followerLogInfo);
904 boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
905 getReplicatedToAllIndex(), followerId);
906 if (captureInitiated) {
907 followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
908 context.getConfigParams().getSnapshotChunkSize(), logName()));
911 return captureInitiated;
914 private boolean canInstallSnapshot(final long nextIndex) {
915 // If the follower's nextIndex is -1 then we might as well send it a snapshot
916 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
918 return nextIndex == -1 || !context.getReplicatedLog().isPresent(nextIndex)
919 && context.getReplicatedLog().isInSnapshot(nextIndex);
924 private void sendInstallSnapshot() {
925 log.debug("{}: sendInstallSnapshot", logName());
926 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
927 String followerId = e.getKey();
928 ActorSelection followerActor = context.getPeerActorSelection(followerId);
929 FollowerLogInformation followerLogInfo = e.getValue();
931 if (followerActor != null) {
932 long nextIndex = followerLogInfo.getNextIndex();
933 if (followerLogInfo.getInstallSnapshotState() != null
934 || context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
935 || canInstallSnapshot(nextIndex)) {
936 sendSnapshotChunk(followerActor, followerLogInfo);
943 * Sends a snapshot chunk to a given follower
944 * InstallSnapshot should qualify as a heartbeat too.
946 private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) {
947 if (snapshotHolder.isPresent()) {
948 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
949 if (installSnapshotState == null) {
950 installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
952 followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
956 // Ensure the snapshot bytes are set - this is a no-op.
957 installSnapshotState.setSnapshotBytes(snapshotHolder.get().getSnapshotBytes());
959 if (!installSnapshotState.canSendNextChunk()) {
963 byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();
965 log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
966 nextSnapshotChunk.length);
968 int nextChunkIndex = installSnapshotState.incrementChunkIndex();
969 Optional<ServerConfigurationPayload> serverConfig = Optional.empty();
970 if (installSnapshotState.isLastChunk(nextChunkIndex)) {
971 serverConfig = Optional.ofNullable(context.getPeerServerInfo(true));
974 sendSnapshotChunk(followerActor, followerLogInfo, nextSnapshotChunk, nextChunkIndex, serverConfig);
976 log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
977 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
979 } catch (IOException e) {
980 log.warn("{}: Unable to send chunk: {}/{}. Reseting snapshot progress. Snapshot state: {}", logName(),
981 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks(),
982 installSnapshotState, e);
983 installSnapshotState.reset();
988 private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo,
989 final byte[] snapshotChunk, final int chunkIndex,
990 final Optional<ServerConfigurationPayload> serverConfig) {
991 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
993 installSnapshotState.startChunkTimer();
995 new InstallSnapshot(currentTerm(), context.getId(),
996 snapshotHolder.get().getLastIncludedIndex(),
997 snapshotHolder.get().getLastIncludedTerm(),
1000 installSnapshotState.getTotalChunks(),
1001 OptionalInt.of(installSnapshotState.getLastChunkHashCode()),
1003 followerLogInfo.getRaftVersion()),
1008 private boolean resendSnapshotChunk(final ActorSelection followerActor,
1009 final FollowerLogInformation followerLogInfo) {
1010 if (!snapshotHolder.isPresent()) {
1011 // Seems like we should never hit this case, but just in case we do, reset the snapshot progress so that it
1012 // can restart from the next AppendEntries.
1013 log.warn("{}: Attempting to resend snapshot with no snapshot holder present.", logName());
1014 followerLogInfo.clearLeaderInstallSnapshotState();
1018 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
1019 // we are resending, timer needs to be reset
1020 installSnapshotState.resetChunkTimer();
1021 installSnapshotState.markSendStatus(false);
1023 sendSnapshotChunk(followerActor, followerLogInfo);
1028 private void sendHeartBeat() {
1029 if (!followerToLog.isEmpty()) {
1030 log.trace("{}: Sending heartbeat", logName());
1031 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toNanos(), true);
1033 appendEntriesMessageSlicer.checkExpiredSlicedMessageState();
1037 private void stopHeartBeat() {
1038 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
1039 heartbeatSchedule.cancel();
1043 private void scheduleHeartBeat(final FiniteDuration interval) {
1044 if (followerToLog.isEmpty()) {
1045 // Optimization - do not bother scheduling a heartbeat as there are
1052 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
1053 // message is sent to itself.
1054 // Scheduling the heartbeat only once here because heartbeats do not
1055 // need to be sent if there are other messages being sent to the remote
1057 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
1058 interval, context.getActor(), SendHeartBeat.INSTANCE,
1059 context.getActorSystem().dispatcher(), context.getActor());
1063 public void close() {
1065 appendEntriesMessageSlicer.close();
1069 public final String getLeaderId() {
1070 return context.getId();
1074 public final short getLeaderPayloadVersion() {
1075 return context.getPayloadVersion();
1078 protected boolean isLeaderIsolated() {
1079 int minPresent = getMinIsolatedLeaderPeerCount();
1080 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1081 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
1082 if (peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
1084 if (minPresent == 0) {
1089 return minPresent != 0;
1092 // called from example-actor for printing the follower-states
1093 public String printFollowerStates() {
1094 final StringBuilder sb = new StringBuilder();
1097 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1099 sb.append(followerLogInformation.getId());
1100 sb.append(" state:");
1101 sb.append(followerLogInformation.isFollowerActive());
1106 return sb.toString();
1110 public FollowerLogInformation getFollower(final String followerId) {
1111 return followerToLog.get(followerId);
1115 public int followerLogSize() {
1116 return followerToLog.size();
1119 static class SnapshotHolder {
1120 private final long lastIncludedTerm;
1121 private final long lastIncludedIndex;
1122 private final ByteSource snapshotBytes;
1124 SnapshotHolder(final Snapshot snapshot, final ByteSource snapshotBytes) {
1125 lastIncludedTerm = snapshot.getLastAppliedTerm();
1126 lastIncludedIndex = snapshot.getLastAppliedIndex();
1127 this.snapshotBytes = snapshotBytes;
1130 long getLastIncludedTerm() {
1131 return lastIncludedTerm;
1134 long getLastIncludedIndex() {
1135 return lastIncludedIndex;
1138 ByteSource getSnapshotBytes() {
1139 return snapshotBytes;