73e2cf9bc576d7831f9d12ba42cd849e7c1dea7a
[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 akka.actor.ActorSelection;
13 import akka.actor.Address;
14 import akka.cluster.Cluster;
15 import akka.cluster.ClusterEvent.CurrentClusterState;
16 import akka.cluster.Member;
17 import akka.cluster.MemberStatus;
18 import akka.japi.Procedure;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Stopwatch;
21 import java.util.ArrayList;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nullable;
26 import org.opendaylight.controller.cluster.raft.RaftActorContext;
27 import org.opendaylight.controller.cluster.raft.RaftState;
28 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
29 import org.opendaylight.controller.cluster.raft.Snapshot;
30 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
31 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
32 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
33 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
34 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
35 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
36 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
37 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
38 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
39 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
40 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
41
42 /**
43  * The behavior of a RaftActor in the Follower state
44  * <p/>
45  * <ul>
46  * <li> Respond to RPCs from candidates and leaders
47  * <li> If election timeout elapses without receiving AppendEntries
48  * RPC from current leader or granting vote to candidate:
49  * convert to candidate
50  * </ul>
51  */
52 public class Follower extends AbstractRaftActorBehavior {
53     private static final int SYNC_THRESHOLD = 10;
54
55     private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
56
57     private final SyncStatusTracker initialSyncStatusTracker;
58
59     private final Procedure<ReplicatedLogEntry> appendAndPersistCallback = new Procedure<ReplicatedLogEntry>() {
60         @Override
61         public void apply(ReplicatedLogEntry logEntry) {
62             context.getReplicatedLog().captureSnapshotIfReady(logEntry);
63         }
64     };
65
66     private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
67     private SnapshotTracker snapshotTracker = null;
68     private String leaderId;
69     private short leaderPayloadVersion;
70
71     public Follower(RaftActorContext context) {
72         this(context, null, (short)-1);
73     }
74
75     public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
76         super(context, RaftState.Follower);
77         this.leaderId = initialLeaderId;
78         this.leaderPayloadVersion = initialLeaderPayloadVersion;
79
80         initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
81
82         if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
83             actor().tell(TimeoutNow.INSTANCE, actor());
84         } else {
85             scheduleElection(electionDuration());
86         }
87     }
88
89     @Override
90     public final String getLeaderId() {
91         return leaderId;
92     }
93
94     @VisibleForTesting
95     protected final void setLeaderId(@Nullable final String leaderId) {
96         this.leaderId = leaderId;
97     }
98
99     @Override
100     public short getLeaderPayloadVersion() {
101         return leaderPayloadVersion;
102     }
103
104     @VisibleForTesting
105     protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
106         this.leaderPayloadVersion = leaderPayloadVersion;
107     }
108
109     private void restartLastLeaderMessageTimer() {
110         if (lastLeaderMessageTimer.isRunning()) {
111             lastLeaderMessageTimer.reset();
112         }
113
114         lastLeaderMessageTimer.start();
115     }
116
117     private boolean isLogEntryPresent(long index){
118         if(context.getReplicatedLog().isInSnapshot(index)) {
119             return true;
120         }
121
122         ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
123         return entry != null;
124
125     }
126
127     private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
128         initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
129     }
130
131     @Override
132     protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
133
134         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
135         if(LOG.isTraceEnabled()) {
136             LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
137         } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
138             LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
139         }
140
141         // TODO : Refactor this method into a bunch of smaller methods
142         // to make it easier to read. Before refactoring ensure tests
143         // cover the code properly
144
145         if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
146             // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
147             AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
148                     lastIndex(), lastTerm(), context.getPayloadVersion());
149
150             if(LOG.isDebugEnabled()) {
151                 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
152             }
153             sender.tell(reply, actor());
154
155             return this;
156         }
157
158         // If we got here then we do appear to be talking to the leader
159         leaderId = appendEntries.getLeaderId();
160         leaderPayloadVersion = appendEntries.getPayloadVersion();
161
162         updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
163         // First check if the logs are in sync or not
164         long lastIndex = lastIndex();
165
166         if (isOutOfSync(appendEntries)) {
167             // We found that the log was out of sync so just send a negative
168             // reply and return
169
170             LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
171                         logName(), lastIndex, lastTerm());
172
173             sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
174                     lastTerm(), context.getPayloadVersion()), actor());
175             return this;
176         }
177
178         if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
179
180             LOG.debug("{}: Number of entries to be appended = {}", logName(),
181                         appendEntries.getEntries().size());
182
183             // 3. If an existing entry conflicts with a new one (same index
184             // but different terms), delete the existing entry and all that
185             // follow it (§5.3)
186             int addEntriesFrom = 0;
187             if (context.getReplicatedLog().size() > 0) {
188
189                 // Find the entry up until the one that is not in the follower's log
190                 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
191                     ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
192
193                     if(!isLogEntryPresent(matchEntry.getIndex())) {
194                         // newEntry not found in the log
195                         break;
196                     }
197
198                     long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
199
200                     LOG.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
201                             existingEntryTerm);
202
203                     // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
204                     // what the term was so we'll assume it matches.
205                     if(existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
206                         continue;
207                     }
208
209                     if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
210
211                         LOG.debug("{}: Removing entries from log starting at {}", logName(),
212                                 matchEntry.getIndex());
213
214                         // Entries do not match so remove all subsequent entries
215                         if(!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
216                             // Could not remove the entries - this means the matchEntry index must be in the
217                             // snapshot and not the log. In this case the prior entries are part of the state
218                             // so we must send back a reply to force a snapshot to completely re-sync the
219                             // follower's log and state.
220
221                             LOG.debug("{}: Could not remove entries - sending reply to force snapshot", logName());
222                             sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
223                                     lastTerm(), context.getPayloadVersion(), true), actor());
224                             return this;
225                         }
226
227                         break;
228                     } else {
229                         sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
230                                 lastTerm(), context.getPayloadVersion(), true), actor());
231                         return this;
232                     }
233                 }
234             }
235
236             lastIndex = lastIndex();
237             LOG.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
238                     lastIndex, addEntriesFrom);
239
240             // 4. Append any new entries not already in the log
241             for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
242                 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
243
244                 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
245
246                 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
247
248                 if(entry.getData() instanceof ServerConfigurationPayload) {
249                     context.updatePeerIds((ServerConfigurationPayload)entry.getData());
250                 }
251             }
252
253             LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
254         }
255
256         // 5. If leaderCommit > commitIndex, set commitIndex =
257         // min(leaderCommit, index of last new entry)
258
259         lastIndex = lastIndex();
260         long prevCommitIndex = context.getCommitIndex();
261
262         context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
263
264         if (prevCommitIndex != context.getCommitIndex()) {
265             LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
266         }
267
268         // If commitIndex > lastApplied: increment lastApplied, apply
269         // log[lastApplied] to state machine (§5.3)
270         // check if there are any entries to be applied. last-applied can be equal to last-index
271         if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
272             context.getLastApplied() < lastIndex) {
273             if(LOG.isDebugEnabled()) {
274                 LOG.debug("{}: applyLogToStateMachine, " +
275                         "appendEntries.getLeaderCommit(): {}," +
276                         "context.getLastApplied(): {}, lastIndex(): {}", logName(),
277                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
278             }
279
280             applyLogToStateMachine(appendEntries.getLeaderCommit());
281         }
282
283         AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
284             lastIndex, lastTerm(), context.getPayloadVersion());
285
286         if(LOG.isTraceEnabled()) {
287             LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
288         } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
289             LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
290         }
291
292         sender.tell(reply, actor());
293
294         if (!context.getSnapshotManager().isCapturing()) {
295             super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
296         }
297
298         return this;
299     }
300
301     private boolean isOutOfSync(AppendEntries appendEntries) {
302
303         long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
304         boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
305         long lastIndex = lastIndex();
306         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
307         boolean outOfSync = true;
308
309         if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
310
311             // The follower's log is out of sync because the leader does have
312             // an entry at prevLogIndex and this follower has no entries in
313             // it's log.
314
315             LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
316                         logName(), appendEntries.getPrevLogIndex());
317         } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
318
319             // The follower's log is out of sync because the Leader's
320             // prevLogIndex entry was not found in it's log
321
322             LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
323                         logName(), appendEntries.getPrevLogIndex(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
324         } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
325
326             // The follower's log is out of sync because the Leader's
327             // prevLogIndex entry does exist in the follower's log but it has
328             // a different term in it
329
330             LOG.debug(
331                     "{}: Cannot append entries because previous entry term {}  is not equal to append entries prevLogTerm {}",
332                     logName(), prevLogTerm, appendEntries.getPrevLogTerm());
333         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
334                 && appendEntries.getReplicatedToAllIndex() != -1
335                 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
336             // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
337             // the previous entry in it's in-memory journal
338
339             LOG.debug(
340                     "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
341                     logName(), appendEntries.getReplicatedToAllIndex());
342         } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
343                 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
344                 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
345             LOG.debug(
346                     "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
347                     logName(), appendEntries.getEntries().get(0).getIndex() - 1);
348         } else {
349             outOfSync = false;
350         }
351         return outOfSync;
352     }
353
354     @Override
355     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
356         AppendEntriesReply appendEntriesReply) {
357         return this;
358     }
359
360     @Override
361     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
362         RequestVoteReply requestVoteReply) {
363         return this;
364     }
365
366     @Override
367     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
368         if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
369             return handleElectionTimeout(message);
370         }
371
372         if (!(message instanceof RaftRPC)) {
373             // The rest of the processing requires the message to be a RaftRPC
374             return null;
375         }
376
377         final RaftRPC rpc = (RaftRPC) message;
378         // If RPC request or response contains term T > currentTerm:
379         // set currentTerm = T, convert to follower (§5.1)
380         // This applies to all RPC messages and responses
381         if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
382             LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
383                 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
384
385             context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
386         }
387
388         if (rpc instanceof InstallSnapshot) {
389             handleInstallSnapshot(sender, (InstallSnapshot) rpc);
390             restartLastLeaderMessageTimer();
391             scheduleElection(electionDuration());
392             return this;
393         }
394
395         if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
396             restartLastLeaderMessageTimer();
397             scheduleElection(electionDuration());
398         }
399
400         return super.handleMessage(sender, rpc);
401     }
402
403     private RaftActorBehavior handleElectionTimeout(Object message) {
404         // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
405         // during the election timeout interval. It may that the election timer expired b/c this actor
406         // was busy and messages got delayed, in which case leader messages would be backed up in the
407         // queue but would be processed before the ElectionTimeout message and thus would restart the
408         // lastLeaderMessageTimer.
409         long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
410         long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
411         boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning() ||
412                 lastLeaderMessageInterval >= electionTimeoutInMillis;
413
414         if(canStartElection()) {
415             if(message instanceof TimeoutNow) {
416                 LOG.debug("{}: Received TimeoutNow - switching to Candidate", logName());
417                 return internalSwitchBehavior(RaftState.Candidate);
418             } else if(noLeaderMessageReceived) {
419                 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
420                 // However if we haven't heard from the leader in a long time even though the cluster state
421                 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
422                 // to Candidate,
423                 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
424                 if(isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
425                     LOG.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
426                     scheduleElection(electionDuration());
427                 } else {
428                     LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
429                     return internalSwitchBehavior(RaftState.Candidate);
430                 }
431             } else {
432                 LOG.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
433                         logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
434                 scheduleElection(electionDuration());
435             }
436         } else if(message instanceof ElectionTimeout) {
437             if(noLeaderMessageReceived) {
438                 setLeaderId(null);
439             }
440
441             scheduleElection(electionDuration());
442         }
443
444         return this;
445     }
446
447     private boolean isLeaderAvailabilityKnown() {
448         if(leaderId == null) {
449             return false;
450         }
451
452         Optional<Cluster> cluster = context.getCluster();
453         if(!cluster.isPresent()) {
454             return false;
455         }
456
457         ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
458         if(leaderActor == null) {
459             return false;
460         }
461
462         Address leaderAddress = leaderActor.anchorPath().address();
463
464         CurrentClusterState state = cluster.get().state();
465         Set<Member> unreachable = state.getUnreachable();
466
467         LOG.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
468                 unreachable);
469
470         for(Member m: unreachable) {
471             if(leaderAddress.equals(m.address())) {
472                 LOG.info("{}: Leader {} is unreachable", logName(), leaderAddress);
473                 return false;
474             }
475         }
476
477         for(Member m: state.getMembers()) {
478             if(leaderAddress.equals(m.address())) {
479                 if(m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
480                     LOG.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
481                             leaderAddress, m.status());
482                     return true;
483                 } else {
484                     LOG.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
485                             leaderAddress, m.status());
486                     return false;
487                 }
488             }
489         }
490
491         LOG.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
492
493         return false;
494     }
495
496     private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
497
498         LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
499
500         leaderId = installSnapshot.getLeaderId();
501
502         if(snapshotTracker == null){
503             snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
504         }
505
506         updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
507
508         try {
509             final InstallSnapshotReply reply = new InstallSnapshotReply(
510                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
511
512             if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
513                     installSnapshot.getLastChunkHashCode())){
514                 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
515                         new ArrayList<ReplicatedLogEntry>(),
516                         installSnapshot.getLastIncludedIndex(),
517                         installSnapshot.getLastIncludedTerm(),
518                         installSnapshot.getLastIncludedIndex(),
519                         installSnapshot.getLastIncludedTerm(),
520                         context.getTermInformation().getCurrentTerm(),
521                         context.getTermInformation().getVotedFor(),
522                         installSnapshot.getServerConfig().orNull());
523
524                 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
525                     @Override
526                     public void onSuccess() {
527                         LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
528
529                         sender.tell(reply, actor());
530                     }
531
532                     @Override
533                     public void onFailure() {
534                         sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
535                     }
536                 };
537
538                 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
539
540                 snapshotTracker = null;
541             } else {
542                 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
543
544                 sender.tell(reply, actor());
545             }
546         } catch (SnapshotTracker.InvalidChunkException e) {
547             LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
548
549             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
550                     -1, false), actor());
551             snapshotTracker = null;
552
553         } catch (Exception e){
554             LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
555
556             //send reply with success as false. The chunk will be sent again on failure
557             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
558                     installSnapshot.getChunkIndex(), false), actor());
559
560         }
561     }
562
563     @Override
564     public void close() {
565         stopElection();
566     }
567
568     @VisibleForTesting
569     SnapshotTracker getSnapshotTracker(){
570         return snapshotTracker;
571     }
572 }