Bug 7521: Convert install snapshot chunking to use streams
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / Follower.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Address;
14 import akka.cluster.Cluster;
15 import akka.cluster.ClusterEvent.CurrentClusterState;
16 import akka.cluster.Member;
17 import akka.cluster.MemberStatus;
18 import akka.japi.Procedure;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Stopwatch;
21 import java.io.IOException;
22 import java.util.ArrayList;
23 import java.util.Optional;
24 import java.util.Set;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import javax.annotation.Nullable;
28 import org.opendaylight.controller.cluster.raft.RaftActorContext;
29 import org.opendaylight.controller.cluster.raft.RaftState;
30 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
32 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
33 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
34 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
35 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
36 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
37 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
38 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
39 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
40 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
41 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
42 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
43
44 /**
45  * The behavior of a RaftActor in the Follower raft state.
46  * <ul>
47  * <li> Respond to RPCs from candidates and leaders
48  * <li> If election timeout elapses without receiving AppendEntries
49  * RPC from current leader or granting vote to candidate:
50  * convert to candidate
51  * </ul>
52  */
53 public class Follower extends AbstractRaftActorBehavior {
54     private static final int SYNC_THRESHOLD = 10;
55
56     private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
57
58     private final SyncStatusTracker initialSyncStatusTracker;
59
60     private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
61     private SnapshotTracker snapshotTracker = null;
62     private String leaderId;
63     private short leaderPayloadVersion;
64
65     public Follower(RaftActorContext context) {
66         this(context, null, (short)-1);
67     }
68
69     public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
70         super(context, RaftState.Follower);
71         this.leaderId = initialLeaderId;
72         this.leaderPayloadVersion = initialLeaderPayloadVersion;
73
74         initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
75
76         if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
77             actor().tell(TimeoutNow.INSTANCE, actor());
78         } else {
79             scheduleElection(electionDuration());
80         }
81     }
82
83     @Override
84     public final String getLeaderId() {
85         return leaderId;
86     }
87
88     @VisibleForTesting
89     protected final void setLeaderId(@Nullable final String leaderId) {
90         this.leaderId = leaderId;
91     }
92
93     @Override
94     public short getLeaderPayloadVersion() {
95         return leaderPayloadVersion;
96     }
97
98     @VisibleForTesting
99     protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
100         this.leaderPayloadVersion = leaderPayloadVersion;
101     }
102
103     private void restartLastLeaderMessageTimer() {
104         if (lastLeaderMessageTimer.isRunning()) {
105             lastLeaderMessageTimer.reset();
106         }
107
108         lastLeaderMessageTimer.start();
109     }
110
111     private boolean isLogEntryPresent(long index) {
112         if (context.getReplicatedLog().isInSnapshot(index)) {
113             return true;
114         }
115
116         ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
117         return entry != null;
118
119     }
120
121     private void updateInitialSyncStatus(long currentLeaderCommit, String newLeaderId) {
122         initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
123     }
124
125     @Override
126     protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
127
128         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
129         if (log.isTraceEnabled()) {
130             log.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
131         } else if (log.isDebugEnabled() && numLogEntries > 0) {
132             log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
133         }
134
135         // TODO : Refactor this method into a bunch of smaller methods
136         // to make it easier to read. Before refactoring ensure tests
137         // cover the code properly
138
139         if (snapshotTracker != null && !snapshotTracker.getLeaderId().equals(appendEntries.getLeaderId())) {
140             log.debug("{}: snapshot install is in progress but the prior snapshot leaderId {} does not match the "
141                 + "AppendEntries leaderId {}", logName(), snapshotTracker.getLeaderId(), appendEntries.getLeaderId());
142             snapshotTracker = null;
143         }
144
145         if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
146             // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
147             AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
148                     lastIndex(), lastTerm(), context.getPayloadVersion());
149
150             log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
151             sender.tell(reply, actor());
152
153             return this;
154         }
155
156         // If we got here then we do appear to be talking to the leader
157         leaderId = appendEntries.getLeaderId();
158         leaderPayloadVersion = appendEntries.getPayloadVersion();
159
160         updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
161         // First check if the logs are in sync or not
162         long lastIndex = lastIndex();
163
164         if (isOutOfSync(appendEntries)) {
165             // We found that the log was out of sync so just send a negative
166             // reply and return
167
168             log.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
169                         logName(), lastIndex, lastTerm());
170
171             sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
172                     lastTerm(), context.getPayloadVersion()), actor());
173             return this;
174         }
175
176         if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
177
178             log.debug("{}: Number of entries to be appended = {}", logName(),
179                         appendEntries.getEntries().size());
180
181             // 3. If an existing entry conflicts with a new one (same index
182             // but different terms), delete the existing entry and all that
183             // follow it (§5.3)
184             int addEntriesFrom = 0;
185             if (context.getReplicatedLog().size() > 0) {
186
187                 // Find the entry up until the one that is not in the follower's log
188                 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
189                     ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
190
191                     if (!isLogEntryPresent(matchEntry.getIndex())) {
192                         // newEntry not found in the log
193                         break;
194                     }
195
196                     long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
197
198                     log.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
199                             existingEntryTerm);
200
201                     // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
202                     // what the term was so we'll assume it matches.
203                     if (existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
204                         continue;
205                     }
206
207                     if (!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
208
209                         log.debug("{}: Removing entries from log starting at {}", logName(),
210                                 matchEntry.getIndex());
211
212                         // Entries do not match so remove all subsequent entries
213                         if (!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
214                             // Could not remove the entries - this means the matchEntry index must be in the
215                             // snapshot and not the log. In this case the prior entries are part of the state
216                             // so we must send back a reply to force a snapshot to completely re-sync the
217                             // follower's log and state.
218
219                             log.debug("{}: Could not remove entries - sending reply to force snapshot", logName());
220                             sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
221                                     lastTerm(), context.getPayloadVersion(), true), actor());
222                             return this;
223                         }
224
225                         break;
226                     } else {
227                         sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
228                                 lastTerm(), context.getPayloadVersion(), true), actor());
229                         return this;
230                     }
231                 }
232             }
233
234             lastIndex = lastIndex();
235             log.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
236                     lastIndex, addEntriesFrom);
237
238             // When persistence successfully completes for each new log entry appended, we need to determine if we
239             // should capture a snapshot to compact the persisted log. shouldCaptureSnapshot tracks whether or not
240             // one of the log entries has exceeded the log size threshold whereby a snapshot should be taken. However
241             // we don't initiate the snapshot at that log entry but rather after the last log entry has been persisted.
242             // This is done because subsequent log entries after the one that tripped the threshold may have been
243             // applied to the state already, as the persistence callback occurs async, and we want those entries
244             // purged from the persisted log as well.
245             final AtomicBoolean shouldCaptureSnapshot = new AtomicBoolean(false);
246             final Procedure<ReplicatedLogEntry> appendAndPersistCallback = logEntry -> {
247                 final ReplicatedLogEntry lastEntryToAppend = appendEntries.getEntries().get(
248                         appendEntries.getEntries().size() - 1);
249                 if (shouldCaptureSnapshot.get() && logEntry == lastEntryToAppend) {
250                     context.getSnapshotManager().capture(context.getReplicatedLog().last(), getReplicatedToAllIndex());
251                 }
252             };
253
254             // 4. Append any new entries not already in the log
255             for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
256                 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
257
258                 log.debug("{}: Append entry to log {}", logName(), entry.getData());
259
260                 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback, false);
261
262                 shouldCaptureSnapshot.compareAndSet(false,
263                         context.getReplicatedLog().shouldCaptureSnapshot(entry.getIndex()));
264
265                 if (entry.getData() instanceof ServerConfigurationPayload) {
266                     context.updatePeerIds((ServerConfigurationPayload)entry.getData());
267                 }
268             }
269
270             log.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
271         }
272
273         // 5. If leaderCommit > commitIndex, set commitIndex =
274         // min(leaderCommit, index of last new entry)
275
276         lastIndex = lastIndex();
277         long prevCommitIndex = context.getCommitIndex();
278
279         if (appendEntries.getLeaderCommit() > prevCommitIndex) {
280             context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
281         }
282
283         if (prevCommitIndex != context.getCommitIndex()) {
284             log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
285         }
286
287         // If commitIndex > lastApplied: increment lastApplied, apply
288         // log[lastApplied] to state machine (§5.3)
289         // check if there are any entries to be applied. last-applied can be equal to last-index
290         if (appendEntries.getLeaderCommit() > context.getLastApplied()
291                 && context.getLastApplied() < lastIndex) {
292             if (log.isDebugEnabled()) {
293                 log.debug("{}: applyLogToStateMachine, appendEntries.getLeaderCommit(): {},"
294                         + "context.getLastApplied(): {}, lastIndex(): {}", logName(),
295                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
296             }
297
298             applyLogToStateMachine(appendEntries.getLeaderCommit());
299         }
300
301         AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
302             lastIndex, lastTerm(), context.getPayloadVersion());
303
304         if (log.isTraceEnabled()) {
305             log.trace("{}: handleAppendEntries returning : {}", logName(), reply);
306         } else if (log.isDebugEnabled() && numLogEntries > 0) {
307             log.debug("{}: handleAppendEntries returning : {}", logName(), reply);
308         }
309
310         sender.tell(reply, actor());
311
312         if (!context.getSnapshotManager().isCapturing()) {
313             super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
314         }
315
316         return this;
317     }
318
319     private boolean isOutOfSync(AppendEntries appendEntries) {
320
321         long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
322         boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
323         long lastIndex = lastIndex();
324         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
325         boolean outOfSync = true;
326
327         if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
328
329             // The follower's log is out of sync because the leader does have
330             // an entry at prevLogIndex and this follower has no entries in
331             // it's log.
332
333             log.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
334                         logName(), appendEntries.getPrevLogIndex());
335         } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
336
337             // The follower's log is out of sync because the Leader's
338             // prevLogIndex entry was not found in it's log
339
340             log.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - "
341                     + "lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(), lastIndex,
342                     context.getReplicatedLog().getSnapshotIndex());
343         } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
344
345             // The follower's log is out of sync because the Leader's
346             // prevLogIndex entry does exist in the follower's log but it has
347             // a different term in it
348
349             log.debug("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append entries"
350                       + "prevLogTerm {} - lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(),
351                       prevLogTerm, appendEntries.getPrevLogTerm(), lastIndex,
352                       context.getReplicatedLog().getSnapshotIndex());
353         } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
354                 && appendEntries.getReplicatedToAllIndex() != -1
355                 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
356             // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
357             // the previous entry in it's in-memory journal
358
359             log.debug("{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the"
360                     + " in-memory journal", logName(), appendEntries.getReplicatedToAllIndex());
361         } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
362                 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
363                 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
364             log.debug("{}: Cannot append entries because the calculated previousIndex {} was not found in the "
365                     + " in-memory journal", logName(), appendEntries.getEntries().get(0).getIndex() - 1);
366         } else {
367             outOfSync = false;
368         }
369         return outOfSync;
370     }
371
372     @Override
373     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
374         AppendEntriesReply appendEntriesReply) {
375         return this;
376     }
377
378     @Override
379     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
380         RequestVoteReply requestVoteReply) {
381         return this;
382     }
383
384     @Override
385     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
386         if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
387             return handleElectionTimeout(message);
388         }
389
390         if (!(message instanceof RaftRPC)) {
391             // The rest of the processing requires the message to be a RaftRPC
392             return null;
393         }
394
395         final RaftRPC rpc = (RaftRPC) message;
396         // If RPC request or response contains term T > currentTerm:
397         // set currentTerm = T, convert to follower (§5.1)
398         // This applies to all RPC messages and responses
399         if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
400             log.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
401                 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
402
403             context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
404         }
405
406         if (rpc instanceof InstallSnapshot) {
407             handleInstallSnapshot(sender, (InstallSnapshot) rpc);
408             restartLastLeaderMessageTimer();
409             scheduleElection(electionDuration());
410             return this;
411         }
412
413         if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
414             restartLastLeaderMessageTimer();
415             scheduleElection(electionDuration());
416         }
417
418         return super.handleMessage(sender, rpc);
419     }
420
421     private RaftActorBehavior handleElectionTimeout(Object message) {
422         // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
423         // during the election timeout interval. It may that the election timer expired b/c this actor
424         // was busy and messages got delayed, in which case leader messages would be backed up in the
425         // queue but would be processed before the ElectionTimeout message and thus would restart the
426         // lastLeaderMessageTimer.
427         long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
428         long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
429         boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning()
430                 || lastLeaderMessageInterval >= electionTimeoutInMillis;
431
432         if (canStartElection()) {
433             if (message instanceof TimeoutNow) {
434                 log.debug("{}: Received TimeoutNow - switching to Candidate", logName());
435                 return internalSwitchBehavior(RaftState.Candidate);
436             } else if (noLeaderMessageReceived) {
437                 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
438                 // However if we haven't heard from the leader in a long time even though the cluster state
439                 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
440                 // to Candidate,
441                 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
442                 if (isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
443                     log.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
444                     scheduleElection(electionDuration());
445                 } else {
446                     log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
447                     return internalSwitchBehavior(RaftState.Candidate);
448                 }
449             } else {
450                 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
451                         logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
452                 scheduleElection(electionDuration());
453             }
454         } else if (message instanceof ElectionTimeout) {
455             if (noLeaderMessageReceived) {
456                 setLeaderId(null);
457             }
458
459             scheduleElection(electionDuration());
460         }
461
462         return this;
463     }
464
465     private boolean isLeaderAvailabilityKnown() {
466         if (leaderId == null) {
467             return false;
468         }
469
470         Optional<Cluster> cluster = context.getCluster();
471         if (!cluster.isPresent()) {
472             return false;
473         }
474
475         ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
476         if (leaderActor == null) {
477             return false;
478         }
479
480         Address leaderAddress = leaderActor.anchorPath().address();
481
482         CurrentClusterState state = cluster.get().state();
483         Set<Member> unreachable = state.getUnreachable();
484
485         log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
486                 unreachable);
487
488         for (Member m: unreachable) {
489             if (leaderAddress.equals(m.address())) {
490                 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
491                 return false;
492             }
493         }
494
495         for (Member m: state.getMembers()) {
496             if (leaderAddress.equals(m.address())) {
497                 if (m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
498                     log.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
499                             leaderAddress, m.status());
500                     return true;
501                 } else {
502                     log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
503                             leaderAddress, m.status());
504                     return false;
505                 }
506             }
507         }
508
509         log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
510
511         return false;
512     }
513
514     private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
515
516         log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
517
518         leaderId = installSnapshot.getLeaderId();
519
520         if (snapshotTracker == null) {
521             snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
522         }
523
524         updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
525
526         try {
527             final InstallSnapshotReply reply = new InstallSnapshotReply(
528                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
529
530             if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
531                     installSnapshot.getLastChunkHashCode())) {
532                 Snapshot snapshot = Snapshot.create(
533                         context.getSnapshotManager().convertSnapshot(snapshotTracker.getSnapshotBytes()),
534                         new ArrayList<>(),
535                         installSnapshot.getLastIncludedIndex(),
536                         installSnapshot.getLastIncludedTerm(),
537                         installSnapshot.getLastIncludedIndex(),
538                         installSnapshot.getLastIncludedTerm(),
539                         context.getTermInformation().getCurrentTerm(),
540                         context.getTermInformation().getVotedFor(),
541                         installSnapshot.getServerConfig().orNull());
542
543                 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
544                     @Override
545                     public void onSuccess() {
546                         log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
547
548                         sender.tell(reply, actor());
549                     }
550
551                     @Override
552                     public void onFailure() {
553                         sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
554                     }
555                 };
556
557                 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
558
559                 closeSnapshotTracker();
560             } else {
561                 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
562
563                 sender.tell(reply, actor());
564             }
565         } catch (IOException e) {
566             log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
567
568             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
569                     -1, false), actor());
570
571             closeSnapshotTracker();
572         }
573     }
574
575     private void closeSnapshotTracker() {
576         if (snapshotTracker != null) {
577             snapshotTracker.close();
578             snapshotTracker = null;
579         }
580     }
581
582     @Override
583     public void close() {
584         closeSnapshotTracker();
585         stopElection();
586     }
587
588     @VisibleForTesting
589     SnapshotTracker getSnapshotTracker() {
590         return snapshotTracker;
591     }
592 }