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 akka.actor.ActorRef;
11 import akka.actor.ActorSelection;
12 import akka.actor.Address;
13 import akka.cluster.Cluster;
14 import akka.cluster.ClusterEvent.CurrentClusterState;
15 import akka.cluster.Member;
16 import akka.cluster.MemberStatus;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Stopwatch;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Optional;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.atomic.AtomicBoolean;
26 import java.util.function.Consumer;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.controller.cluster.messaging.MessageAssembler;
29 import org.opendaylight.controller.cluster.raft.RaftActorContext;
30 import org.opendaylight.controller.cluster.raft.RaftState;
31 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
32 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
33 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
34 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
35 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
36 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
37 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
38 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
39 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
40 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
41 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
42 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
43 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
46 * The behavior of a RaftActor in the Follower raft state.
48 * <li> Respond to RPCs from candidates and leaders
49 * <li> If election timeout elapses without receiving AppendEntries
50 * RPC from current leader or granting vote to candidate:
51 * convert to candidate
54 public class Follower extends AbstractRaftActorBehavior {
55 private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
57 private final SyncStatusTracker initialSyncStatusTracker;
59 private final MessageAssembler appendEntriesMessageAssembler;
61 private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
62 private SnapshotTracker snapshotTracker = null;
63 private String leaderId;
64 private short leaderPayloadVersion;
66 public Follower(final RaftActorContext context) {
67 this(context, null, (short)-1);
70 public Follower(final RaftActorContext context, final String initialLeaderId,
71 final short initialLeaderPayloadVersion) {
72 super(context, RaftState.Follower);
73 this.leaderId = initialLeaderId;
74 this.leaderPayloadVersion = initialLeaderPayloadVersion;
76 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), context.getConfigParams()
77 .getSyncIndexThreshold());
79 appendEntriesMessageAssembler = MessageAssembler.builder().logContext(logName())
80 .fileBackedStreamFactory(context.getFileBackedOutputStreamFactory())
81 .assembledMessageCallback((message, sender) -> handleMessage(sender, message)).build();
83 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
84 actor().tell(TimeoutNow.INSTANCE, actor());
86 scheduleElection(electionDuration());
91 public final String getLeaderId() {
96 protected final void setLeaderId(final @Nullable String leaderId) {
97 this.leaderId = leaderId;
101 public short getLeaderPayloadVersion() {
102 return leaderPayloadVersion;
106 protected final void setLeaderPayloadVersion(final short leaderPayloadVersion) {
107 this.leaderPayloadVersion = leaderPayloadVersion;
110 private void restartLastLeaderMessageTimer() {
111 if (lastLeaderMessageTimer.isRunning()) {
112 lastLeaderMessageTimer.reset();
115 lastLeaderMessageTimer.start();
118 private boolean isLogEntryPresent(final long index) {
119 if (context.getReplicatedLog().isInSnapshot(index)) {
123 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
124 return entry != null;
128 private void updateInitialSyncStatus(final long currentLeaderCommit, final String newLeaderId) {
129 initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
133 protected RaftActorBehavior handleAppendEntries(final ActorRef sender, final AppendEntries appendEntries) {
134 int numLogEntries = appendEntries.getEntries().size();
135 if (log.isTraceEnabled()) {
136 log.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
137 } else if (log.isDebugEnabled() && numLogEntries > 0) {
138 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
141 if (snapshotTracker != null && !snapshotTracker.getLeaderId().equals(appendEntries.getLeaderId())) {
142 log.debug("{}: snapshot install is in progress but the prior snapshot leaderId {} does not match the "
143 + "AppendEntries leaderId {}", logName(), snapshotTracker.getLeaderId(), appendEntries.getLeaderId());
144 closeSnapshotTracker();
147 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
148 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
149 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
150 lastIndex(), lastTerm(), context.getPayloadVersion(), false, needsLeaderAddress(),
151 appendEntries.getLeaderRaftVersion());
153 log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
154 sender.tell(reply, actor());
159 // If we got here then we do appear to be talking to the leader
160 leaderId = appendEntries.getLeaderId();
161 leaderPayloadVersion = appendEntries.getPayloadVersion();
163 if (appendEntries.getLeaderAddress().isPresent()) {
164 final String address = appendEntries.getLeaderAddress().get();
165 log.debug("New leader address: {}", address);
167 context.setPeerAddress(leaderId, address);
168 context.getConfigParams().getPeerAddressResolver().setResolved(leaderId, address);
171 // First check if the logs are in sync or not
172 if (isOutOfSync(appendEntries, sender)) {
173 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
177 if (!processNewEntries(appendEntries, sender)) {
178 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
182 long lastIndex = lastIndex();
183 long prevCommitIndex = context.getCommitIndex();
185 // If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry)
186 if (appendEntries.getLeaderCommit() > prevCommitIndex) {
187 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
190 if (prevCommitIndex != context.getCommitIndex()) {
191 log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
194 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
195 lastIndex, lastTerm(), context.getPayloadVersion(), false, needsLeaderAddress(),
196 appendEntries.getLeaderRaftVersion());
198 if (log.isTraceEnabled()) {
199 log.trace("{}: handleAppendEntries returning : {}", logName(), reply);
200 } else if (log.isDebugEnabled() && numLogEntries > 0) {
201 log.debug("{}: handleAppendEntries returning : {}", logName(), reply);
204 // Reply to the leader before applying any previous state so as not to hold up leader consensus.
205 sender.tell(reply, actor());
207 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
209 // If leaderCommit > lastApplied, increment lastApplied and apply log[lastApplied] to state machine (§5.3).
210 // lastApplied can be equal to lastIndex.
211 if (appendEntries.getLeaderCommit() > context.getLastApplied() && context.getLastApplied() < lastIndex) {
212 if (log.isDebugEnabled()) {
213 log.debug("{}: applyLogToStateMachine, appendEntries.getLeaderCommit(): {}, "
214 + "context.getLastApplied(): {}, lastIndex(): {}", logName(),
215 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
218 applyLogToStateMachine(appendEntries.getLeaderCommit());
221 if (!context.getSnapshotManager().isCapturing()) {
222 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
225 appendEntriesMessageAssembler.checkExpiredAssembledMessageState();
230 private boolean processNewEntries(final AppendEntries appendEntries, final ActorRef sender) {
231 int numLogEntries = appendEntries.getEntries().size();
232 if (numLogEntries == 0) {
236 log.debug("{}: Number of entries to be appended = {}", logName(), numLogEntries);
238 long lastIndex = lastIndex();
239 int addEntriesFrom = 0;
241 // First check for conflicting entries. If an existing entry conflicts with a new one (same index but different
242 // term), delete the existing entry and all that follow it (§5.3)
243 if (context.getReplicatedLog().size() > 0) {
244 // Find the entry up until the one that is not in the follower's log
245 for (int i = 0;i < numLogEntries; i++, addEntriesFrom++) {
246 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
248 if (!isLogEntryPresent(matchEntry.getIndex())) {
249 // newEntry not found in the log
253 long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
255 log.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
258 // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
259 // what the term was so we'll assume it matches.
260 if (existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
264 if (!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
265 log.info("{}: Removing entries from log starting at {}, commitIndex: {}, lastApplied: {}",
266 logName(), matchEntry.getIndex(), context.getCommitIndex(), context.getLastApplied());
268 // Entries do not match so remove all subsequent entries but only if the existing entries haven't
269 // been applied to the state yet.
270 if (matchEntry.getIndex() <= context.getLastApplied()
271 || !context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
272 // Could not remove the entries - this means the matchEntry index must be in the
273 // snapshot and not the log. In this case the prior entries are part of the state
274 // so we must send back a reply to force a snapshot to completely re-sync the
275 // follower's log and state.
277 log.info("{}: Could not remove entries - sending reply to force snapshot", logName());
278 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
279 lastTerm(), context.getPayloadVersion(), true, needsLeaderAddress(),
280 appendEntries.getLeaderRaftVersion()), actor());
286 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
287 lastTerm(), context.getPayloadVersion(), true, needsLeaderAddress(),
288 appendEntries.getLeaderRaftVersion()), actor());
294 lastIndex = lastIndex();
295 log.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(), lastIndex,
298 // When persistence successfully completes for each new log entry appended, we need to determine if we
299 // should capture a snapshot to compact the persisted log. shouldCaptureSnapshot tracks whether or not
300 // one of the log entries has exceeded the log size threshold whereby a snapshot should be taken. However
301 // we don't initiate the snapshot at that log entry but rather after the last log entry has been persisted.
302 // This is done because subsequent log entries after the one that tripped the threshold may have been
303 // applied to the state already, as the persistence callback occurs async, and we want those entries
304 // purged from the persisted log as well.
305 final AtomicBoolean shouldCaptureSnapshot = new AtomicBoolean(false);
306 final Consumer<ReplicatedLogEntry> appendAndPersistCallback = logEntry -> {
307 final List<ReplicatedLogEntry> entries = appendEntries.getEntries();
308 final ReplicatedLogEntry lastEntryToAppend = entries.get(entries.size() - 1);
309 if (shouldCaptureSnapshot.get() && logEntry == lastEntryToAppend) {
310 context.getSnapshotManager().capture(context.getReplicatedLog().last(), getReplicatedToAllIndex());
314 // Append any new entries not already in the log
315 for (int i = addEntriesFrom; i < numLogEntries; i++) {
316 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
318 log.debug("{}: Append entry to log {}", logName(), entry.getData());
320 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback, false);
322 shouldCaptureSnapshot.compareAndSet(false,
323 context.getReplicatedLog().shouldCaptureSnapshot(entry.getIndex()));
325 if (entry.getData() instanceof ServerConfigurationPayload) {
326 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
330 log.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
335 private boolean isOutOfSync(final AppendEntries appendEntries, final ActorRef sender) {
337 final long lastIndex = lastIndex();
338 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
340 // The follower's log is out of sync because the leader does have an entry at prevLogIndex and this
341 // follower has no entries in it's log.
343 log.info("{}: The followers log is empty and the senders prevLogIndex is {}", logName(),
344 appendEntries.getPrevLogIndex());
346 sendOutOfSyncAppendEntriesReply(sender, false, appendEntries.getLeaderRaftVersion());
350 if (lastIndex > -1) {
351 if (isLogEntryPresent(appendEntries.getPrevLogIndex())) {
352 final long leadersPrevLogTermInFollowersLogOrSnapshot =
353 getLogEntryOrSnapshotTerm(appendEntries.getPrevLogIndex());
354 if (leadersPrevLogTermInFollowersLogOrSnapshot != appendEntries.getPrevLogTerm()) {
356 // The follower's log is out of sync because the Leader's prevLogIndex entry does exist
357 // in the follower's log or snapshot but it has a different term.
359 log.info("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append "
360 + "entries prevLogTerm {} - lastIndex: {}, snapshotIndex: {}, snapshotTerm: {}", logName(),
361 appendEntries.getPrevLogIndex(), leadersPrevLogTermInFollowersLogOrSnapshot,
362 appendEntries.getPrevLogTerm(), lastIndex, context.getReplicatedLog().getSnapshotIndex(),
363 context.getReplicatedLog().getSnapshotTerm());
365 sendOutOfSyncAppendEntriesReply(sender, false, appendEntries.getLeaderRaftVersion());
368 } else if (appendEntries.getPrevLogIndex() != -1) {
370 // The follower's log is out of sync because the Leader's prevLogIndex entry was not found in it's log
372 log.info("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, "
373 + "snapshotIndex: {}, snapshotTerm: {}", logName(), appendEntries.getPrevLogIndex(), lastIndex,
374 context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm());
376 sendOutOfSyncAppendEntriesReply(sender, false, appendEntries.getLeaderRaftVersion());
381 if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
382 && appendEntries.getReplicatedToAllIndex() != -1) {
383 if (!isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
384 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
385 // the previous entry in it's in-memory journal
387 log.info("{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the "
388 + "in-memory journal - lastIndex: {}, snapshotIndex: {}, snapshotTerm: {}", logName(),
389 appendEntries.getReplicatedToAllIndex(), lastIndex,
390 context.getReplicatedLog().getSnapshotIndex(), context.getReplicatedLog().getSnapshotTerm());
392 sendOutOfSyncAppendEntriesReply(sender, false, appendEntries.getLeaderRaftVersion());
396 final List<ReplicatedLogEntry> entries = appendEntries.getEntries();
397 if (entries.size() > 0 && !isLogEntryPresent(entries.get(0).getIndex() - 1)) {
398 log.info("{}: Cannot append entries because the calculated previousIndex {} was not found in the "
399 + "in-memory journal - lastIndex: {}, snapshotIndex: {}, snapshotTerm: {}", logName(),
400 entries.get(0).getIndex() - 1, lastIndex, context.getReplicatedLog().getSnapshotIndex(),
401 context.getReplicatedLog().getSnapshotTerm());
403 sendOutOfSyncAppendEntriesReply(sender, false, appendEntries.getLeaderRaftVersion());
411 private void sendOutOfSyncAppendEntriesReply(final ActorRef sender, final boolean forceInstallSnapshot,
412 final short leaderRaftVersion) {
413 // We found that the log was out of sync so just send a negative reply.
414 final AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex(),
415 lastTerm(), context.getPayloadVersion(), forceInstallSnapshot, needsLeaderAddress(),
418 log.info("{}: Follower is out-of-sync so sending negative reply: {}", logName(), reply);
419 sender.tell(reply, actor());
422 private boolean needsLeaderAddress() {
423 return context.getPeerAddress(leaderId) == null;
427 protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
428 final AppendEntriesReply appendEntriesReply) {
433 protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender,
434 final RequestVoteReply requestVoteReply) {
439 public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
440 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
441 return handleElectionTimeout(message);
444 if (appendEntriesMessageAssembler.handleMessage(message, actor())) {
448 if (!(message instanceof RaftRPC)) {
449 // The rest of the processing requires the message to be a RaftRPC
453 final RaftRPC rpc = (RaftRPC) message;
454 // If RPC request or response contains term T > currentTerm:
455 // set currentTerm = T, convert to follower (§5.1)
456 // This applies to all RPC messages and responses
457 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
458 log.info("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
459 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
461 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
464 if (rpc instanceof InstallSnapshot) {
465 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
466 restartLastLeaderMessageTimer();
467 scheduleElection(electionDuration());
471 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
472 restartLastLeaderMessageTimer();
473 scheduleElection(electionDuration());
476 return super.handleMessage(sender, rpc);
479 private RaftActorBehavior handleElectionTimeout(final Object message) {
480 // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
481 // during the election timeout interval. It may that the election timer expired b/c this actor
482 // was busy and messages got delayed, in which case leader messages would be backed up in the
483 // queue but would be processed before the ElectionTimeout message and thus would restart the
484 // lastLeaderMessageTimer.
485 long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
486 long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
487 boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning()
488 || lastLeaderMessageInterval >= electionTimeoutInMillis;
490 if (canStartElection()) {
491 if (message instanceof TimeoutNow) {
492 log.debug("{}: Received TimeoutNow - switching to Candidate", logName());
493 return internalSwitchBehavior(RaftState.Candidate);
494 } else if (noLeaderMessageReceived) {
495 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
496 // However if we haven't heard from the leader in a long time even though the cluster state
497 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
499 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
500 if (isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
501 log.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
502 scheduleElection(electionDuration());
504 log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
505 return internalSwitchBehavior(RaftState.Candidate);
508 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
509 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
510 scheduleElection(electionDuration());
512 } else if (message instanceof ElectionTimeout) {
513 if (noLeaderMessageReceived) {
517 scheduleElection(electionDuration());
523 private boolean isLeaderAvailabilityKnown() {
524 if (leaderId == null) {
528 Optional<Cluster> cluster = context.getCluster();
529 if (!cluster.isPresent()) {
533 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
534 if (leaderActor == null) {
538 Address leaderAddress = leaderActor.anchorPath().address();
540 CurrentClusterState state = cluster.get().state();
541 Set<Member> unreachable = state.getUnreachable();
543 log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
546 for (Member m: unreachable) {
547 if (leaderAddress.equals(m.address())) {
548 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
553 for (Member m: state.getMembers()) {
554 if (leaderAddress.equals(m.address())) {
555 if (m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
556 log.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
557 leaderAddress, m.status());
560 log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
561 leaderAddress, m.status());
567 log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
572 private void handleInstallSnapshot(final ActorRef sender, final InstallSnapshot installSnapshot) {
574 log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
576 leaderId = installSnapshot.getLeaderId();
578 if (snapshotTracker == null) {
579 snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId(),
583 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
586 final InstallSnapshotReply reply = new InstallSnapshotReply(
587 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
589 if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
590 installSnapshot.getLastChunkHashCode())) {
592 log.info("{}: Snapshot installed from leader: {}", logName(), installSnapshot.getLeaderId());
594 Snapshot snapshot = Snapshot.create(
595 context.getSnapshotManager().convertSnapshot(snapshotTracker.getSnapshotBytes()),
597 installSnapshot.getLastIncludedIndex(),
598 installSnapshot.getLastIncludedTerm(),
599 installSnapshot.getLastIncludedIndex(),
600 installSnapshot.getLastIncludedTerm(),
601 context.getTermInformation().getCurrentTerm(),
602 context.getTermInformation().getVotedFor(),
603 installSnapshot.getServerConfig().orElse(null));
605 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
607 public void onSuccess() {
608 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
610 sender.tell(reply, actor());
614 public void onFailure() {
615 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
619 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
621 closeSnapshotTracker();
623 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
625 sender.tell(reply, actor());
627 } catch (IOException e) {
628 log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
630 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
631 -1, false), actor());
633 closeSnapshotTracker();
637 private void closeSnapshotTracker() {
638 if (snapshotTracker != null) {
639 snapshotTracker.close();
640 snapshotTracker = null;
645 public void close() {
646 closeSnapshotTracker();
648 appendEntriesMessageAssembler.close();
652 SnapshotTracker getSnapshotTracker() {
653 return snapshotTracker;