Fix warnings and clean up javadocs in sal-akka-raft
[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 raft 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 =
60         logEntry -> context.getReplicatedLog().captureSnapshotIfReady(logEntry);
61
62     private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
63     private SnapshotTracker snapshotTracker = null;
64     private String leaderId;
65     private short leaderPayloadVersion;
66
67     public Follower(RaftActorContext context) {
68         this(context, null, (short)-1);
69     }
70
71     public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
72         super(context, RaftState.Follower);
73         this.leaderId = initialLeaderId;
74         this.leaderPayloadVersion = initialLeaderPayloadVersion;
75
76         initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
77
78         if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
79             actor().tell(TimeoutNow.INSTANCE, actor());
80         } else {
81             scheduleElection(electionDuration());
82         }
83     }
84
85     @Override
86     public final String getLeaderId() {
87         return leaderId;
88     }
89
90     @VisibleForTesting
91     protected final void setLeaderId(@Nullable final String leaderId) {
92         this.leaderId = leaderId;
93     }
94
95     @Override
96     public short getLeaderPayloadVersion() {
97         return leaderPayloadVersion;
98     }
99
100     @VisibleForTesting
101     protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
102         this.leaderPayloadVersion = leaderPayloadVersion;
103     }
104
105     private void restartLastLeaderMessageTimer() {
106         if (lastLeaderMessageTimer.isRunning()) {
107             lastLeaderMessageTimer.reset();
108         }
109
110         lastLeaderMessageTimer.start();
111     }
112
113     private boolean isLogEntryPresent(long index) {
114         if (context.getReplicatedLog().isInSnapshot(index)) {
115             return true;
116         }
117
118         ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
119         return entry != null;
120
121     }
122
123     private void updateInitialSyncStatus(long currentLeaderCommit, String newLeaderId) {
124         initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
125     }
126
127     @Override
128     protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
129
130         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
131         if (log.isTraceEnabled()) {
132             log.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
133         } else if (log.isDebugEnabled() && numLogEntries > 0) {
134             log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
135         }
136
137         // TODO : Refactor this method into a bunch of smaller methods
138         // to make it easier to read. Before refactoring ensure tests
139         // cover the code properly
140
141         if (snapshotTracker != null && !snapshotTracker.getLeaderId().equals(appendEntries.getLeaderId())) {
142             log.debug("{}: snapshot install is in progress but the prior snapshot leaderId {} does not match the "
143                 + "AppendEntries leaderId {}", logName(), snapshotTracker.getLeaderId(), appendEntries.getLeaderId());
144             snapshotTracker = null;
145         }
146
147         if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
148             // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
149             AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
150                     lastIndex(), lastTerm(), context.getPayloadVersion());
151
152             log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
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         if (appendEntries.getLeaderCommit() > prevCommitIndex) {
263             context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
264         }
265
266         if (prevCommitIndex != context.getCommitIndex()) {
267             log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
268         }
269
270         // If commitIndex > lastApplied: increment lastApplied, apply
271         // log[lastApplied] to state machine (§5.3)
272         // check if there are any entries to be applied. last-applied can be equal to last-index
273         if (appendEntries.getLeaderCommit() > context.getLastApplied()
274                 && context.getLastApplied() < lastIndex) {
275             if (log.isDebugEnabled()) {
276                 log.debug("{}: applyLogToStateMachine, appendEntries.getLeaderCommit(): {},"
277                         + "context.getLastApplied(): {}, lastIndex(): {}", logName(),
278                     appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
279             }
280
281             applyLogToStateMachine(appendEntries.getLeaderCommit());
282         }
283
284         AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
285             lastIndex, lastTerm(), context.getPayloadVersion());
286
287         if (log.isTraceEnabled()) {
288             log.trace("{}: handleAppendEntries returning : {}", logName(), reply);
289         } else if (log.isDebugEnabled() && numLogEntries > 0) {
290             log.debug("{}: handleAppendEntries returning : {}", logName(), reply);
291         }
292
293         sender.tell(reply, actor());
294
295         if (!context.getSnapshotManager().isCapturing()) {
296             super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
297         }
298
299         return this;
300     }
301
302     private boolean isOutOfSync(AppendEntries appendEntries) {
303
304         long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
305         boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
306         long lastIndex = lastIndex();
307         int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
308         boolean outOfSync = true;
309
310         if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
311
312             // The follower's log is out of sync because the leader does have
313             // an entry at prevLogIndex and this follower has no entries in
314             // it's log.
315
316             log.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
317                         logName(), appendEntries.getPrevLogIndex());
318         } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
319
320             // The follower's log is out of sync because the Leader's
321             // prevLogIndex entry was not found in it's log
322
323             log.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - "
324                     + "lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(), lastIndex,
325                     context.getReplicatedLog().getSnapshotIndex());
326         } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
327
328             // The follower's log is out of sync because the Leader's
329             // prevLogIndex entry does exist in the follower's log but it has
330             // a different term in it
331
332             log.debug("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append entries"
333                       + "prevLogTerm {} - lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(),
334                       prevLogTerm, appendEntries.getPrevLogTerm(), lastIndex,
335                       context.getReplicatedLog().getSnapshotIndex());
336         } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
337                 && appendEntries.getReplicatedToAllIndex() != -1
338                 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
339             // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
340             // the previous entry in it's in-memory journal
341
342             log.debug("{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the"
343                     + " in-memory journal", logName(), appendEntries.getReplicatedToAllIndex());
344         } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
345                 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
346                 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
347             log.debug("{}: Cannot append entries because the calculated previousIndex {} was not found in the "
348                     + " in-memory journal", logName(), appendEntries.getEntries().get(0).getIndex() - 1);
349         } else {
350             outOfSync = false;
351         }
352         return outOfSync;
353     }
354
355     @Override
356     protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
357         AppendEntriesReply appendEntriesReply) {
358         return this;
359     }
360
361     @Override
362     protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
363         RequestVoteReply requestVoteReply) {
364         return this;
365     }
366
367     @Override
368     public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
369         if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
370             return handleElectionTimeout(message);
371         }
372
373         if (!(message instanceof RaftRPC)) {
374             // The rest of the processing requires the message to be a RaftRPC
375             return null;
376         }
377
378         final RaftRPC rpc = (RaftRPC) message;
379         // If RPC request or response contains term T > currentTerm:
380         // set currentTerm = T, convert to follower (§5.1)
381         // This applies to all RPC messages and responses
382         if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
383             log.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
384                 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
385
386             context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
387         }
388
389         if (rpc instanceof InstallSnapshot) {
390             handleInstallSnapshot(sender, (InstallSnapshot) rpc);
391             restartLastLeaderMessageTimer();
392             scheduleElection(electionDuration());
393             return this;
394         }
395
396         if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
397             restartLastLeaderMessageTimer();
398             scheduleElection(electionDuration());
399         }
400
401         return super.handleMessage(sender, rpc);
402     }
403
404     private RaftActorBehavior handleElectionTimeout(Object message) {
405         // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
406         // during the election timeout interval. It may that the election timer expired b/c this actor
407         // was busy and messages got delayed, in which case leader messages would be backed up in the
408         // queue but would be processed before the ElectionTimeout message and thus would restart the
409         // lastLeaderMessageTimer.
410         long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
411         long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
412         boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning()
413                 || lastLeaderMessageInterval >= electionTimeoutInMillis;
414
415         if (canStartElection()) {
416             if (message instanceof TimeoutNow) {
417                 log.debug("{}: Received TimeoutNow - switching to Candidate", logName());
418                 return internalSwitchBehavior(RaftState.Candidate);
419             } else if (noLeaderMessageReceived) {
420                 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
421                 // However if we haven't heard from the leader in a long time even though the cluster state
422                 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
423                 // to Candidate,
424                 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
425                 if (isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
426                     log.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
427                     scheduleElection(electionDuration());
428                 } else {
429                     log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
430                     return internalSwitchBehavior(RaftState.Candidate);
431                 }
432             } else {
433                 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
434                         logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
435                 scheduleElection(electionDuration());
436             }
437         } else if (message instanceof ElectionTimeout) {
438             if (noLeaderMessageReceived) {
439                 setLeaderId(null);
440             }
441
442             scheduleElection(electionDuration());
443         }
444
445         return this;
446     }
447
448     private boolean isLeaderAvailabilityKnown() {
449         if (leaderId == null) {
450             return false;
451         }
452
453         Optional<Cluster> cluster = context.getCluster();
454         if (!cluster.isPresent()) {
455             return false;
456         }
457
458         ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
459         if (leaderActor == null) {
460             return false;
461         }
462
463         Address leaderAddress = leaderActor.anchorPath().address();
464
465         CurrentClusterState state = cluster.get().state();
466         Set<Member> unreachable = state.getUnreachable();
467
468         log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
469                 unreachable);
470
471         for (Member m: unreachable) {
472             if (leaderAddress.equals(m.address())) {
473                 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
474                 return false;
475             }
476         }
477
478         for (Member m: state.getMembers()) {
479             if (leaderAddress.equals(m.address())) {
480                 if (m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
481                     log.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
482                             leaderAddress, m.status());
483                     return true;
484                 } else {
485                     log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
486                             leaderAddress, m.status());
487                     return false;
488                 }
489             }
490         }
491
492         log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
493
494         return false;
495     }
496
497     private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
498
499         log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
500
501         leaderId = installSnapshot.getLeaderId();
502
503         if (snapshotTracker == null) {
504             snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
505         }
506
507         updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
508
509         try {
510             final InstallSnapshotReply reply = new InstallSnapshotReply(
511                     currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
512
513             if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
514                     installSnapshot.getLastChunkHashCode())) {
515                 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
516                         new ArrayList<>(),
517                         installSnapshot.getLastIncludedIndex(),
518                         installSnapshot.getLastIncludedTerm(),
519                         installSnapshot.getLastIncludedIndex(),
520                         installSnapshot.getLastIncludedTerm(),
521                         context.getTermInformation().getCurrentTerm(),
522                         context.getTermInformation().getVotedFor(),
523                         installSnapshot.getServerConfig().orNull());
524
525                 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
526                     @Override
527                     public void onSuccess() {
528                         log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
529
530                         sender.tell(reply, actor());
531                     }
532
533                     @Override
534                     public void onFailure() {
535                         sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
536                     }
537                 };
538
539                 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
540
541                 snapshotTracker = null;
542             } else {
543                 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
544
545                 sender.tell(reply, actor());
546             }
547         } catch (SnapshotTracker.InvalidChunkException e) {
548             log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
549
550             sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
551                     -1, false), actor());
552             snapshotTracker = null;
553
554         }
555     }
556
557     @Override
558     public void close() {
559         stopElection();
560     }
561
562     @VisibleForTesting
563     SnapshotTracker getSnapshotTracker() {
564         return snapshotTracker;
565     }
566 }