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.LinkedList;
24 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.OptionalInt;
29 import java.util.Queue;
30 import java.util.concurrent.TimeUnit;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.controller.cluster.io.SharedFileBackedOutputStream;
33 import org.opendaylight.controller.cluster.messaging.MessageSlicer;
34 import org.opendaylight.controller.cluster.messaging.SliceOptions;
35 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
36 import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
37 import org.opendaylight.controller.cluster.raft.PeerInfo;
38 import org.opendaylight.controller.cluster.raft.RaftActorContext;
39 import org.opendaylight.controller.cluster.raft.RaftState;
40 import org.opendaylight.controller.cluster.raft.RaftVersions;
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.ApplyState;
44 import org.opendaylight.controller.cluster.raft.base.messages.CheckConsensusReached;
45 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
46 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
47 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
48 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
49 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
50 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
51 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
52 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
53 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
54 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
55 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
56 import org.opendaylight.controller.cluster.raft.messages.UnInitializedFollowerSnapshotReply;
57 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
58 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
59 import scala.concurrent.duration.FiniteDuration;
62 * The behavior of a RaftActor when it is in the Leader state.
67 * <li> Upon election: send initial empty AppendEntries RPCs
68 * (heartbeat) to each server; repeat during idle periods to
69 * prevent election timeouts (§5.2)
70 * <li> If command received from client: append entry to local log,
71 * respond after entry applied to state machine (§5.3)
72 * <li> If last log index ≥ nextIndex for a follower: send
73 * AppendEntries RPC with log entries starting at nextIndex
74 * <li> If successful: update nextIndex and matchIndex for
76 * <li> If AppendEntries fails because of log inconsistency:
77 * decrement nextIndex and retry (§5.3)
78 * <li> If there exists an N such that N > commitIndex, a majority
79 * of matchIndex[i] ≥ N, and log[N].term == currentTerm:
80 * set commitIndex = N (§5.3, §5.4).
83 public abstract class AbstractLeader extends AbstractRaftActorBehavior {
84 private final Map<String, FollowerLogInformation> followerToLog = new HashMap<>();
87 * Lookup table for request contexts based on journal index. We could use a {@link Map} here, but we really
88 * expect the entries to be modified in sequence, hence we open-code the lookup.
89 * TODO: Evaluate the use of ArrayDeque(), as that has lower memory overhead. Non-head removals are more costly,
90 * but we already expect those to be far from frequent.
92 private final Queue<ClientRequestTracker> trackers = new LinkedList<>();
95 * Map of serialized AppendEntries output streams keyed by log index. This is used in conjunction with the
96 * appendEntriesMessageSlicer for slicing single ReplicatedLogEntry payloads that exceed the message size threshold.
97 * This Map allows the SharedFileBackedOutputStreams to be reused for multiple followers.
99 private final Map<Long, SharedFileBackedOutputStream> sharedSerializedAppendEntriesStreams = new HashMap<>();
100 private final MessageSlicer appendEntriesMessageSlicer;
102 private Cancellable heartbeatSchedule = null;
103 private Optional<SnapshotHolder> snapshotHolder = Optional.empty();
104 private int minReplicationCount;
106 protected AbstractLeader(final RaftActorContext context, final RaftState state,
107 final @Nullable AbstractLeader initializeFromLeader) {
108 super(context, state);
110 appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName())
111 .messageSliceSize(context.getConfigParams().getMaximumMessageSliceSize())
112 .expireStateAfterInactivity(context.getConfigParams().getElectionTimeOutInterval().toMillis() * 3,
113 TimeUnit.MILLISECONDS).build();
115 if (initializeFromLeader != null) {
116 followerToLog.putAll(initializeFromLeader.followerToLog);
117 snapshotHolder = initializeFromLeader.snapshotHolder;
118 trackers.addAll(initializeFromLeader.trackers);
120 for (PeerInfo peerInfo: context.getPeers()) {
121 FollowerLogInformation followerLogInformation = new FollowerLogInformation(peerInfo, context);
122 followerToLog.put(peerInfo.getId(), followerLogInformation);
126 log.debug("{}: Election: Leader has following peers: {}", logName(), getFollowerIds());
128 updateMinReplicaCount();
130 // Immediately schedule a heartbeat
131 // Upon election: send initial empty AppendEntries RPCs
132 // (heartbeat) to each server; repeat during idle periods to
133 // prevent election timeouts (§5.2)
134 sendAppendEntries(0, false);
136 // It is important to schedule this heartbeat here
137 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
140 protected AbstractLeader(final RaftActorContext context, final RaftState state) {
141 this(context, state, null);
145 * Return an immutable collection of follower identifiers.
147 * @return Collection of follower IDs
149 public final Collection<String> getFollowerIds() {
150 return followerToLog.keySet();
153 public void addFollower(final String followerId) {
154 FollowerLogInformation followerLogInformation = new FollowerLogInformation(context.getPeerInfo(followerId),
156 followerToLog.put(followerId, followerLogInformation);
158 if (heartbeatSchedule == null) {
159 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
163 public void removeFollower(final String followerId) {
164 followerToLog.remove(followerId);
167 public final void updateMinReplicaCount() {
169 for (PeerInfo peer: context.getPeers()) {
170 if (peer.isVoting()) {
175 minReplicationCount = getMajorityVoteCount(numVoting);
178 protected int getMinIsolatedLeaderPeerCount() {
179 //the isolated Leader peer count will be 1 less than the majority vote count.
180 //this is because the vote count has the self vote counted in it
182 //0 peers = 1 votesRequired , minIsolatedLeaderPeerCount = 0
183 //2 peers = 2 votesRequired , minIsolatedLeaderPeerCount = 1
184 //4 peers = 3 votesRequired, minIsolatedLeaderPeerCount = 2
186 return minReplicationCount > 0 ? minReplicationCount - 1 : 0;
190 void setSnapshotHolder(final @Nullable SnapshotHolder snapshotHolder) {
191 this.snapshotHolder = Optional.ofNullable(snapshotHolder);
195 boolean hasSnapshot() {
196 return snapshotHolder.isPresent();
200 protected RaftActorBehavior handleAppendEntries(final ActorRef sender,
201 final AppendEntries appendEntries) {
203 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
209 protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
210 final AppendEntriesReply appendEntriesReply) {
211 log.trace("{}: handleAppendEntriesReply: {}", logName(), appendEntriesReply);
213 // Update the FollowerLogInformation
214 String followerId = appendEntriesReply.getFollowerId();
215 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
217 if (followerLogInformation == null) {
218 log.error("{}: handleAppendEntriesReply - unknown follower {}", logName(), followerId);
222 final var followerRaftVersion = appendEntriesReply.getRaftVersion();
223 if (followerRaftVersion < RaftVersions.FLUORINE_VERSION) {
224 log.warn("{}: handleAppendEntriesReply - ignoring reply from follower {} raft version {}", logName(),
225 followerId, followerRaftVersion);
229 final long lastActivityNanos = followerLogInformation.nanosSinceLastActivity();
230 if (lastActivityNanos > context.getConfigParams().getElectionTimeOutInterval().toNanos()) {
231 log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
232 + "appendEntriesReply : {}, timeSinceLastActivity : {}, lastApplied : {}, commitIndex : {}",
233 logName(), appendEntriesReply, TimeUnit.NANOSECONDS.toMillis(lastActivityNanos),
234 context.getLastApplied(), context.getCommitIndex());
237 followerLogInformation.markFollowerActive();
238 followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
239 followerLogInformation.setRaftVersion(followerRaftVersion);
240 followerLogInformation.setNeedsLeaderAddress(appendEntriesReply.isNeedsLeaderAddress());
242 long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
243 boolean updated = false;
244 if (appendEntriesReply.getLogLastIndex() > context.getReplicatedLog().lastIndex()) {
245 // The follower's log is actually ahead of the leader's log. Normally this doesn't happen
246 // in raft as a node cannot become leader if it's log is behind another's. However, the
247 // non-voting semantics deviate a bit from raft. Only voting members participate in
248 // elections and can become leader so it's possible for a non-voting follower to be ahead
249 // of the leader. This can happen if persistence is disabled and all voting members are
250 // restarted. In this case, the voting leader will start out with an empty log however
251 // the non-voting followers still retain the previous data in memory. On the first
252 // AppendEntries, the non-voting follower returns a successful reply b/c the prevLogIndex
253 // sent by the leader is -1 and thus the integrity checks pass. However the follower's returned
254 // lastLogIndex may be higher in which case we want to reset the follower by installing a
255 // snapshot. It's also possible that the follower's last log index is behind the leader's.
256 // However in this case the log terms won't match and the logs will conflict - this is handled
258 log.info("{}: handleAppendEntriesReply: follower {} lastIndex {} is ahead of our lastIndex {} "
259 + "(snapshotIndex {}, snapshotTerm {}) - forcing install snaphot", logName(),
260 followerLogInformation.getId(), appendEntriesReply.getLogLastIndex(),
261 context.getReplicatedLog().lastIndex(), context.getReplicatedLog().getSnapshotIndex(),
262 context.getReplicatedLog().getSnapshotTerm());
264 followerLogInformation.setMatchIndex(-1);
265 followerLogInformation.setNextIndex(-1);
267 initiateCaptureSnapshot(followerId);
270 } else if (appendEntriesReply.isSuccess()) {
271 long followersLastLogTermInLeadersLog = getLogEntryTerm(followerLastLogIndex);
272 if (followerLastLogIndex >= 0 && followersLastLogTermInLeadersLog >= 0
273 && followersLastLogTermInLeadersLog != appendEntriesReply.getLogLastTerm()) {
274 // The follower's last entry is present in the leader's journal but the terms don't match so the
275 // follower has a conflicting entry. Since the follower didn't report that it's out of sync, this means
276 // either the previous leader entry sent didn't conflict or the previous leader entry is in the snapshot
277 // and no longer in the journal. Either way, we set the follower's next index to 1 less than the last
278 // index reported by the follower. For the former case, the leader will send all entries starting with
279 // the previous follower's index and the follower will remove and replace the conflicting entries as
280 // needed. For the latter, the leader will initiate an install snapshot.
282 followerLogInformation.setNextIndex(followerLastLogIndex - 1);
285 log.info("{}: handleAppendEntriesReply: follower {} last log term {} for index {} conflicts with the "
286 + "leader's {} - set the follower's next index to {}", logName(),
287 followerId, appendEntriesReply.getLogLastTerm(), appendEntriesReply.getLogLastIndex(),
288 followersLastLogTermInLeadersLog, followerLogInformation.getNextIndex());
290 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
293 log.info("{}: handleAppendEntriesReply - received unsuccessful reply: {}, leader snapshotIndex: {}, "
294 + "snapshotTerm: {}, replicatedToAllIndex: {}", logName(), appendEntriesReply,
295 context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm(),
296 getReplicatedToAllIndex());
298 long followersLastLogTermInLeadersLogOrSnapshot = getLogEntryOrSnapshotTerm(followerLastLogIndex);
299 if (appendEntriesReply.isForceInstallSnapshot()) {
300 // Reset the followers match and next index. This is to signal that this follower has nothing
301 // in common with this Leader and so would require a snapshot to be installed
302 followerLogInformation.setMatchIndex(-1);
303 followerLogInformation.setNextIndex(-1);
305 // Force initiate a snapshot capture
306 initiateCaptureSnapshot(followerId);
307 } else if (followerLastLogIndex < 0 || followersLastLogTermInLeadersLogOrSnapshot >= 0
308 && followersLastLogTermInLeadersLogOrSnapshot == appendEntriesReply.getLogLastTerm()) {
309 // The follower's log is empty or the follower's last entry is present in the leader's journal or
310 // snapshot and the terms match so the follower is just behind the leader's journal from the last
311 // snapshot, if any. We'll catch up the follower quickly by starting at the follower's last log index.
313 updated = updateFollowerLogInformation(followerLogInformation, appendEntriesReply);
315 log.info("{}: follower {} appears to be behind the leader from the last snapshot - "
316 + "updated: matchIndex: {}, nextIndex: {}", logName(), followerId,
317 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
319 // The follower's log conflicts with leader's log so decrement follower's next index
320 // in an attempt to find where the logs match.
321 if (followerLogInformation.decrNextIndex(appendEntriesReply.getLogLastIndex())) {
324 log.info("{}: follower {} last log term {} conflicts with the leader's {} - dec next index to {}",
325 logName(), followerId, appendEntriesReply.getLogLastTerm(),
326 followersLastLogTermInLeadersLogOrSnapshot, followerLogInformation.getNextIndex());
331 if (log.isTraceEnabled()) {
332 log.trace("{}: handleAppendEntriesReply from {}: commitIndex: {}, lastAppliedIndex: {}, currentTerm: {}",
333 logName(), followerId, context.getCommitIndex(), context.getLastApplied(), currentTerm());
336 possiblyUpdateCommitIndex();
338 //Send the next log entry immediately, if possible, no need to wait for heartbeat to trigger that event
339 sendUpdatesToFollower(followerId, followerLogInformation, false, !updated);
344 private void possiblyUpdateCommitIndex() {
345 // Figure out if we can update the the commitIndex as follows:
346 // If there exists an index N such that N > commitIndex, a majority of matchIndex[i] ≥ N,
347 // and log[N].term == currentTerm:
348 // set commitIndex = N (§5.3, §5.4).
349 for (long index = context.getCommitIndex() + 1; ; index++) {
350 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(index);
351 if (replicatedLogEntry == null) {
352 log.trace("{}: ReplicatedLogEntry not found for index {} - snapshotIndex: {}, journal size: {}",
353 logName(), index, context.getReplicatedLog().getSnapshotIndex(),
354 context.getReplicatedLog().size());
358 // Count our entry if it has been persisted.
359 int replicatedCount = replicatedLogEntry.isPersistencePending() ? 0 : 1;
361 if (replicatedCount == 0) {
362 // We don't commit and apply a log entry until we've gotten the ack from our local persistence,
363 // even though there *shouldn't* be any issue with updating the commit index if we get a consensus
364 // amongst the followers w/o the local persistence ack.
368 log.trace("{}: checking Nth index {}", logName(), index);
369 for (FollowerLogInformation info : followerToLog.values()) {
370 final PeerInfo peerInfo = context.getPeerInfo(info.getId());
371 if (info.getMatchIndex() >= index && peerInfo != null && peerInfo.isVoting()) {
373 } else if (log.isTraceEnabled()) {
374 log.trace("{}: Not counting follower {} - matchIndex: {}, {}", logName(), info.getId(),
375 info.getMatchIndex(), peerInfo);
379 if (log.isTraceEnabled()) {
380 log.trace("{}: replicatedCount {}, minReplicationCount: {}", logName(), replicatedCount,
381 minReplicationCount);
384 if (replicatedCount >= minReplicationCount) {
385 // Don't update the commit index if the log entry is from a previous term, as per §5.4.1:
386 // "Raft never commits log entries from previous terms by counting replicas".
387 // However we keep looping so we can make progress when new entries in the current term
388 // reach consensus, as per §5.4.1: "once an entry from the current term is committed by
389 // counting replicas, then all prior entries are committed indirectly".
390 if (replicatedLogEntry.getTerm() == currentTerm()) {
391 log.trace("{}: Setting commit index to {}", logName(), index);
392 context.setCommitIndex(index);
394 log.debug("{}: Not updating commit index to {} - retrieved log entry with index {}, "
395 + "term {} does not match the current term {}", logName(), index,
396 replicatedLogEntry.getIndex(), replicatedLogEntry.getTerm(), currentTerm());
399 log.trace("{}: minReplicationCount not reached, actual {} - breaking", logName(), replicatedCount);
404 // Apply the change to the state machine
405 if (context.getCommitIndex() > context.getLastApplied()) {
406 log.debug("{}: Applying to log - commitIndex: {}, lastAppliedIndex: {}", logName(),
407 context.getCommitIndex(), context.getLastApplied());
409 applyLogToStateMachine(context.getCommitIndex());
412 if (!context.getSnapshotManager().isCapturing()) {
417 private boolean updateFollowerLogInformation(final FollowerLogInformation followerLogInformation,
418 final AppendEntriesReply appendEntriesReply) {
419 boolean updated = followerLogInformation.setMatchIndex(appendEntriesReply.getLogLastIndex());
420 updated = followerLogInformation.setNextIndex(appendEntriesReply.getLogLastIndex() + 1) || updated;
422 if (updated && log.isDebugEnabled()) {
424 "{}: handleAppendEntriesReply - FollowerLogInformation for {} updated: matchIndex: {}, nextIndex: {}",
425 logName(), followerLogInformation.getId(), followerLogInformation.getMatchIndex(),
426 followerLogInformation.getNextIndex());
431 private void purgeInMemoryLog() {
432 //find the lowest index across followers which has been replicated to all.
433 // lastApplied if there are no followers, so that we keep clearing the log for single-node
434 // we would delete the in-mem log from that index on, in-order to minimize mem usage
435 // we would also share this info thru AE with the followers so that they can delete their log entries as well.
436 long minReplicatedToAllIndex = followerToLog.isEmpty() ? context.getLastApplied() : Long.MAX_VALUE;
437 for (FollowerLogInformation info : followerToLog.values()) {
438 minReplicatedToAllIndex = Math.min(minReplicatedToAllIndex, info.getMatchIndex());
441 super.performSnapshotWithoutCapture(minReplicatedToAllIndex);
445 * Removes and returns the ClientRequestTracker for the specified log index.
446 * @param logIndex the log index
447 * @return the ClientRequestTracker or null if none available
449 private ClientRequestTracker removeClientRequestTracker(final long logIndex) {
450 final var it = trackers.iterator();
451 while (it.hasNext()) {
452 final var tracker = it.next();
453 if (tracker.logIndex() == logIndex) {
462 final ApplyState getApplyStateFor(final ReplicatedLogEntry entry) {
463 // first check whether a ClientRequestTracker exists for this entry.
464 // If it does that means the leader wasn't dropped before the transaction applied.
465 // That means that this transaction can be safely applied as a local transaction since we
466 // have the ClientRequestTracker.
467 final var tracker = removeClientRequestTracker(entry.getIndex());
468 if (tracker != null) {
469 return new ApplyState(tracker.clientActor(), tracker.identifier(), entry);
472 // Tracker is missing, this means that we switched behaviours between replicate and applystate
473 // and became the leader again,. We still want to apply this as a local modification because
474 // we have resumed leadership with that log entry having been committed.
475 if (entry.getData() instanceof IdentifiablePayload<?> identifiable) {
476 return new ApplyState(null, identifiable.getIdentifier(), entry);
479 return new ApplyState(null, null, entry);
483 protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender, final RequestVoteReply requestVoteReply) {
487 protected void beforeSendHeartbeat() {
492 public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
493 requireNonNull(sender, "sender should not be null");
495 if (appendEntriesMessageSlicer.handleMessage(message)) {
499 // If RPC request or response contains term T > currentTerm:
500 // set currentTerm = T, convert to follower (§5.1)
501 // This applies to all RPC messages and responses
502 if (message instanceof RaftRPC rpc && rpc.getTerm() > context.getTermInformation().getCurrentTerm()
503 && shouldUpdateTerm(rpc)) {
505 log.info("{}: Term {} in \"{}\" message is greater than leader's term {} - switching to Follower",
506 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
508 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
510 // This is a special case. Normally when stepping down as leader we don't process and reply to the
511 // RaftRPC as per raft. But if we're in the process of transferring leadership and we get a
512 // RequestVote, process the RequestVote before switching to Follower. This enables the requesting
513 // candidate node to be elected the leader faster and avoids us possibly timing out in the Follower
514 // state and starting a new election and grabbing leadership back before the other candidate node can
515 // start a new election due to lack of responses. This case would only occur if there isn't a majority
516 // of other nodes available that can elect the requesting candidate. Since we're transferring
517 // leadership, we should make every effort to get the requesting node elected.
518 if (rpc instanceof RequestVote requestVote && context.getRaftActorLeadershipTransferCohort() != null) {
519 log.debug("{}: Leadership transfer in progress - processing RequestVote", logName());
520 requestVote(sender, requestVote);
523 return internalSwitchBehavior(RaftState.Follower);
526 if (message instanceof SendHeartBeat) {
527 beforeSendHeartbeat();
529 scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
530 } else if (message instanceof SendInstallSnapshot sendInstallSnapshot) {
531 setSnapshotHolder(new SnapshotHolder(sendInstallSnapshot.getSnapshot(),
532 sendInstallSnapshot.getSnapshotBytes()));
533 sendInstallSnapshot();
534 } else if (message instanceof Replicate replicate) {
535 replicate(replicate);
536 } else if (message instanceof InstallSnapshotReply installSnapshotReply) {
537 handleInstallSnapshotReply(installSnapshotReply);
538 } else if (message instanceof CheckConsensusReached) {
539 possiblyUpdateCommitIndex();
541 return super.handleMessage(sender, message);
547 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS",
548 justification = "JDT nullness with SpotBugs at setSnapshotHolder(null)")
549 private void handleInstallSnapshotReply(final InstallSnapshotReply reply) {
550 log.debug("{}: handleInstallSnapshotReply: {}", logName(), reply);
552 String followerId = reply.getFollowerId();
553 FollowerLogInformation followerLogInformation = followerToLog.get(followerId);
554 if (followerLogInformation == null) {
555 // This can happen during AddServer if it times out.
556 log.error("{}: FollowerLogInformation not found for follower {} in InstallSnapshotReply",
557 logName(), followerId);
561 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
562 if (installSnapshotState == null) {
563 log.error("{}: LeaderInstallSnapshotState not found for follower {} in InstallSnapshotReply",
564 logName(), followerId);
568 installSnapshotState.resetChunkTimer();
569 followerLogInformation.markFollowerActive();
571 if (installSnapshotState.getChunkIndex() == reply.getChunkIndex()) {
572 boolean wasLastChunk = false;
573 if (reply.isSuccess()) {
574 if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
575 //this was the last chunk reply
577 long followerMatchIndex = snapshotHolder.orElseThrow().getLastIncludedIndex();
578 followerLogInformation.setMatchIndex(followerMatchIndex);
579 followerLogInformation.setNextIndex(followerMatchIndex + 1);
580 followerLogInformation.clearLeaderInstallSnapshotState();
582 log.info("{}: Snapshot successfully installed on follower {} (last chunk {}) - "
583 + "matchIndex set to {}, nextIndex set to {}", logName(), followerId, reply.getChunkIndex(),
584 followerLogInformation.getMatchIndex(), followerLogInformation.getNextIndex());
586 if (!anyFollowersInstallingSnapshot()) {
587 // once there are no pending followers receiving snapshots
588 // we can remove snapshot from the memory
589 setSnapshotHolder(null);
593 if (context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED) {
594 UnInitializedFollowerSnapshotReply unInitFollowerSnapshotSuccess =
595 new UnInitializedFollowerSnapshotReply(followerId);
596 context.getActor().tell(unInitFollowerSnapshotSuccess, context.getActor());
597 log.debug("Sent message UnInitializedFollowerSnapshotReply to self");
600 installSnapshotState.markSendStatus(true);
603 log.warn("{}: Received failed InstallSnapshotReply - will retry: {}", logName(), reply);
605 installSnapshotState.markSendStatus(false);
609 if (!context.getSnapshotManager().isCapturing()) {
610 // Since the follower is now caught up try to purge the log.
614 ActorSelection followerActor = context.getPeerActorSelection(followerId);
615 if (followerActor != null) {
616 sendSnapshotChunk(followerActor, followerLogInformation);
621 log.error("{}: Chunk index {} in InstallSnapshotReply from follower {} does not match expected index {}",
622 logName(), reply.getChunkIndex(), followerId,
623 installSnapshotState.getChunkIndex());
625 if (reply.getChunkIndex() == LeaderInstallSnapshotState.INVALID_CHUNK_INDEX) {
626 // Since the Follower did not find this index to be valid we should reset the follower snapshot
627 // so that Installing the snapshot can resume from the beginning
628 installSnapshotState.reset();
633 private boolean anyFollowersInstallingSnapshot() {
634 for (FollowerLogInformation info: followerToLog.values()) {
635 if (info.getInstallSnapshotState() != null) {
644 private void replicate(final Replicate replicate) {
645 final long logIndex = replicate.logIndex();
647 log.debug("{}: Replicate message: identifier: {}, logIndex: {}, isSendImmediate: {}", logName(),
648 replicate.identifier(), logIndex, replicate.sendImmediate());
650 // Create a tracker entry we will use this later to notify the
652 final var clientActor = replicate.clientActor();
653 if (clientActor != null) {
654 trackers.add(new ClientRequestTracker(logIndex, clientActor, replicate.identifier()));
657 boolean applyModificationToState = !context.anyVotingPeers()
658 || context.getRaftPolicy().applyModificationToStateBeforeConsensus();
660 if (applyModificationToState) {
661 context.setCommitIndex(logIndex);
662 applyLogToStateMachine(logIndex);
665 if (replicate.sendImmediate() && !followerToLog.isEmpty()) {
666 sendAppendEntries(0, false);
670 protected void sendAppendEntries(final long timeSinceLastActivityIntervalNanos, final boolean isHeartbeat) {
671 // Send an AppendEntries to all followers
672 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
673 final String followerId = e.getKey();
674 final FollowerLogInformation followerLogInformation = e.getValue();
675 // This checks helps not to send a repeat message to the follower
676 if (!followerLogInformation.isFollowerActive()
677 || followerLogInformation.nanosSinceLastActivity() >= timeSinceLastActivityIntervalNanos) {
678 sendUpdatesToFollower(followerId, followerLogInformation, true, isHeartbeat);
684 * This method checks if any update needs to be sent to the given follower. This includes append log entries,
685 * sending next snapshot chunk, and initiating a snapshot.
687 private void sendUpdatesToFollower(final String followerId, final FollowerLogInformation followerLogInformation,
688 final boolean sendHeartbeat, final boolean isHeartbeat) {
690 ActorSelection followerActor = context.getPeerActorSelection(followerId);
691 if (followerActor != null) {
692 long followerNextIndex = followerLogInformation.getNextIndex();
693 boolean isFollowerActive = followerLogInformation.isFollowerActive();
694 boolean sendAppendEntries = false;
695 List<ReplicatedLogEntry> entries = Collections.emptyList();
697 LeaderInstallSnapshotState installSnapshotState = followerLogInformation.getInstallSnapshotState();
698 if (installSnapshotState != null) {
700 // if install snapshot is in process , then sent next chunk if possible
701 if (isFollowerActive) {
702 // 30 seconds with default settings, can be modified via heartbeat or election timeout factor
703 FiniteDuration snapshotReplyTimeout = context.getConfigParams().getHeartBeatInterval()
704 .$times(context.getConfigParams().getElectionTimeoutFactor() * 3);
706 if (installSnapshotState.isChunkTimedOut(snapshotReplyTimeout)) {
707 sendAppendEntries = !resendSnapshotChunk(followerActor, followerLogInformation);
708 } else if (installSnapshotState.canSendNextChunk()) {
709 sendSnapshotChunk(followerActor, followerLogInformation);
711 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
712 // we send a heartbeat even if we have not received a reply for the last chunk
713 sendAppendEntries = true;
715 } else if (followerLogInformation.isLogEntrySlicingInProgress()) {
716 sendAppendEntries = sendHeartbeat;
718 long leaderLastIndex = context.getReplicatedLog().lastIndex();
719 long leaderSnapShotIndex = context.getReplicatedLog().getSnapshotIndex();
721 if (!isHeartbeat && log.isDebugEnabled() || log.isTraceEnabled()) {
722 log.debug("{}: Checking sendAppendEntries for follower {}: active: {}, followerNextIndex: {}, "
723 + "leaderLastIndex: {}, leaderSnapShotIndex: {}", logName(), followerId, isFollowerActive,
724 followerNextIndex, leaderLastIndex, leaderSnapShotIndex);
727 if (isFollowerActive && context.getReplicatedLog().isPresent(followerNextIndex)) {
729 log.debug("{}: sendAppendEntries: {} is present for follower {}", logName(),
730 followerNextIndex, followerId);
732 if (followerLogInformation.okToReplicate(context.getCommitIndex())) {
733 entries = getEntriesToSend(followerLogInformation, followerActor);
734 sendAppendEntries = true;
736 } else if (isFollowerActive && followerNextIndex >= 0
737 && leaderLastIndex > followerNextIndex && !context.getSnapshotManager().isCapturing()) {
738 // if the followers next index is not present in the leaders log, and
739 // if the follower is just not starting and if leader's index is more than followers index
740 // then snapshot should be sent
742 // Send heartbeat to follower whenever install snapshot is initiated.
743 sendAppendEntries = true;
744 if (canInstallSnapshot(followerNextIndex)) {
745 log.info("{}: Initiating install snapshot to follower {}: follower nextIndex: {}, leader "
746 + "snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(), followerId,
747 followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
748 context.getReplicatedLog().size());
750 initiateCaptureSnapshot(followerId);
752 // It doesn't seem like we should ever reach here - most likely indicates sonething is
754 log.info("{}: Follower {} is behind but cannot install snapshot: follower nextIndex: {}, "
755 + "leader snapshotIndex: {}, leader lastIndex: {}, leader log size: {}", logName(),
756 followerId, followerNextIndex, leaderSnapShotIndex, leaderLastIndex,
757 context.getReplicatedLog().size());
760 } else if (sendHeartbeat || followerLogInformation.hasStaleCommitIndex(context.getCommitIndex())) {
761 // we send an AppendEntries, even if the follower is inactive
762 // in-order to update the followers timestamp, in case it becomes active again
763 sendAppendEntries = true;
768 if (sendAppendEntries) {
769 sendAppendEntriesToFollower(followerActor, entries, followerLogInformation);
774 private List<ReplicatedLogEntry> getEntriesToSend(final FollowerLogInformation followerLogInfo,
775 final ActorSelection followerActor) {
776 // Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
778 int maxEntries = (int) context.getReplicatedLog().size();
779 final int maxDataSize = context.getConfigParams().getMaximumMessageSliceSize();
780 final long followerNextIndex = followerLogInfo.getNextIndex();
781 List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex,
782 maxEntries, maxDataSize);
784 // If the first entry's size exceeds the max data size threshold, it will be returned from the call above. If
785 // that is the case, then we need to slice it into smaller chunks.
786 if (entries.size() != 1 || entries.get(0).getData().serializedSize() <= maxDataSize) {
787 // Don't need to slice.
791 log.debug("{}: Log entry size {} exceeds max payload size {}", logName(), entries.get(0).getData().size(),
794 // If an AppendEntries has already been serialized for the log index then reuse the
795 // SharedFileBackedOutputStream.
796 final Long logIndex = entries.get(0).getIndex();
797 SharedFileBackedOutputStream fileBackedStream = sharedSerializedAppendEntriesStreams.get(logIndex);
798 if (fileBackedStream == null) {
799 fileBackedStream = context.getFileBackedOutputStreamFactory().newSharedInstance();
801 final AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
802 getLogEntryIndex(followerNextIndex - 1), getLogEntryTerm(followerNextIndex - 1), entries,
803 context.getCommitIndex(), getReplicatedToAllIndex(), context.getPayloadVersion());
805 log.debug("{}: Serializing {} for slicing for follower {}", logName(), appendEntries,
806 followerLogInfo.getId());
808 try (ObjectOutputStream out = new ObjectOutputStream(fileBackedStream)) {
809 out.writeObject(appendEntries);
810 } catch (IOException e) {
811 log.error("{}: Error serializing {}", logName(), appendEntries, e);
812 fileBackedStream.cleanup();
813 return Collections.emptyList();
816 sharedSerializedAppendEntriesStreams.put(logIndex, fileBackedStream);
818 fileBackedStream.setOnCleanupCallback(index -> {
819 log.debug("{}: On SharedFileBackedOutputStream cleanup for index {}", logName(), index);
820 sharedSerializedAppendEntriesStreams.remove(index);
823 log.debug("{}: Reusing SharedFileBackedOutputStream for follower {}", logName(), followerLogInfo.getId());
824 fileBackedStream.incrementUsageCount();
827 log.debug("{}: Slicing stream for index {}, follower {}", logName(), logIndex, followerLogInfo.getId());
829 // Record that slicing is in progress for the follower.
830 followerLogInfo.setSlicedLogEntryIndex(logIndex);
832 final FollowerIdentifier identifier = new FollowerIdentifier(followerLogInfo.getId());
833 appendEntriesMessageSlicer.slice(SliceOptions.builder().identifier(identifier)
834 .fileBackedOutputStream(fileBackedStream).sendTo(followerActor).replyTo(actor())
835 .onFailureCallback(failure -> {
836 log.error("{}: Error slicing AppendEntries for follower {}", logName(),
837 followerLogInfo.getId(), failure);
838 followerLogInfo.setSlicedLogEntryIndex(FollowerLogInformation.NO_INDEX);
841 return Collections.emptyList();
844 private void sendAppendEntriesToFollower(final ActorSelection followerActor, final List<ReplicatedLogEntry> entries,
845 final FollowerLogInformation followerLogInformation) {
846 // In certain cases outlined below we don't want to send the actual commit index to prevent the follower from
847 // possibly committing and applying conflicting entries (those with same index, different term) from a prior
848 // term that weren't replicated to a majority, which would be a violation of raft.
849 // - if the follower isn't active. In this case we don't know the state of the follower and we send an
850 // empty AppendEntries as a heart beat to prevent election.
851 // - if we're in the process of installing a snapshot. In this case we don't send any new entries but still
852 // need to send AppendEntries to prevent election.
853 // - if we're in the process of slicing an AppendEntries with a large log entry payload. In this case we
854 // need to send an empty AppendEntries to prevent election.
855 boolean isInstallingSnaphot = followerLogInformation.getInstallSnapshotState() != null;
856 long leaderCommitIndex = isInstallingSnaphot || followerLogInformation.isLogEntrySlicingInProgress()
857 || !followerLogInformation.isFollowerActive() ? -1 : context.getCommitIndex();
859 long followerNextIndex = followerLogInformation.getNextIndex();
860 AppendEntries appendEntries = new AppendEntries(currentTerm(), context.getId(),
861 getLogEntryIndex(followerNextIndex - 1),
862 getLogEntryTerm(followerNextIndex - 1), entries,
863 leaderCommitIndex, super.getReplicatedToAllIndex(), context.getPayloadVersion(),
864 followerLogInformation.getRaftVersion(), followerLogInformation.needsLeaderAddress(getId()));
866 if (!entries.isEmpty() || log.isTraceEnabled()) {
867 log.debug("{}: Sending AppendEntries to follower {}: {}", logName(), followerLogInformation.getId(),
871 followerLogInformation.setSentCommitIndex(leaderCommitIndex);
872 followerActor.tell(appendEntries, actor());
876 * Initiates a snapshot capture to install on a follower.
879 * Install Snapshot works as follows
880 * 1. Leader initiates the capture snapshot by calling createSnapshot on the RaftActor.
881 * 2. On receipt of the CaptureSnapshotReply message, the RaftActor persists the snapshot and makes a call to
882 * the Leader's handleMessage with a SendInstallSnapshot message.
883 * 3. The Leader obtains and stores the Snapshot from the SendInstallSnapshot message and sends it in chunks to
884 * the Follower via InstallSnapshot messages.
885 * 4. For each chunk, the Follower sends back an InstallSnapshotReply.
886 * 5. On receipt of the InstallSnapshotReply for the last chunk, the Leader marks the install complete for that
888 * 6. If another follower requires a snapshot and a snapshot has been collected (via SendInstallSnapshot)
889 * then send the existing snapshot in chunks to the follower.
891 * @param followerId the id of the follower.
892 * @return true if capture was initiated, false otherwise.
894 public boolean initiateCaptureSnapshot(final String followerId) {
895 FollowerLogInformation followerLogInfo = followerToLog.get(followerId);
896 if (snapshotHolder.isPresent()) {
897 // If a snapshot is present in the memory, most likely another install is in progress no need to capture
898 // snapshot. This could happen if another follower needs an install when one is going on.
899 final ActorSelection followerActor = context.getPeerActorSelection(followerId);
901 // Note: sendSnapshotChunk will set the LeaderInstallSnapshotState.
902 sendSnapshotChunk(followerActor, followerLogInfo);
906 boolean captureInitiated = context.getSnapshotManager().captureToInstall(context.getReplicatedLog().last(),
907 getReplicatedToAllIndex(), followerId);
908 if (captureInitiated) {
909 followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
910 context.getConfigParams().getMaximumMessageSliceSize(), logName()));
913 return captureInitiated;
916 private boolean canInstallSnapshot(final long nextIndex) {
917 // If the follower's nextIndex is -1 then we might as well send it a snapshot
918 // Otherwise send it a snapshot only if the nextIndex is not present in the log but is present
920 return nextIndex == -1 || !context.getReplicatedLog().isPresent(nextIndex)
921 && context.getReplicatedLog().isInSnapshot(nextIndex);
926 private void sendInstallSnapshot() {
927 log.debug("{}: sendInstallSnapshot", logName());
928 for (Entry<String, FollowerLogInformation> e : followerToLog.entrySet()) {
929 String followerId = e.getKey();
930 ActorSelection followerActor = context.getPeerActorSelection(followerId);
931 FollowerLogInformation followerLogInfo = e.getValue();
933 if (followerActor != null) {
934 long nextIndex = followerLogInfo.getNextIndex();
935 if (followerLogInfo.getInstallSnapshotState() != null
936 || context.getPeerInfo(followerId).getVotingState() == VotingState.VOTING_NOT_INITIALIZED
937 || canInstallSnapshot(nextIndex)) {
938 sendSnapshotChunk(followerActor, followerLogInfo);
945 * Sends a snapshot chunk to a given follower
946 * InstallSnapshot should qualify as a heartbeat too.
948 private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) {
949 if (snapshotHolder.isPresent()) {
950 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
951 if (installSnapshotState == null) {
952 installSnapshotState = new LeaderInstallSnapshotState(
953 context.getConfigParams().getMaximumMessageSliceSize(), logName());
954 followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
958 // Ensure the snapshot bytes are set - this is a no-op.
959 installSnapshotState.setSnapshotBytes(snapshotHolder.orElseThrow().getSnapshotBytes());
961 if (!installSnapshotState.canSendNextChunk()) {
965 byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();
967 log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
968 nextSnapshotChunk.length);
970 int nextChunkIndex = installSnapshotState.incrementChunkIndex();
971 Optional<ServerConfigurationPayload> serverConfig = Optional.empty();
972 if (installSnapshotState.isLastChunk(nextChunkIndex)) {
973 serverConfig = Optional.ofNullable(context.getPeerServerInfo(true));
976 sendSnapshotChunk(followerActor, followerLogInfo, nextSnapshotChunk, nextChunkIndex, serverConfig);
978 log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
979 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
981 } catch (IOException e) {
982 log.warn("{}: Unable to send chunk: {}/{}. Reseting snapshot progress. Snapshot state: {}", logName(),
983 installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks(),
984 installSnapshotState, e);
985 installSnapshotState.reset();
990 private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo,
991 final byte[] snapshotChunk, final int chunkIndex,
992 final Optional<ServerConfigurationPayload> serverConfig) {
993 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
995 installSnapshotState.startChunkTimer();
997 new InstallSnapshot(currentTerm(), context.getId(),
998 snapshotHolder.orElseThrow().getLastIncludedIndex(),
999 snapshotHolder.orElseThrow().getLastIncludedTerm(),
1002 installSnapshotState.getTotalChunks(),
1003 OptionalInt.of(installSnapshotState.getLastChunkHashCode()),
1005 followerLogInfo.getRaftVersion()),
1010 private boolean resendSnapshotChunk(final ActorSelection followerActor,
1011 final FollowerLogInformation followerLogInfo) {
1012 if (!snapshotHolder.isPresent()) {
1013 // Seems like we should never hit this case, but just in case we do, reset the snapshot progress so that it
1014 // can restart from the next AppendEntries.
1015 log.warn("{}: Attempting to resend snapshot with no snapshot holder present.", logName());
1016 followerLogInfo.clearLeaderInstallSnapshotState();
1020 LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
1021 // we are resending, timer needs to be reset
1022 installSnapshotState.resetChunkTimer();
1023 installSnapshotState.markSendStatus(false);
1025 sendSnapshotChunk(followerActor, followerLogInfo);
1030 private void sendHeartBeat() {
1031 if (!followerToLog.isEmpty()) {
1032 log.trace("{}: Sending heartbeat", logName());
1033 sendAppendEntries(context.getConfigParams().getHeartBeatInterval().toNanos(), true);
1035 appendEntriesMessageSlicer.checkExpiredSlicedMessageState();
1039 private void stopHeartBeat() {
1040 if (heartbeatSchedule != null && !heartbeatSchedule.isCancelled()) {
1041 heartbeatSchedule.cancel();
1045 private void scheduleHeartBeat(final FiniteDuration interval) {
1046 if (followerToLog.isEmpty()) {
1047 // Optimization - do not bother scheduling a heartbeat as there are
1054 // Schedule a heartbeat. When the scheduler triggers a SendHeartbeat
1055 // message is sent to itself.
1056 // Scheduling the heartbeat only once here because heartbeats do not
1057 // need to be sent if there are other messages being sent to the remote
1059 heartbeatSchedule = context.getActorSystem().scheduler().scheduleOnce(
1060 interval, context.getActor(), SendHeartBeat.INSTANCE,
1061 context.getActorSystem().dispatcher(), context.getActor());
1065 public void close() {
1067 appendEntriesMessageSlicer.close();
1071 public final String getLeaderId() {
1072 return context.getId();
1076 public final short getLeaderPayloadVersion() {
1077 return context.getPayloadVersion();
1080 protected boolean isLeaderIsolated() {
1081 int minPresent = getMinIsolatedLeaderPeerCount();
1082 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1083 final PeerInfo peerInfo = context.getPeerInfo(followerLogInformation.getId());
1084 if (peerInfo != null && peerInfo.isVoting() && followerLogInformation.isFollowerActive()) {
1086 if (minPresent == 0) {
1091 return minPresent != 0;
1094 // called from example-actor for printing the follower-states
1095 public String printFollowerStates() {
1096 final StringBuilder sb = new StringBuilder();
1099 for (FollowerLogInformation followerLogInformation : followerToLog.values()) {
1101 sb.append(followerLogInformation.getId());
1102 sb.append(" state:");
1103 sb.append(followerLogInformation.isFollowerActive());
1108 return sb.toString();
1112 public FollowerLogInformation getFollower(final String followerId) {
1113 return followerToLog.get(followerId);
1117 public int followerLogSize() {
1118 return followerToLog.size();
1121 static class SnapshotHolder {
1122 private final long lastIncludedTerm;
1123 private final long lastIncludedIndex;
1124 private final ByteSource snapshotBytes;
1126 SnapshotHolder(final Snapshot snapshot, final ByteSource snapshotBytes) {
1127 lastIncludedTerm = snapshot.getLastAppliedTerm();
1128 lastIncludedIndex = snapshot.getLastAppliedIndex();
1129 this.snapshotBytes = snapshotBytes;
1132 long getLastIncludedTerm() {
1133 return lastIncludedTerm;
1136 long getLastIncludedIndex() {
1137 return lastIncludedIndex;
1140 ByteSource getSnapshotBytes() {
1141 return snapshotBytes;