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