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