Merge "Bug 2415: Fixed intermittent RpcRegistry unit test failures"
[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 com.google.protobuf.ByteString;
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.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.RequestVoteReply;
27
28 /**
29  * The behavior of a RaftActor in the Follower state
30  * <p/>
31  * <ul>
32  * <li> Respond to RPCs from candidates and leaders
33  * <li> If election timeout elapses without receiving AppendEntries
34  * RPC from current leader or granting vote to candidate:
35  * convert to candidate
36  * </ul>
37  */
38 public class Follower extends AbstractRaftActorBehavior {
39
40     private SnapshotTracker snapshotTracker = null;
41
42     public Follower(RaftActorContext context) {
43         super(context);
44
45         scheduleElection(electionDuration());
46     }
47
48     @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
49         AppendEntries appendEntries) {
50
51         if(appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
52             if(LOG.isDebugEnabled()) {
53                 LOG.debug(appendEntries.toString());
54             }
55         }
56
57         // TODO : Refactor this method into a bunch of smaller methods
58         // to make it easier to read. Before refactoring ensure tests
59         // cover the code properly
60
61         // 1. Reply false if term < currentTerm (§5.1)
62         // This is handled in the appendEntries method of the base class
63
64         // If we got here then we do appear to be talking to the leader
65         leaderId = appendEntries.getLeaderId();
66
67         // 2. Reply false if log doesn’t contain an entry at prevLogIndex
68         // whose term matches prevLogTerm (§5.3)
69
70         ReplicatedLogEntry previousEntry = context.getReplicatedLog()
71             .get(appendEntries.getPrevLogIndex());
72
73
74         boolean outOfSync = true;
75
76         // First check if the logs are in sync or not
77         if (lastIndex() == -1
78             && appendEntries.getPrevLogIndex() != -1) {
79
80             // The follower's log is out of sync because the leader does have
81             // an entry at prevLogIndex and this follower has no entries in
82             // it's log.
83
84             if(LOG.isDebugEnabled()) {
85                 LOG.debug("The followers log is empty and the senders prevLogIndex is {}",
86                     appendEntries.getPrevLogIndex());
87             }
88
89         } else if (lastIndex() > -1
90             && appendEntries.getPrevLogIndex() != -1
91             && previousEntry == null) {
92
93             // The follower's log is out of sync because the Leader's
94             // prevLogIndex entry was not found in it's log
95
96             if(LOG.isDebugEnabled()) {
97                 LOG.debug("The log is not empty but the prevLogIndex {} was not found in it",
98                     appendEntries.getPrevLogIndex());
99             }
100
101         } else if (lastIndex() > -1
102             && previousEntry != null
103             && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
104
105             // The follower's log is out of sync because the Leader's
106             // prevLogIndex entry does exist in the follower's log but it has
107             // a different term in it
108
109             if(LOG.isDebugEnabled()) {
110                 LOG.debug(
111                     "Cannot append entries because previous entry term {}  is not equal to append entries prevLogTerm {}"
112                     , previousEntry.getTerm()
113                     , appendEntries.getPrevLogTerm());
114             }
115         } else {
116             outOfSync = false;
117         }
118
119         if (outOfSync) {
120             // We found that the log was out of sync so just send a negative
121             // reply and return
122             if(LOG.isDebugEnabled()) {
123                 LOG.debug("Follower is out-of-sync, " +
124                         "so sending negative reply, lastIndex():{}, lastTerm():{}",
125                     lastIndex(), lastTerm()
126                 );
127             }
128             sender.tell(
129                 new AppendEntriesReply(context.getId(), currentTerm(), false,
130                     lastIndex(), lastTerm()), actor()
131             );
132             return this;
133         }
134
135         if (appendEntries.getEntries() != null
136             && appendEntries.getEntries().size() > 0) {
137             if(LOG.isDebugEnabled()) {
138                 LOG.debug(
139                     "Number of entries to be appended = {}", appendEntries.getEntries().size()
140                 );
141             }
142
143             // 3. If an existing entry conflicts with a new one (same index
144             // but different terms), delete the existing entry and all that
145             // follow it (§5.3)
146             int addEntriesFrom = 0;
147             if (context.getReplicatedLog().size() > 0) {
148
149                 // Find the entry up until which the one that is not in the follower's log
150                 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
151                     ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
152                     ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
153
154                     if (newEntry == null) {
155                         //newEntry not found in the log
156                         break;
157                     }
158
159                     if (newEntry.getTerm() == matchEntry
160                         .getTerm()) {
161                         continue;
162                     }
163
164                     if(LOG.isDebugEnabled()) {
165                         LOG.debug(
166                             "Removing entries from log starting at {}", matchEntry.getIndex()
167                         );
168                     }
169
170                     // Entries do not match so remove all subsequent entries
171                     context.getReplicatedLog()
172                         .removeFromAndPersist(matchEntry.getIndex());
173                     break;
174                 }
175             }
176
177             if(LOG.isDebugEnabled()) {
178                 LOG.debug("After cleanup entries to be added from = {}", (addEntriesFrom + lastIndex())
179                 );
180             }
181
182             // 4. Append any new entries not already in the log
183             for (int i = addEntriesFrom;
184                  i < appendEntries.getEntries().size(); i++) {
185
186                 if(LOG.isDebugEnabled()) {
187                     LOG.debug("Append entry to log {}", appendEntries.getEntries().get(i).getData());
188                 }
189                 context.getReplicatedLog().appendAndPersist(appendEntries.getEntries().get(i));
190             }
191
192             if(LOG.isDebugEnabled()) {
193                 LOG.debug("Log size is now {}", context.getReplicatedLog().size());
194             }
195         }
196
197
198         // 5. If leaderCommit > commitIndex, set commitIndex =
199         // min(leaderCommit, index of last new entry)
200
201         long prevCommitIndex = context.getCommitIndex();
202
203         context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(),
204             context.getReplicatedLog().lastIndex()));
205
206         if (prevCommitIndex != context.getCommitIndex()) {
207             if(LOG.isDebugEnabled()) {
208                 LOG.debug("Commit index set to {}", context.getCommitIndex());
209             }
210         }
211
212         // If commitIndex > lastApplied: increment lastApplied, apply
213         // log[lastApplied] to state machine (§5.3)
214         // check if there are any entries to be applied. last-applied can be equal to last-index
215         if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
216             context.getLastApplied() < lastIndex()) {
217             if(LOG.isDebugEnabled()) {
218                 LOG.debug("applyLogToStateMachine, " +
219                         "appendEntries.getLeaderCommit():{}," +
220                         "context.getLastApplied():{}, lastIndex():{}",
221                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex()
222                 );
223             }
224
225             applyLogToStateMachine(appendEntries.getLeaderCommit());
226         }
227
228         sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), true,
229             lastIndex(), lastTerm()), actor());
230
231         return this;
232     }
233
234     @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
235         AppendEntriesReply appendEntriesReply) {
236         return this;
237     }
238
239     @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
240         RequestVoteReply requestVoteReply) {
241         return this;
242     }
243
244     @Override public RaftState state() {
245         return RaftState.Follower;
246     }
247
248     @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
249
250         Object message = fromSerializableMessage(originalMessage);
251
252         if (message instanceof RaftRPC) {
253             RaftRPC rpc = (RaftRPC) message;
254             // If RPC request or response contains term T > currentTerm:
255             // set currentTerm = T, convert to follower (§5.1)
256             // This applies to all RPC messages and responses
257             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
258                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
259             }
260         }
261
262         if (message instanceof ElectionTimeout) {
263             return switchBehavior(new Candidate(context));
264
265         } else if (message instanceof InstallSnapshot) {
266             InstallSnapshot installSnapshot = (InstallSnapshot) message;
267             handleInstallSnapshot(sender, installSnapshot);
268         }
269
270         scheduleElection(electionDuration());
271
272         return super.handleMessage(sender, message);
273     }
274
275     private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
276
277         if(LOG.isDebugEnabled()) {
278             LOG.debug("InstallSnapshot received by follower " +
279                     "datasize:{} , Chunk:{}/{}", installSnapshot.getData().size(),
280                 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks()
281             );
282         }
283
284         if(snapshotTracker == null){
285             snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
286         }
287
288         try {
289             if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
290                     installSnapshot.getLastChunkHashCode())){
291                 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
292                         new ArrayList<ReplicatedLogEntry>(),
293                         installSnapshot.getLastIncludedIndex(),
294                         installSnapshot.getLastIncludedTerm(),
295                         installSnapshot.getLastIncludedIndex(),
296                         installSnapshot.getLastIncludedTerm());
297
298                 actor().tell(new ApplySnapshot(snapshot), actor());
299
300                 snapshotTracker = null;
301
302             }
303
304             sender.tell(new InstallSnapshotReply(
305                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(),
306                     true), actor());
307
308         } catch (SnapshotTracker.InvalidChunkException e) {
309
310             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
311                     -1, false), actor());
312             snapshotTracker = null;
313
314         } catch (Exception e){
315
316             LOG.error(e, "Exception in InstallSnapshot of follower:");
317             //send reply with success as false. The chunk will be sent again on failure
318             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
319                     installSnapshot.getChunkIndex(), false), actor());
320
321         }
322     }
323
324     @Override public void close() throws Exception {
325         stopElection();
326     }
327
328     @VisibleForTesting
329     ByteString getSnapshotChunksCollected(){
330         return snapshotTracker != null ? snapshotTracker.getCollectedChunks() : ByteString.EMPTY;
331     }
332
333
334 }