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.io.IOException;
22 import java.util.ArrayList;
23 import java.util.Optional;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicBoolean;
27 import javax.annotation.Nullable;
28 import org.opendaylight.controller.cluster.raft.RaftActorContext;
29 import org.opendaylight.controller.cluster.raft.RaftState;
30 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
32 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
33 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
34 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
35 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
36 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
37 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
38 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
39 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
40 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
41 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
42 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
45 * The behavior of a RaftActor in the Follower raft state.
47 * <li> Respond to RPCs from candidates and leaders
48 * <li> If election timeout elapses without receiving AppendEntries
49 * RPC from current leader or granting vote to candidate:
50 * convert to candidate
53 public class Follower extends AbstractRaftActorBehavior {
54 private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
56 private final SyncStatusTracker initialSyncStatusTracker;
58 private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
59 private SnapshotTracker snapshotTracker = null;
60 private String leaderId;
61 private short leaderPayloadVersion;
63 public Follower(final RaftActorContext context) {
64 this(context, null, (short)-1);
67 public Follower(final RaftActorContext context, final String initialLeaderId,
68 final short initialLeaderPayloadVersion) {
69 super(context, RaftState.Follower);
70 this.leaderId = initialLeaderId;
71 this.leaderPayloadVersion = initialLeaderPayloadVersion;
73 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), context.getConfigParams()
74 .getSyncIndexThreshold());
76 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
77 actor().tell(TimeoutNow.INSTANCE, actor());
79 scheduleElection(electionDuration());
84 public final String getLeaderId() {
89 protected final void setLeaderId(@Nullable final String leaderId) {
90 this.leaderId = leaderId;
94 public short getLeaderPayloadVersion() {
95 return leaderPayloadVersion;
99 protected final void setLeaderPayloadVersion(final short leaderPayloadVersion) {
100 this.leaderPayloadVersion = leaderPayloadVersion;
103 private void restartLastLeaderMessageTimer() {
104 if (lastLeaderMessageTimer.isRunning()) {
105 lastLeaderMessageTimer.reset();
108 lastLeaderMessageTimer.start();
111 private boolean isLogEntryPresent(final long index) {
112 if (context.getReplicatedLog().isInSnapshot(index)) {
116 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
117 return entry != null;
121 private void updateInitialSyncStatus(final long currentLeaderCommit, final String newLeaderId) {
122 initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
126 protected RaftActorBehavior handleAppendEntries(final ActorRef sender, final AppendEntries appendEntries) {
128 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
129 if (log.isTraceEnabled()) {
130 log.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
131 } else if (log.isDebugEnabled() && numLogEntries > 0) {
132 log.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
135 // TODO : Refactor this method into a bunch of smaller methods
136 // to make it easier to read. Before refactoring ensure tests
137 // cover the code properly
139 if (snapshotTracker != null && !snapshotTracker.getLeaderId().equals(appendEntries.getLeaderId())) {
140 log.debug("{}: snapshot install is in progress but the prior snapshot leaderId {} does not match the "
141 + "AppendEntries leaderId {}", logName(), snapshotTracker.getLeaderId(), appendEntries.getLeaderId());
142 closeSnapshotTracker();
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());
150 log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
151 sender.tell(reply, actor());
156 // If we got here then we do appear to be talking to the leader
157 leaderId = appendEntries.getLeaderId();
158 leaderPayloadVersion = appendEntries.getPayloadVersion();
160 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
161 // First check if the logs are in sync or not
162 long lastIndex = lastIndex();
164 if (isOutOfSync(appendEntries)) {
165 // We found that the log was out of sync so just send a negative
168 final AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
169 lastTerm(), context.getPayloadVersion());
171 log.info("{}: Follower is out-of-sync so sending negative reply: {}", logName(), reply);
173 sender.tell(reply, 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.info("{}: Removing entries from log starting at {}", logName(), matchEntry.getIndex());
212 // Entries do not match so remove all subsequent entries
213 if (!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
214 // Could not remove the entries - this means the matchEntry index must be in the
215 // snapshot and not the log. In this case the prior entries are part of the state
216 // so we must send back a reply to force a snapshot to completely re-sync the
217 // follower's log and state.
219 log.info("{}: Could not remove entries - sending reply to force snapshot", logName());
220 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
221 lastTerm(), context.getPayloadVersion(), true), actor());
227 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
228 lastTerm(), context.getPayloadVersion(), true), actor());
234 lastIndex = lastIndex();
235 log.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
236 lastIndex, addEntriesFrom);
238 // When persistence successfully completes for each new log entry appended, we need to determine if we
239 // should capture a snapshot to compact the persisted log. shouldCaptureSnapshot tracks whether or not
240 // one of the log entries has exceeded the log size threshold whereby a snapshot should be taken. However
241 // we don't initiate the snapshot at that log entry but rather after the last log entry has been persisted.
242 // This is done because subsequent log entries after the one that tripped the threshold may have been
243 // applied to the state already, as the persistence callback occurs async, and we want those entries
244 // purged from the persisted log as well.
245 final AtomicBoolean shouldCaptureSnapshot = new AtomicBoolean(false);
246 final Procedure<ReplicatedLogEntry> appendAndPersistCallback = logEntry -> {
247 final ReplicatedLogEntry lastEntryToAppend = appendEntries.getEntries().get(
248 appendEntries.getEntries().size() - 1);
249 if (shouldCaptureSnapshot.get() && logEntry == lastEntryToAppend) {
250 context.getSnapshotManager().capture(context.getReplicatedLog().last(), getReplicatedToAllIndex());
254 // 4. Append any new entries not already in the log
255 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
256 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
258 log.debug("{}: Append entry to log {}", logName(), entry.getData());
260 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback, false);
262 shouldCaptureSnapshot.compareAndSet(false,
263 context.getReplicatedLog().shouldCaptureSnapshot(entry.getIndex()));
265 if (entry.getData() instanceof ServerConfigurationPayload) {
266 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
270 log.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
273 // 5. If leaderCommit > commitIndex, set commitIndex =
274 // min(leaderCommit, index of last new entry)
276 lastIndex = lastIndex();
277 long prevCommitIndex = context.getCommitIndex();
279 if (appendEntries.getLeaderCommit() > prevCommitIndex) {
280 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
283 if (prevCommitIndex != context.getCommitIndex()) {
284 log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
287 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
288 lastIndex, lastTerm(), context.getPayloadVersion());
290 if (log.isTraceEnabled()) {
291 log.trace("{}: handleAppendEntries returning : {}", logName(), reply);
292 } else if (log.isDebugEnabled() && numLogEntries > 0) {
293 log.debug("{}: handleAppendEntries returning : {}", logName(), reply);
296 // Reply to the leader before applying any previous state so as not to hold up leader consensus.
297 sender.tell(reply, actor());
299 // If commitIndex > lastApplied: increment lastApplied, apply
300 // log[lastApplied] to state machine (§5.3)
301 // check if there are any entries to be applied. last-applied can be equal to last-index
302 if (appendEntries.getLeaderCommit() > context.getLastApplied()
303 && context.getLastApplied() < lastIndex) {
304 if (log.isDebugEnabled()) {
305 log.debug("{}: applyLogToStateMachine, appendEntries.getLeaderCommit(): {},"
306 + "context.getLastApplied(): {}, lastIndex(): {}", logName(),
307 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
310 applyLogToStateMachine(appendEntries.getLeaderCommit());
313 if (!context.getSnapshotManager().isCapturing()) {
314 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
320 private boolean isOutOfSync(final AppendEntries appendEntries) {
322 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
323 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
324 long lastIndex = lastIndex();
325 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
326 boolean outOfSync = true;
328 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
330 // The follower's log is out of sync because the leader does have
331 // an entry at prevLogIndex and this follower has no entries in
334 log.info("{}: The followers log is empty and the senders prevLogIndex is {}",
335 logName(), appendEntries.getPrevLogIndex());
336 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
338 // The follower's log is out of sync because the Leader's
339 // prevLogIndex entry was not found in it's log
341 log.info("{}: The log is not empty but the prevLogIndex {} was not found in it - "
342 + "lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(), lastIndex,
343 context.getReplicatedLog().getSnapshotIndex());
344 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
346 // The follower's log is out of sync because the Leader's
347 // prevLogIndex entry does exist in the follower's log but it has
348 // a different term in it
350 log.info("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append entries"
351 + "prevLogTerm {} - lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(),
352 prevLogTerm, appendEntries.getPrevLogTerm(), lastIndex,
353 context.getReplicatedLog().getSnapshotIndex());
354 } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
355 && appendEntries.getReplicatedToAllIndex() != -1
356 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
357 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
358 // the previous entry in it's in-memory journal
360 log.info("{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the"
361 + " in-memory journal", logName(), appendEntries.getReplicatedToAllIndex());
362 } else if (appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
363 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
364 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
365 log.info("{}: Cannot append entries because the calculated previousIndex {} was not found in the "
366 + " in-memory journal", logName(), appendEntries.getEntries().get(0).getIndex() - 1);
374 protected RaftActorBehavior handleAppendEntriesReply(final ActorRef sender,
375 final AppendEntriesReply appendEntriesReply) {
380 protected RaftActorBehavior handleRequestVoteReply(final ActorRef sender,
381 final RequestVoteReply requestVoteReply) {
386 public RaftActorBehavior handleMessage(final ActorRef sender, final Object message) {
387 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
388 return handleElectionTimeout(message);
391 if (!(message instanceof RaftRPC)) {
392 // The rest of the processing requires the message to be a RaftRPC
396 final RaftRPC rpc = (RaftRPC) message;
397 // If RPC request or response contains term T > currentTerm:
398 // set currentTerm = T, convert to follower (§5.1)
399 // This applies to all RPC messages and responses
400 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
401 log.info("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
402 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
404 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
407 if (rpc instanceof InstallSnapshot) {
408 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
409 restartLastLeaderMessageTimer();
410 scheduleElection(electionDuration());
414 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
415 restartLastLeaderMessageTimer();
416 scheduleElection(electionDuration());
419 return super.handleMessage(sender, rpc);
422 private RaftActorBehavior handleElectionTimeout(final Object message) {
423 // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
424 // during the election timeout interval. It may that the election timer expired b/c this actor
425 // was busy and messages got delayed, in which case leader messages would be backed up in the
426 // queue but would be processed before the ElectionTimeout message and thus would restart the
427 // lastLeaderMessageTimer.
428 long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
429 long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
430 boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning()
431 || lastLeaderMessageInterval >= electionTimeoutInMillis;
433 if (canStartElection()) {
434 if (message instanceof TimeoutNow) {
435 log.debug("{}: Received TimeoutNow - switching to Candidate", logName());
436 return internalSwitchBehavior(RaftState.Candidate);
437 } else if (noLeaderMessageReceived) {
438 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
439 // However if we haven't heard from the leader in a long time even though the cluster state
440 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
442 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
443 if (isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
444 log.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
445 scheduleElection(electionDuration());
447 log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
448 return internalSwitchBehavior(RaftState.Candidate);
451 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
452 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
453 scheduleElection(electionDuration());
455 } else if (message instanceof ElectionTimeout) {
456 if (noLeaderMessageReceived) {
460 scheduleElection(electionDuration());
466 private boolean isLeaderAvailabilityKnown() {
467 if (leaderId == null) {
471 Optional<Cluster> cluster = context.getCluster();
472 if (!cluster.isPresent()) {
476 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
477 if (leaderActor == null) {
481 Address leaderAddress = leaderActor.anchorPath().address();
483 CurrentClusterState state = cluster.get().state();
484 Set<Member> unreachable = state.getUnreachable();
486 log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
489 for (Member m: unreachable) {
490 if (leaderAddress.equals(m.address())) {
491 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
496 for (Member m: state.getMembers()) {
497 if (leaderAddress.equals(m.address())) {
498 if (m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
499 log.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
500 leaderAddress, m.status());
503 log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
504 leaderAddress, m.status());
510 log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
515 private void handleInstallSnapshot(final ActorRef sender, final InstallSnapshot installSnapshot) {
517 log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
519 leaderId = installSnapshot.getLeaderId();
521 if (snapshotTracker == null) {
522 snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId(),
526 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
529 final InstallSnapshotReply reply = new InstallSnapshotReply(
530 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
532 if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
533 installSnapshot.getLastChunkHashCode())) {
535 log.info("{}: Snapshot installed from leader: {}", logName(), installSnapshot.getLeaderId());
537 Snapshot snapshot = Snapshot.create(
538 context.getSnapshotManager().convertSnapshot(snapshotTracker.getSnapshotBytes()),
540 installSnapshot.getLastIncludedIndex(),
541 installSnapshot.getLastIncludedTerm(),
542 installSnapshot.getLastIncludedIndex(),
543 installSnapshot.getLastIncludedTerm(),
544 context.getTermInformation().getCurrentTerm(),
545 context.getTermInformation().getVotedFor(),
546 installSnapshot.getServerConfig().orNull());
548 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
550 public void onSuccess() {
551 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
553 sender.tell(reply, actor());
557 public void onFailure() {
558 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
562 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
564 closeSnapshotTracker();
566 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
568 sender.tell(reply, actor());
570 } catch (IOException e) {
571 log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
573 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
574 -1, false), actor());
576 closeSnapshotTracker();
580 private void closeSnapshotTracker() {
581 if (snapshotTracker != null) {
582 snapshotTracker.close();
583 snapshotTracker = null;
588 public void close() {
589 closeSnapshotTracker();
594 SnapshotTracker getSnapshotTracker() {
595 return snapshotTracker;