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