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