Merge "Serialization/Deserialization and a host of other fixes"
[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 org.opendaylight.controller.cluster.raft.RaftActorContext;
13 import org.opendaylight.controller.cluster.raft.RaftState;
14 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
15 import org.opendaylight.controller.cluster.raft.internal.messages.ApplySnapshot;
16 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
18 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
19 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
20 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
21 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
22
23 /**
24  * The behavior of a RaftActor in the Follower state
25  * <p/>
26  * <ul>
27  * <li> Respond to RPCs from candidates and leaders
28  * <li> If election timeout elapses without receiving AppendEntries
29  * RPC from current leader or granting vote to candidate:
30  * convert to candidate
31  * </ul>
32  */
33 public class Follower extends AbstractRaftActorBehavior {
34     public Follower(RaftActorContext context) {
35         super(context);
36
37         scheduleElection(electionDuration());
38     }
39
40     @Override protected RaftState handleAppendEntries(ActorRef sender,
41         AppendEntries appendEntries) {
42
43         // TODO : Refactor this method into a bunch of smaller methods
44         // to make it easier to read. Before refactoring ensure tests
45         // cover the code properly
46
47         // 1. Reply false if term < currentTerm (§5.1)
48         // This is handled in the appendEntries method of the base class
49
50         // If we got here then we do appear to be talking to the leader
51         leaderId = appendEntries.getLeaderId();
52
53         // 2. Reply false if log doesn’t contain an entry at prevLogIndex
54         // whose term matches prevLogTerm (§5.3)
55
56         ReplicatedLogEntry previousEntry = context.getReplicatedLog()
57             .get(appendEntries.getPrevLogIndex());
58
59
60         boolean outOfSync = true;
61
62         // First check if the logs are in sync or not
63         if (lastIndex() == -1
64             && appendEntries.getPrevLogIndex() != -1) {
65
66             // The follower's log is out of sync because the leader does have
67             // an entry at prevLogIndex and this follower has no entries in
68             // it's log.
69
70             context.getLogger().debug(
71                 "The followers log is empty and the senders prevLogIndex is {}",
72                 appendEntries.getPrevLogIndex());
73
74         } else if (lastIndex() > -1
75             && appendEntries.getPrevLogIndex() != -1
76             && previousEntry == null) {
77
78             // The follower's log is out of sync because the Leader's
79             // prevLogIndex entry was not found in it's log
80
81             context.getLogger().debug(
82                 "The log is not empty but the prevLogIndex {} was not found in it",
83                 appendEntries.getPrevLogIndex());
84
85         } else if (lastIndex() > -1
86             && previousEntry != null
87             && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
88
89             // The follower's log is out of sync because the Leader's
90             // prevLogIndex entry does exist in the follower's log but it has
91             // a different term in it
92
93             context.getLogger().debug(
94                 "Cannot append entries because previous entry term {}  is not equal to append entries prevLogTerm {}"
95                 , previousEntry.getTerm()
96                 , appendEntries.getPrevLogTerm());
97         } else {
98             outOfSync = false;
99         }
100
101         if (outOfSync) {
102             // We found that the log was out of sync so just send a negative
103             // reply and return
104             sender.tell(
105                 new AppendEntriesReply(context.getId(), currentTerm(), false,
106                     lastIndex(), lastTerm()), actor()
107             );
108             return state();
109         }
110
111         if (appendEntries.getEntries() != null
112             && appendEntries.getEntries().size() > 0) {
113             context.getLogger().debug(
114                 "Number of entries to be appended = " + appendEntries
115                     .getEntries().size()
116             );
117
118             // 3. If an existing entry conflicts with a new one (same index
119             // but different terms), delete the existing entry and all that
120             // follow it (§5.3)
121             int addEntriesFrom = 0;
122             if (context.getReplicatedLog().size() > 0) {
123
124                 // Find the entry up until which the one that is not in the
125                 // follower's log
126                 for (int i = 0;
127                      i < appendEntries.getEntries()
128                          .size(); i++, addEntriesFrom++) {
129                     ReplicatedLogEntry matchEntry =
130                         appendEntries.getEntries().get(i);
131                     ReplicatedLogEntry newEntry = context.getReplicatedLog()
132                         .get(matchEntry.getIndex());
133
134                     if (newEntry == null) {
135                         //newEntry not found in the log
136                         break;
137                     }
138
139                     if (newEntry.getTerm() == matchEntry
140                         .getTerm()) {
141                         continue;
142                     }
143
144                     context.getLogger().debug(
145                         "Removing entries from log starting at "
146                             + matchEntry.getIndex()
147                     );
148
149                     // Entries do not match so remove all subsequent entries
150                     context.getReplicatedLog()
151                         .removeFromAndPersist(matchEntry.getIndex());
152                     break;
153                 }
154             }
155
156             context.getLogger().debug(
157                 "After cleanup entries to be added from = " + (addEntriesFrom
158                     + lastIndex())
159             );
160
161             // 4. Append any new entries not already in the log
162             for (int i = addEntriesFrom;
163                  i < appendEntries.getEntries().size(); i++) {
164
165                 context.getLogger().debug(
166                     "Append entry to log " + appendEntries.getEntries().get(i).getData()
167                         .toString()
168                 );
169                 context.getReplicatedLog()
170                     .appendAndPersist(appendEntries.getEntries().get(i));
171             }
172
173             context.getLogger().debug(
174                 "Log size is now " + context.getReplicatedLog().size());
175         }
176
177
178         // 5. If leaderCommit > commitIndex, set commitIndex =
179         // min(leaderCommit, index of last new entry)
180
181         long prevCommitIndex = context.getCommitIndex();
182
183         context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(),
184             context.getReplicatedLog().lastIndex()));
185
186         if (prevCommitIndex != context.getCommitIndex()) {
187             context.getLogger()
188                 .debug("Commit index set to " + context.getCommitIndex());
189         }
190
191         // If commitIndex > lastApplied: increment lastApplied, apply
192         // log[lastApplied] to state machine (§5.3)
193         if (appendEntries.getLeaderCommit() > context.getLastApplied()) {
194             applyLogToStateMachine(appendEntries.getLeaderCommit());
195         }
196
197         sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), true,
198             lastIndex(), lastTerm()), actor());
199
200         return state();
201     }
202
203     @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
204         AppendEntriesReply appendEntriesReply) {
205         return state();
206     }
207
208     @Override protected RaftState handleRequestVoteReply(ActorRef sender,
209         RequestVoteReply requestVoteReply) {
210         return state();
211     }
212
213     @Override public RaftState state() {
214         return RaftState.Follower;
215     }
216
217     @Override public RaftState handleMessage(ActorRef sender, Object message) {
218         if (message instanceof RaftRPC) {
219             RaftRPC rpc = (RaftRPC) message;
220             // If RPC request or response contains term T > currentTerm:
221             // set currentTerm = T, convert to follower (§5.1)
222             // This applies to all RPC messages and responses
223             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
224                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
225             }
226         }
227
228         if (message instanceof ElectionTimeout) {
229             return RaftState.Candidate;
230         } else if (message instanceof InstallSnapshot) {
231             InstallSnapshot snapshot = (InstallSnapshot) message;
232             actor().tell(new ApplySnapshot(snapshot), actor());
233         }
234
235         scheduleElection(electionDuration());
236
237         return super.handleMessage(sender, message);
238     }
239
240     @Override public void close() throws Exception {
241         stopElection();
242     }
243 }