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