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