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