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 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 leaderId){
124 initialSyncStatusTracker.update(leaderId, 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 if(LOG.isDebugEnabled()) {
153 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
155 sender.tell(reply, actor());
160 // If we got here then we do appear to be talking to the leader
161 leaderId = appendEntries.getLeaderId();
162 leaderPayloadVersion = appendEntries.getPayloadVersion();
164 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
165 // First check if the logs are in sync or not
166 long lastIndex = lastIndex();
168 if (isOutOfSync(appendEntries)) {
169 // We found that the log was out of sync so just send a negative
172 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
173 logName(), lastIndex, lastTerm());
175 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
176 lastTerm(), context.getPayloadVersion()), actor());
180 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
182 LOG.debug("{}: Number of entries to be appended = {}", logName(),
183 appendEntries.getEntries().size());
185 // 3. If an existing entry conflicts with a new one (same index
186 // but different terms), delete the existing entry and all that
188 int addEntriesFrom = 0;
189 if (context.getReplicatedLog().size() > 0) {
191 // Find the entry up until the one that is not in the follower's log
192 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
193 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
195 if(!isLogEntryPresent(matchEntry.getIndex())) {
196 // newEntry not found in the log
200 long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
202 LOG.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
205 // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
206 // what the term was so we'll assume it matches.
207 if(existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
211 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
213 LOG.debug("{}: Removing entries from log starting at {}", logName(),
214 matchEntry.getIndex());
216 // Entries do not match so remove all subsequent entries
217 if(!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
218 // Could not remove the entries - this means the matchEntry index must be in the
219 // snapshot and not the log. In this case the prior entries are part of the state
220 // so we must send back a reply to force a snapshot to completely re-sync the
221 // follower's log and state.
223 LOG.debug("{}: Could not remove entries - sending reply to force snapshot", logName());
224 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
225 lastTerm(), context.getPayloadVersion(), true), actor());
231 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
232 lastTerm(), context.getPayloadVersion(), true), actor());
238 lastIndex = lastIndex();
239 LOG.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
240 lastIndex, addEntriesFrom);
242 // 4. Append any new entries not already in the log
243 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
244 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
246 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
248 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
250 if(entry.getData() instanceof ServerConfigurationPayload) {
251 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
255 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
258 // 5. If leaderCommit > commitIndex, set commitIndex =
259 // min(leaderCommit, index of last new entry)
261 lastIndex = lastIndex();
262 long prevCommitIndex = context.getCommitIndex();
264 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, " +
277 "appendEntries.getLeaderCommit(): {}," +
278 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
279 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
282 applyLogToStateMachine(appendEntries.getLeaderCommit());
285 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
286 lastIndex, lastTerm(), context.getPayloadVersion());
288 if(LOG.isTraceEnabled()) {
289 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
290 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
291 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
294 sender.tell(reply, actor());
296 if (!context.getSnapshotManager().isCapturing()) {
297 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
303 private boolean isOutOfSync(AppendEntries appendEntries) {
305 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
306 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
307 long lastIndex = lastIndex();
308 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
309 boolean outOfSync = true;
311 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
313 // The follower's log is out of sync because the leader does have
314 // an entry at prevLogIndex and this follower has no entries in
317 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
318 logName(), appendEntries.getPrevLogIndex());
319 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
321 // The follower's log is out of sync because the Leader's
322 // prevLogIndex entry was not found in it's log
324 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
325 logName(), appendEntries.getPrevLogIndex(), lastIndex, 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
333 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
334 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
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
342 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
343 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)) {
348 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
349 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
357 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
358 AppendEntriesReply appendEntriesReply) {
363 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
364 RequestVoteReply requestVoteReply) {
369 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
370 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
371 return handleElectionTimeout(message);
374 if (!(message instanceof RaftRPC)) {
375 // The rest of the processing requires the message to be a RaftRPC
379 final RaftRPC rpc = (RaftRPC) message;
380 // If RPC request or response contains term T > currentTerm:
381 // set currentTerm = T, convert to follower (§5.1)
382 // This applies to all RPC messages and responses
383 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
384 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
385 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
387 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
390 if (rpc instanceof InstallSnapshot) {
391 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
392 restartLastLeaderMessageTimer();
393 scheduleElection(electionDuration());
397 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
398 restartLastLeaderMessageTimer();
399 scheduleElection(electionDuration());
402 return super.handleMessage(sender, rpc);
405 private RaftActorBehavior handleElectionTimeout(Object message) {
406 // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
407 // during the election timeout interval. It may that the election timer expired b/c this actor
408 // was busy and messages got delayed, in which case leader messages would be backed up in the
409 // queue but would be processed before the ElectionTimeout message and thus would restart the
410 // lastLeaderMessageTimer.
411 long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
412 long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
413 boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning() ||
414 lastLeaderMessageInterval >= electionTimeoutInMillis;
416 if(canStartElection()) {
417 if(message instanceof TimeoutNow) {
418 LOG.debug("{}: Received TimeoutNow - switching to Candidate", logName());
419 return internalSwitchBehavior(RaftState.Candidate);
420 } else if(noLeaderMessageReceived) {
421 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
422 // However if we haven't heard from the leader in a long time even though the cluster state
423 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
425 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
426 if(isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
427 LOG.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
428 scheduleElection(electionDuration());
430 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
431 return internalSwitchBehavior(RaftState.Candidate);
434 LOG.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
435 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
436 scheduleElection(electionDuration());
438 } else if(message instanceof ElectionTimeout) {
439 if(noLeaderMessageReceived) {
443 scheduleElection(electionDuration());
449 private boolean isLeaderAvailabilityKnown() {
450 if(leaderId == null) {
454 Optional<Cluster> cluster = context.getCluster();
455 if(!cluster.isPresent()) {
459 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
460 if(leaderActor == null) {
464 Address leaderAddress = leaderActor.anchorPath().address();
466 CurrentClusterState state = cluster.get().state();
467 Set<Member> unreachable = state.getUnreachable();
469 LOG.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
472 for(Member m: unreachable) {
473 if(leaderAddress.equals(m.address())) {
474 LOG.info("{}: Leader {} is unreachable", logName(), leaderAddress);
479 for(Member m: state.getMembers()) {
480 if(leaderAddress.equals(m.address())) {
481 if(m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
482 LOG.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
483 leaderAddress, m.status());
486 LOG.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
487 leaderAddress, m.status());
493 LOG.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
498 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
500 LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
502 leaderId = installSnapshot.getLeaderId();
504 if(snapshotTracker == null){
505 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
508 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
511 final InstallSnapshotReply reply = new InstallSnapshotReply(
512 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
514 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
515 installSnapshot.getLastChunkHashCode())){
516 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
517 new ArrayList<ReplicatedLogEntry>(),
518 installSnapshot.getLastIncludedIndex(),
519 installSnapshot.getLastIncludedTerm(),
520 installSnapshot.getLastIncludedIndex(),
521 installSnapshot.getLastIncludedTerm(),
522 context.getTermInformation().getCurrentTerm(),
523 context.getTermInformation().getVotedFor(),
524 installSnapshot.getServerConfig().orNull());
526 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
528 public void onSuccess() {
529 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
531 sender.tell(reply, actor());
535 public void onFailure() {
536 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
540 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
542 snapshotTracker = null;
544 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
546 sender.tell(reply, actor());
548 } catch (SnapshotTracker.InvalidChunkException e) {
549 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
551 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
552 -1, false), actor());
553 snapshotTracker = null;
555 } catch (Exception e){
556 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
558 //send reply with success as false. The chunk will be sent again on failure
559 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
560 installSnapshot.getChunkIndex(), false), actor());
566 public void close() {
571 SnapshotTracker getSnapshotTracker(){
572 return snapshotTracker;