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