Bug 5460: Fix snaphots on follower
[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.japi.Procedure;
13 import com.google.common.annotations.VisibleForTesting;
14 import java.util.ArrayList;
15 import org.opendaylight.controller.cluster.raft.RaftActorContext;
16 import org.opendaylight.controller.cluster.raft.RaftState;
17 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
18 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
19 import org.opendaylight.controller.cluster.raft.Snapshot;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
22 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
24 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
25 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
26 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
27 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
28 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
29
30 /**
31  * The behavior of a RaftActor in the Follower state
32  * <p/>
33  * <ul>
34  * <li> Respond to RPCs from candidates and leaders
35  * <li> If election timeout elapses without receiving AppendEntries
36  * RPC from current leader or granting vote to candidate:
37  * convert to candidate
38  * </ul>
39  */
40 public class Follower extends AbstractRaftActorBehavior {
41     private static final int SYNC_THRESHOLD = 10;
42
43     private final SyncStatusTracker initialSyncStatusTracker;
44
45     private final Procedure<ReplicatedLogEntry> appendAndPersistCallback = new Procedure<ReplicatedLogEntry>() {
46         @Override
47         public void apply(ReplicatedLogEntry logEntry) {
48             context.getReplicatedLog().captureSnapshotIfReady(logEntry);
49         }
50     };
51
52     private SnapshotTracker snapshotTracker = null;
53
54     public Follower(RaftActorContext context) {
55         this(context, null, (short)-1);
56     }
57
58     public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
59         super(context, RaftState.Follower);
60         leaderId = initialLeaderId;
61         setLeaderPayloadVersion(initialLeaderPayloadVersion);
62
63         initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
64
65         if(canStartElection()) {
66             if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
67                 actor().tell(ElectionTimeout.INSTANCE, actor());
68             } else {
69                 scheduleElection(electionDuration());
70             }
71         }
72
73     }
74
75     private boolean isLogEntryPresent(long index){
76         if(index == context.getReplicatedLog().getSnapshotIndex()){
77             return true;
78         }
79
80         ReplicatedLogEntry previousEntry = context.getReplicatedLog()
81                 .get(index);
82
83         return previousEntry != null;
84
85     }
86
87     private long getLogEntryTerm(long index){
88         if(index == context.getReplicatedLog().getSnapshotIndex()){
89             return context.getReplicatedLog().getSnapshotTerm();
90         }
91
92         ReplicatedLogEntry previousEntry = context.getReplicatedLog()
93                 .get(index);
94
95         if(previousEntry != null){
96             return previousEntry.getTerm();
97         }
98
99         return -1;
100     }
101
102     private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
103         initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
104     }
105
106     @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
107                                                               AppendEntries appendEntries) {
108
109         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
110         if(LOG.isTraceEnabled()) {
111             LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
112         } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
113             LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
114         }
115
116         // TODO : Refactor this method into a bunch of smaller methods
117         // to make it easier to read. Before refactoring ensure tests
118         // cover the code properly
119
120         if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
121             // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
122             AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
123                     lastIndex(), lastTerm(), context.getPayloadVersion());
124
125             if(LOG.isDebugEnabled()) {
126                 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
127             }
128             sender.tell(reply, actor());
129
130             return this;
131         }
132
133         // If we got here then we do appear to be talking to the leader
134         leaderId = appendEntries.getLeaderId();
135
136         setLeaderPayloadVersion(appendEntries.getPayloadVersion());
137
138         updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
139         // First check if the logs are in sync or not
140         long lastIndex = lastIndex();
141
142         if (isOutOfSync(appendEntries)) {
143             // We found that the log was out of sync so just send a negative
144             // reply and return
145
146             LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
147                         logName(), lastIndex, lastTerm());
148
149             sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
150                     lastTerm(), context.getPayloadVersion()), actor());
151             return this;
152         }
153
154         if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
155
156             LOG.debug("{}: Number of entries to be appended = {}", logName(),
157                         appendEntries.getEntries().size());
158
159             // 3. If an existing entry conflicts with a new one (same index
160             // but different terms), delete the existing entry and all that
161             // follow it (§5.3)
162             int addEntriesFrom = 0;
163             if (context.getReplicatedLog().size() > 0) {
164
165                 // Find the entry up until the one that is not in the follower's log
166                 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
167                     ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
168                     ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
169
170                     if (newEntry == null) {
171                         //newEntry not found in the log
172                         break;
173                     }
174
175                     if (newEntry.getTerm() == matchEntry.getTerm()) {
176                         continue;
177                     }
178
179                     if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
180
181                         LOG.debug("{}: Removing entries from log starting at {}", logName(),
182                                 matchEntry.getIndex());
183
184                         // Entries do not match so remove all subsequent entries
185                         context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
186                         break;
187                     } else {
188                         sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
189                                 lastTerm(), context.getPayloadVersion(), true), actor());
190                         return this;
191                     }
192                 }
193             }
194
195             lastIndex = lastIndex();
196             LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
197                         (addEntriesFrom + lastIndex));
198
199             // 4. Append any new entries not already in the log
200             for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
201                 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
202
203                 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
204
205                 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
206
207                 if(entry.getData() instanceof ServerConfigurationPayload) {
208                     context.updatePeerIds((ServerConfigurationPayload)entry.getData());
209                 }
210             }
211
212             LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
213         }
214
215         // 5. If leaderCommit > commitIndex, set commitIndex =
216         // min(leaderCommit, index of last new entry)
217
218         lastIndex = lastIndex();
219         long prevCommitIndex = context.getCommitIndex();
220
221         context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
222
223         if (prevCommitIndex != context.getCommitIndex()) {
224             LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
225         }
226
227         // If commitIndex > lastApplied: increment lastApplied, apply
228         // log[lastApplied] to state machine (§5.3)
229         // check if there are any entries to be applied. last-applied can be equal to last-index
230         if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
231             context.getLastApplied() < lastIndex) {
232             if(LOG.isDebugEnabled()) {
233                 LOG.debug("{}: applyLogToStateMachine, " +
234                         "appendEntries.getLeaderCommit(): {}," +
235                         "context.getLastApplied(): {}, lastIndex(): {}", logName(),
236                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
237             }
238
239             applyLogToStateMachine(appendEntries.getLeaderCommit());
240         }
241
242         AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
243             lastIndex, lastTerm(), context.getPayloadVersion());
244
245         if(LOG.isTraceEnabled()) {
246             LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
247         } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
248             LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
249         }
250
251         sender.tell(reply, actor());
252
253         if (!context.getSnapshotManager().isCapturing()) {
254             super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
255         }
256
257         return this;
258     }
259
260     private boolean isOutOfSync(AppendEntries appendEntries) {
261
262         long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
263         boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
264         long lastIndex = lastIndex();
265         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
266         boolean outOfSync = true;
267
268         if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
269
270             // The follower's log is out of sync because the leader does have
271             // an entry at prevLogIndex and this follower has no entries in
272             // it's log.
273
274             LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
275                         logName(), appendEntries.getPrevLogIndex());
276         } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
277
278             // The follower's log is out of sync because the Leader's
279             // prevLogIndex entry was not found in it's log
280
281             LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
282                         logName(), appendEntries.getPrevLogIndex());
283         } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
284
285             // The follower's log is out of sync because the Leader's
286             // prevLogIndex entry does exist in the follower's log but it has
287             // a different term in it
288
289             LOG.debug(
290                     "{}: Cannot append entries because previous entry term {}  is not equal to append entries prevLogTerm {}",
291                     logName(), prevLogTerm, appendEntries.getPrevLogTerm());
292         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
293                 && appendEntries.getReplicatedToAllIndex() != -1
294                 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())
295                 && !context.getReplicatedLog().isInSnapshot(appendEntries.getReplicatedToAllIndex())) {
296             // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
297             // the previous entry in it's in-memory journal
298
299             LOG.debug(
300                     "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
301                     logName(), appendEntries.getReplicatedToAllIndex());
302         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
303                 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
304                 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)
305                 && !context.getReplicatedLog().isInSnapshot(appendEntries.getEntries().get(0).getIndex() - 1)) {
306             LOG.debug(
307                     "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
308                     logName(), appendEntries.getEntries().get(0).getIndex() - 1);
309         } else {
310             outOfSync = false;
311         }
312         return outOfSync;
313     }
314
315     @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
316         AppendEntriesReply appendEntriesReply) {
317         return this;
318     }
319
320     @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
321         RequestVoteReply requestVoteReply) {
322         return this;
323     }
324
325     @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
326
327         Object message = fromSerializableMessage(originalMessage);
328
329         if (message instanceof RaftRPC) {
330             RaftRPC rpc = (RaftRPC) message;
331             // If RPC request or response contains term T > currentTerm:
332             // set currentTerm = T, convert to follower (§5.1)
333             // This applies to all RPC messages and responses
334             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
335                 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
336                         logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
337
338                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
339             }
340         }
341
342         if (message instanceof ElectionTimeout) {
343             if(canStartElection()) {
344                 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
345                 return internalSwitchBehavior(RaftState.Candidate);
346             } else {
347                 return this;
348             }
349
350         } else if (message instanceof InstallSnapshot) {
351             InstallSnapshot installSnapshot = (InstallSnapshot) message;
352             handleInstallSnapshot(sender, installSnapshot);
353         }
354
355         if(message instanceof RaftRPC && (!(message instanceof RequestVote) || (canGrantVote((RequestVote) message)))){
356             scheduleElection(electionDuration());
357         }
358
359         return super.handleMessage(sender, message);
360     }
361
362     private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
363
364         LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
365
366         leaderId = installSnapshot.getLeaderId();
367
368         if(snapshotTracker == null){
369             snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
370         }
371
372         updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
373
374         try {
375             final InstallSnapshotReply reply = new InstallSnapshotReply(
376                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
377
378             if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
379                     installSnapshot.getLastChunkHashCode())){
380                 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
381                         new ArrayList<ReplicatedLogEntry>(),
382                         installSnapshot.getLastIncludedIndex(),
383                         installSnapshot.getLastIncludedTerm(),
384                         installSnapshot.getLastIncludedIndex(),
385                         installSnapshot.getLastIncludedTerm(),
386                         context.getTermInformation().getCurrentTerm(),
387                         context.getTermInformation().getVotedFor(),
388                         context.getPeerServerInfo(true));
389
390                 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
391                     @Override
392                     public void onSuccess() {
393                         LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
394
395                         sender.tell(reply, actor());
396                     }
397
398                     @Override
399                     public void onFailure() {
400                         sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
401                     }
402                 };
403
404                 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
405
406                 snapshotTracker = null;
407             } else {
408                 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
409
410                 sender.tell(reply, actor());
411             }
412         } catch (SnapshotTracker.InvalidChunkException e) {
413             LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
414
415             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
416                     -1, false), actor());
417             snapshotTracker = null;
418
419         } catch (Exception e){
420             LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
421
422             //send reply with success as false. The chunk will be sent again on failure
423             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
424                     installSnapshot.getChunkIndex(), false), actor());
425
426         }
427     }
428
429     @Override
430     public void close() throws Exception {
431         stopElection();
432     }
433
434     @VisibleForTesting
435     SnapshotTracker getSnapshotTracker(){
436         return snapshotTracker;
437     }
438 }