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