2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft.behaviors;
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;
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;
43 * The behavior of a RaftActor in the Follower raft state.
45 * <li> Respond to RPCs from candidates and leaders
46 * <li> If election timeout elapses without receiving AppendEntries
47 * RPC from current leader or granting vote to candidate:
48 * convert to candidate
51 public class Follower extends AbstractRaftActorBehavior {
52 private static final int SYNC_THRESHOLD = 10;
54 private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
56 private final SyncStatusTracker initialSyncStatusTracker;
58 private final Procedure<ReplicatedLogEntry> appendAndPersistCallback =
59 logEntry -> context.getReplicatedLog().captureSnapshotIfReady(logEntry);
61 private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
62 private SnapshotTracker snapshotTracker = null;
63 private String leaderId;
64 private short leaderPayloadVersion;
66 public Follower(RaftActorContext context) {
67 this(context, null, (short)-1);
70 public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
71 super(context, RaftState.Follower);
72 this.leaderId = initialLeaderId;
73 this.leaderPayloadVersion = initialLeaderPayloadVersion;
75 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
77 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
78 actor().tell(TimeoutNow.INSTANCE, actor());
80 scheduleElection(electionDuration());
85 public final String getLeaderId() {
90 protected final void setLeaderId(@Nullable final String leaderId) {
91 this.leaderId = leaderId;
95 public short getLeaderPayloadVersion() {
96 return leaderPayloadVersion;
100 protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
101 this.leaderPayloadVersion = leaderPayloadVersion;
104 private void restartLastLeaderMessageTimer() {
105 if (lastLeaderMessageTimer.isRunning()) {
106 lastLeaderMessageTimer.reset();
109 lastLeaderMessageTimer.start();
112 private boolean isLogEntryPresent(long index) {
113 if (context.getReplicatedLog().isInSnapshot(index)) {
117 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
118 return entry != null;
122 private void updateInitialSyncStatus(long currentLeaderCommit, String newLeaderId) {
123 initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
127 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
129 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
130 if (log.isTraceEnabled()) {
131 log.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
132 } else if (log.isDebugEnabled() && numLogEntries > 0) {
133 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
136 // TODO : Refactor this method into a bunch of smaller methods
137 // to make it easier to read. Before refactoring ensure tests
138 // cover the code properly
140 if (snapshotTracker != null && !snapshotTracker.getLeaderId().equals(appendEntries.getLeaderId())) {
141 log.debug("{}: snapshot install is in progress but the prior snapshot leaderId {} does not match the "
142 + "AppendEntries leaderId {}", logName(), snapshotTracker.getLeaderId(), appendEntries.getLeaderId());
143 snapshotTracker = null;
146 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
147 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
148 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
149 lastIndex(), lastTerm(), context.getPayloadVersion());
151 log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
152 sender.tell(reply, actor());
157 // If we got here then we do appear to be talking to the leader
158 leaderId = appendEntries.getLeaderId();
159 leaderPayloadVersion = appendEntries.getPayloadVersion();
161 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
162 // First check if the logs are in sync or not
163 long lastIndex = lastIndex();
165 if (isOutOfSync(appendEntries)) {
166 // We found that the log was out of sync so just send a negative
169 log.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
170 logName(), lastIndex, lastTerm());
172 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
173 lastTerm(), context.getPayloadVersion()), actor());
177 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
179 log.debug("{}: Number of entries to be appended = {}", logName(),
180 appendEntries.getEntries().size());
182 // 3. If an existing entry conflicts with a new one (same index
183 // but different terms), delete the existing entry and all that
185 int addEntriesFrom = 0;
186 if (context.getReplicatedLog().size() > 0) {
188 // Find the entry up until 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);
192 if (!isLogEntryPresent(matchEntry.getIndex())) {
193 // newEntry not found in the log
197 long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
199 log.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
202 // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
203 // what the term was so we'll assume it matches.
204 if (existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
208 if (!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
210 log.debug("{}: Removing entries from log starting at {}", logName(),
211 matchEntry.getIndex());
213 // Entries do not match so remove all subsequent entries
214 if (!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
215 // Could not remove the entries - this means the matchEntry index must be in the
216 // snapshot and not the log. In this case the prior entries are part of the state
217 // so we must send back a reply to force a snapshot to completely re-sync the
218 // follower's log and state.
220 log.debug("{}: Could not remove entries - sending reply to force snapshot", logName());
221 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
222 lastTerm(), context.getPayloadVersion(), true), actor());
228 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
229 lastTerm(), context.getPayloadVersion(), true), actor());
235 lastIndex = lastIndex();
236 log.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
237 lastIndex, addEntriesFrom);
239 // 4. Append any new entries not already in the log
240 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
241 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
243 log.debug("{}: Append entry to log {}", logName(), entry.getData());
245 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
247 if (entry.getData() instanceof ServerConfigurationPayload) {
248 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
252 log.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
255 // 5. If leaderCommit > commitIndex, set commitIndex =
256 // min(leaderCommit, index of last new entry)
258 lastIndex = lastIndex();
259 long prevCommitIndex = context.getCommitIndex();
261 if (appendEntries.getLeaderCommit() > prevCommitIndex) {
262 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
265 if (prevCommitIndex != context.getCommitIndex()) {
266 log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
269 // If commitIndex > lastApplied: increment lastApplied, apply
270 // log[lastApplied] to state machine (§5.3)
271 // check if there are any entries to be applied. last-applied can be equal to last-index
272 if (appendEntries.getLeaderCommit() > context.getLastApplied()
273 && context.getLastApplied() < lastIndex) {
274 if (log.isDebugEnabled()) {
275 log.debug("{}: applyLogToStateMachine, appendEntries.getLeaderCommit(): {},"
276 + "context.getLastApplied(): {}, lastIndex(): {}", logName(),
277 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
280 applyLogToStateMachine(appendEntries.getLeaderCommit());
283 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
284 lastIndex, lastTerm(), context.getPayloadVersion());
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);
292 sender.tell(reply, actor());
294 if (!context.getSnapshotManager().isCapturing()) {
295 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
301 private boolean isOutOfSync(AppendEntries appendEntries) {
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;
309 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
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
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) {
319 // The follower's log is out of sync because the Leader's
320 // prevLogIndex entry was not found in it's log
322 log.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - "
323 + "lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(), lastIndex,
324 context.getReplicatedLog().getSnapshotIndex());
325 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
327 // The follower's log is out of sync because the Leader's
328 // prevLogIndex entry does exist in the follower's log but it has
329 // a different term in it
331 log.debug("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append entries"
332 + "prevLogTerm {} - lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(),
333 prevLogTerm, appendEntries.getPrevLogTerm(), lastIndex,
334 context.getReplicatedLog().getSnapshotIndex());
335 } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
336 && appendEntries.getReplicatedToAllIndex() != -1
337 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
338 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
339 // the previous entry in it's in-memory journal
341 log.debug("{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the"
342 + " in-memory journal", logName(), appendEntries.getReplicatedToAllIndex());
343 } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
344 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
345 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
346 log.debug("{}: Cannot append entries because the calculated previousIndex {} was not found in the "
347 + " in-memory journal", logName(), appendEntries.getEntries().get(0).getIndex() - 1);
355 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
356 AppendEntriesReply appendEntriesReply) {
361 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
362 RequestVoteReply requestVoteReply) {
367 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
368 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
369 return handleElectionTimeout(message);
372 if (!(message instanceof RaftRPC)) {
373 // The rest of the processing requires the message to be a RaftRPC
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());
385 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
388 if (rpc instanceof InstallSnapshot) {
389 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
390 restartLastLeaderMessageTimer();
391 scheduleElection(electionDuration());
395 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
396 restartLastLeaderMessageTimer();
397 scheduleElection(electionDuration());
400 return super.handleMessage(sender, rpc);
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;
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
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());
428 log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
429 return internalSwitchBehavior(RaftState.Candidate);
432 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
433 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
434 scheduleElection(electionDuration());
436 } else if (message instanceof ElectionTimeout) {
437 if (noLeaderMessageReceived) {
441 scheduleElection(electionDuration());
447 private boolean isLeaderAvailabilityKnown() {
448 if (leaderId == null) {
452 Optional<Cluster> cluster = context.getCluster();
453 if (!cluster.isPresent()) {
457 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
458 if (leaderActor == null) {
462 Address leaderAddress = leaderActor.anchorPath().address();
464 CurrentClusterState state = cluster.get().state();
465 Set<Member> unreachable = state.getUnreachable();
467 log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
470 for (Member m: unreachable) {
471 if (leaderAddress.equals(m.address())) {
472 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
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());
484 log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
485 leaderAddress, m.status());
491 log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
496 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
498 log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
500 leaderId = installSnapshot.getLeaderId();
502 if (snapshotTracker == null) {
503 snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
506 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
509 final InstallSnapshotReply reply = new InstallSnapshotReply(
510 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
512 if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
513 installSnapshot.getLastChunkHashCode())) {
514 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
516 installSnapshot.getLastIncludedIndex(),
517 installSnapshot.getLastIncludedTerm(),
518 installSnapshot.getLastIncludedIndex(),
519 installSnapshot.getLastIncludedTerm(),
520 context.getTermInformation().getCurrentTerm(),
521 context.getTermInformation().getVotedFor(),
522 installSnapshot.getServerConfig().orNull());
524 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
526 public void onSuccess() {
527 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
529 sender.tell(reply, actor());
533 public void onFailure() {
534 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
538 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
540 snapshotTracker = null;
542 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
544 sender.tell(reply, actor());
546 } catch (SnapshotTracker.InvalidChunkException e) {
547 log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
549 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
550 -1, false), actor());
551 snapshotTracker = null;
557 public void close() {
562 SnapshotTracker getSnapshotTracker() {
563 return snapshotTracker;