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.
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
52 public class Follower extends AbstractRaftActorBehavior {
53 private static final int SYNC_THRESHOLD = 10;
55 private static final long MAX_ELECTION_TIMEOUT_FACTOR = 18;
57 private final SyncStatusTracker initialSyncStatusTracker;
59 private final Procedure<ReplicatedLogEntry> appendAndPersistCallback =
60 logEntry -> context.getReplicatedLog().captureSnapshotIfReady(logEntry);
62 private final Stopwatch lastLeaderMessageTimer = Stopwatch.createStarted();
63 private SnapshotTracker snapshotTracker = null;
64 private String leaderId;
65 private short leaderPayloadVersion;
67 public Follower(RaftActorContext context) {
68 this(context, null, (short)-1);
71 public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
72 super(context, RaftState.Follower);
73 this.leaderId = initialLeaderId;
74 this.leaderPayloadVersion = initialLeaderPayloadVersion;
76 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
78 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
79 actor().tell(TimeoutNow.INSTANCE, actor());
81 scheduleElection(electionDuration());
86 public final String getLeaderId() {
91 protected final void setLeaderId(@Nullable final String leaderId) {
92 this.leaderId = leaderId;
96 public short getLeaderPayloadVersion() {
97 return leaderPayloadVersion;
101 protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
102 this.leaderPayloadVersion = leaderPayloadVersion;
105 private void restartLastLeaderMessageTimer() {
106 if (lastLeaderMessageTimer.isRunning()) {
107 lastLeaderMessageTimer.reset();
110 lastLeaderMessageTimer.start();
113 private boolean isLogEntryPresent(long index) {
114 if (context.getReplicatedLog().isInSnapshot(index)) {
118 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
119 return entry != null;
123 private void updateInitialSyncStatus(long currentLeaderCommit, String newLeaderId) {
124 initialSyncStatusTracker.update(newLeaderId, currentLeaderCommit, context.getCommitIndex());
128 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
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);
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
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;
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());
152 log.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
153 sender.tell(reply, actor());
158 // If we got here then we do appear to be talking to the leader
159 leaderId = appendEntries.getLeaderId();
160 leaderPayloadVersion = appendEntries.getPayloadVersion();
162 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
163 // First check if the logs are in sync or not
164 long lastIndex = lastIndex();
166 if (isOutOfSync(appendEntries)) {
167 // We found that the log was out of sync so just send a negative
170 log.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
171 logName(), lastIndex, lastTerm());
173 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
174 lastTerm(), context.getPayloadVersion()), actor());
178 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
180 log.debug("{}: Number of entries to be appended = {}", logName(),
181 appendEntries.getEntries().size());
183 // 3. If an existing entry conflicts with a new one (same index
184 // but different terms), delete the existing entry and all that
186 int addEntriesFrom = 0;
187 if (context.getReplicatedLog().size() > 0) {
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);
193 if (!isLogEntryPresent(matchEntry.getIndex())) {
194 // newEntry not found in the log
198 long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
200 log.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
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()) {
209 if (!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
211 log.debug("{}: Removing entries from log starting at {}", logName(),
212 matchEntry.getIndex());
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.
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());
229 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
230 lastTerm(), context.getPayloadVersion(), true), actor());
236 lastIndex = lastIndex();
237 log.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
238 lastIndex, addEntriesFrom);
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);
244 log.debug("{}: Append entry to log {}", logName(), entry.getData());
246 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
248 if (entry.getData() instanceof ServerConfigurationPayload) {
249 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
253 log.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
256 // 5. If leaderCommit > commitIndex, set commitIndex =
257 // min(leaderCommit, index of last new entry)
259 lastIndex = lastIndex();
260 long prevCommitIndex = context.getCommitIndex();
262 if (appendEntries.getLeaderCommit() > prevCommitIndex) {
263 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
266 if (prevCommitIndex != context.getCommitIndex()) {
267 log.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
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);
281 applyLogToStateMachine(appendEntries.getLeaderCommit());
284 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
285 lastIndex, lastTerm(), context.getPayloadVersion());
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);
293 sender.tell(reply, actor());
295 if (!context.getSnapshotManager().isCapturing()) {
296 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
302 private boolean isOutOfSync(AppendEntries appendEntries) {
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;
310 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
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
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) {
320 // The follower's log is out of sync because the Leader's
321 // prevLogIndex entry was not found in it's log
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()) {
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
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
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);
356 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
357 AppendEntriesReply appendEntriesReply) {
362 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
363 RequestVoteReply requestVoteReply) {
368 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
369 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
370 return handleElectionTimeout(message);
373 if (!(message instanceof RaftRPC)) {
374 // The rest of the processing requires the message to be a RaftRPC
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());
386 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
389 if (rpc instanceof InstallSnapshot) {
390 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
391 restartLastLeaderMessageTimer();
392 scheduleElection(electionDuration());
396 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
397 restartLastLeaderMessageTimer();
398 scheduleElection(electionDuration());
401 return super.handleMessage(sender, rpc);
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;
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
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());
429 log.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
430 return internalSwitchBehavior(RaftState.Candidate);
433 log.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
434 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
435 scheduleElection(electionDuration());
437 } else if (message instanceof ElectionTimeout) {
438 if (noLeaderMessageReceived) {
442 scheduleElection(electionDuration());
448 private boolean isLeaderAvailabilityKnown() {
449 if (leaderId == null) {
453 Optional<Cluster> cluster = context.getCluster();
454 if (!cluster.isPresent()) {
458 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
459 if (leaderActor == null) {
463 Address leaderAddress = leaderActor.anchorPath().address();
465 CurrentClusterState state = cluster.get().state();
466 Set<Member> unreachable = state.getUnreachable();
468 log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
471 for (Member m: unreachable) {
472 if (leaderAddress.equals(m.address())) {
473 log.info("{}: Leader {} is unreachable", logName(), leaderAddress);
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());
485 log.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
486 leaderAddress, m.status());
492 log.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
497 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
499 log.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
501 leaderId = installSnapshot.getLeaderId();
503 if (snapshotTracker == null) {
504 snapshotTracker = new SnapshotTracker(log, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
507 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
510 final InstallSnapshotReply reply = new InstallSnapshotReply(
511 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
513 if (snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
514 installSnapshot.getLastChunkHashCode())) {
515 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
517 installSnapshot.getLastIncludedIndex(),
518 installSnapshot.getLastIncludedTerm(),
519 installSnapshot.getLastIncludedIndex(),
520 installSnapshot.getLastIncludedTerm(),
521 context.getTermInformation().getCurrentTerm(),
522 context.getTermInformation().getVotedFor(),
523 installSnapshot.getServerConfig().orNull());
525 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
527 public void onSuccess() {
528 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
530 sender.tell(reply, actor());
534 public void onFailure() {
535 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
539 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
541 snapshotTracker = null;
543 log.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
545 sender.tell(reply, actor());
547 } catch (SnapshotTracker.InvalidChunkException e) {
548 log.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
550 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
551 -1, false), actor());
552 snapshotTracker = null;
558 public void close() {
563 SnapshotTracker getSnapshotTracker() {
564 return snapshotTracker;