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