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