d4755e63586f564cd71d106529cef910074b8cba
[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 which 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                     LOG.debug("{}: Removing entries from log starting at {}", logName(),
165                                 matchEntry.getIndex());
166
167                     // Entries do not match so remove all subsequent entries
168                     context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
169                     break;
170                 }
171             }
172
173             lastIndex = lastIndex();
174             LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
175                         (addEntriesFrom + lastIndex));
176
177             // 4. Append any new entries not already in the log
178             for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
179                 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
180
181                 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
182
183                 context.getReplicatedLog().appendAndPersist(entry);
184             }
185
186             LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
187         }
188
189         // 5. If leaderCommit > commitIndex, set commitIndex =
190         // min(leaderCommit, index of last new entry)
191
192         lastIndex = lastIndex();
193         long prevCommitIndex = context.getCommitIndex();
194
195         context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
196
197         if (prevCommitIndex != context.getCommitIndex()) {
198             LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
199         }
200
201         // If commitIndex > lastApplied: increment lastApplied, apply
202         // log[lastApplied] to state machine (§5.3)
203         // check if there are any entries to be applied. last-applied can be equal to last-index
204         if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
205             context.getLastApplied() < lastIndex) {
206             if(LOG.isDebugEnabled()) {
207                 LOG.debug("{}: applyLogToStateMachine, " +
208                         "appendEntries.getLeaderCommit(): {}," +
209                         "context.getLastApplied(): {}, lastIndex(): {}", logName(),
210                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
211             }
212
213             applyLogToStateMachine(appendEntries.getLeaderCommit());
214         }
215
216         AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
217             lastIndex, lastTerm(), context.getPayloadVersion());
218
219         if(LOG.isTraceEnabled()) {
220             LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
221         } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
222             LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
223         }
224
225         sender.tell(reply, actor());
226
227         if (!context.getSnapshotManager().isCapturing()) {
228             super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
229         }
230
231         return this;
232     }
233
234     private boolean isOutOfSync(AppendEntries appendEntries) {
235
236         long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
237         boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
238         long lastIndex = lastIndex();
239         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
240         boolean outOfSync = true;
241
242         if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
243
244             // The follower's log is out of sync because the leader does have
245             // an entry at prevLogIndex and this follower has no entries in
246             // it's log.
247
248             LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
249                         logName(), appendEntries.getPrevLogIndex());
250         } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
251
252             // The follower's log is out of sync because the Leader's
253             // prevLogIndex entry was not found in it's log
254
255             LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
256                         logName(), appendEntries.getPrevLogIndex());
257         } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
258
259             // The follower's log is out of sync because the Leader's
260             // prevLogIndex entry does exist in the follower's log but it has
261             // a different term in it
262
263             LOG.debug(
264                     "{}: Cannot append entries because previous entry term {}  is not equal to append entries prevLogTerm {}",
265                     logName(), prevLogTerm, appendEntries.getPrevLogTerm());
266         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
267                 && appendEntries.getReplicatedToAllIndex() != -1
268                 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
269             // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
270             // the previous entry in it's in-memory journal
271
272             LOG.debug(
273                     "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
274                     logName(), appendEntries.getReplicatedToAllIndex());
275         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
276                 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0 &&
277                 !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)){
278             LOG.debug(
279                     "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
280                     logName(), appendEntries.getEntries().get(0).getIndex() - 1);
281         } else {
282             outOfSync = false;
283         }
284         return outOfSync;
285     }
286
287     @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
288         AppendEntriesReply appendEntriesReply) {
289         return this;
290     }
291
292     @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
293         RequestVoteReply requestVoteReply) {
294         return this;
295     }
296
297     @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
298
299         Object message = fromSerializableMessage(originalMessage);
300
301         if (message instanceof RaftRPC) {
302             RaftRPC rpc = (RaftRPC) message;
303             // If RPC request or response contains term T > currentTerm:
304             // set currentTerm = T, convert to follower (§5.1)
305             // This applies to all RPC messages and responses
306             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
307                 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
308                         logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
309
310                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
311             }
312         }
313
314         if (message instanceof ElectionTimeout) {
315             LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
316             return switchBehavior(new Candidate(context));
317
318         } else if (message instanceof InstallSnapshot) {
319             InstallSnapshot installSnapshot = (InstallSnapshot) message;
320             handleInstallSnapshot(sender, installSnapshot);
321         }
322
323         if(message instanceof RaftRPC && (!(message instanceof RequestVote) || (canGrantVote((RequestVote) message)))){
324             scheduleElection(electionDuration());
325         }
326
327         return super.handleMessage(sender, message);
328     }
329
330     private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
331
332         LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
333                     logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
334                     installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
335
336         if(snapshotTracker == null){
337             snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
338         }
339
340         updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
341
342         try {
343             if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
344                     installSnapshot.getLastChunkHashCode())){
345                 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
346                         new ArrayList<ReplicatedLogEntry>(),
347                         installSnapshot.getLastIncludedIndex(),
348                         installSnapshot.getLastIncludedTerm(),
349                         installSnapshot.getLastIncludedIndex(),
350                         installSnapshot.getLastIncludedTerm());
351
352                 actor().tell(new ApplySnapshot(snapshot), actor());
353
354                 snapshotTracker = null;
355
356             }
357
358             InstallSnapshotReply reply = new InstallSnapshotReply(
359                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
360
361             LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
362
363             sender.tell(reply, actor());
364
365         } catch (SnapshotTracker.InvalidChunkException e) {
366             LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
367
368             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
369                     -1, false), actor());
370             snapshotTracker = null;
371
372         } catch (Exception e){
373             LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
374
375             //send reply with success as false. The chunk will be sent again on failure
376             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
377                     installSnapshot.getChunkIndex(), false), actor());
378
379         }
380     }
381
382     @Override
383     public void close() throws Exception {
384         stopElection();
385     }
386
387     @VisibleForTesting
388     SnapshotTracker getSnapshotTracker(){
389         return snapshotTracker;
390     }
391
392     private class InitialSyncStatusTracker {
393
394         private static final long INVALID_LOG_INDEX = -2L;
395         private long initialLeaderCommit = INVALID_LOG_INDEX;
396         private boolean initialSyncUpDone = false;
397         private String syncedLeaderId = null;
398         private final ActorRef actor;
399
400         public InitialSyncStatusTracker(ActorRef actor) {
401             this.actor = actor;
402         }
403
404         public void update(String leaderId, long leaderCommit, long commitIndex){
405
406             if(!leaderId.equals(syncedLeaderId)){
407                 initialSyncUpDone = false;
408                 initialLeaderCommit = INVALID_LOG_INDEX;
409                 syncedLeaderId = leaderId;
410             }
411
412             if(!initialSyncUpDone){
413                 if(initialLeaderCommit == INVALID_LOG_INDEX){
414                     actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
415                     initialLeaderCommit = leaderCommit;
416                 } else if(commitIndex >= initialLeaderCommit){
417                     actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
418                     initialSyncUpDone = true;
419                 }
420             }
421         }
422     }
423 }