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 if(appendEntries.getLeaderCommit() > prevCommitIndex) {
265 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
268 if (prevCommitIndex != context.getCommitIndex()) {
269 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
272 // If commitIndex > lastApplied: increment lastApplied, apply
273 // log[lastApplied] to state machine (§5.3)
274 // check if there are any entries to be applied. last-applied can be equal to last-index
275 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
276 context.getLastApplied() < lastIndex) {
277 if(LOG.isDebugEnabled()) {
278 LOG.debug("{}: applyLogToStateMachine, " +
279 "appendEntries.getLeaderCommit(): {}," +
280 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
281 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
284 applyLogToStateMachine(appendEntries.getLeaderCommit());
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 sender.tell(reply, actor());
298 if (!context.getSnapshotManager().isCapturing()) {
299 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
305 private boolean isOutOfSync(AppendEntries appendEntries) {
307 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
308 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
309 long lastIndex = lastIndex();
310 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
311 boolean outOfSync = true;
313 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
315 // The follower's log is out of sync because the leader does have
316 // an entry at prevLogIndex and this follower has no entries in
319 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
320 logName(), appendEntries.getPrevLogIndex());
321 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
323 // The follower's log is out of sync because the Leader's
324 // prevLogIndex entry was not found in it's log
326 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
327 logName(), appendEntries.getPrevLogIndex(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
328 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
330 // The follower's log is out of sync because the Leader's
331 // prevLogIndex entry does exist in the follower's log but it has
332 // a different term in it
334 LOG.debug("{}: The prevLogIndex {} was found in the log but the term {} is not equal to the append entries " +
335 "prevLogTerm {} - lastIndex: {}, snapshotIndex: {}", logName(), appendEntries.getPrevLogIndex(),
336 prevLogTerm, appendEntries.getPrevLogTerm(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
337 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
338 && appendEntries.getReplicatedToAllIndex() != -1
339 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
340 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
341 // the previous entry in it's in-memory journal
344 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
345 logName(), appendEntries.getReplicatedToAllIndex());
346 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
347 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
348 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
350 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
351 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
359 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
360 AppendEntriesReply appendEntriesReply) {
365 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
366 RequestVoteReply requestVoteReply) {
371 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
372 if (message instanceof ElectionTimeout || message instanceof TimeoutNow) {
373 return handleElectionTimeout(message);
376 if (!(message instanceof RaftRPC)) {
377 // The rest of the processing requires the message to be a RaftRPC
381 final RaftRPC rpc = (RaftRPC) message;
382 // If RPC request or response contains term T > currentTerm:
383 // set currentTerm = T, convert to follower (§5.1)
384 // This applies to all RPC messages and responses
385 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
386 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
387 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
389 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
392 if (rpc instanceof InstallSnapshot) {
393 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
394 restartLastLeaderMessageTimer();
395 scheduleElection(electionDuration());
399 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
400 restartLastLeaderMessageTimer();
401 scheduleElection(electionDuration());
404 return super.handleMessage(sender, rpc);
407 private RaftActorBehavior handleElectionTimeout(Object message) {
408 // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
409 // during the election timeout interval. It may that the election timer expired b/c this actor
410 // was busy and messages got delayed, in which case leader messages would be backed up in the
411 // queue but would be processed before the ElectionTimeout message and thus would restart the
412 // lastLeaderMessageTimer.
413 long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
414 long electionTimeoutInMillis = context.getConfigParams().getElectionTimeOutInterval().toMillis();
415 boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning() ||
416 lastLeaderMessageInterval >= electionTimeoutInMillis;
418 if(canStartElection()) {
419 if(message instanceof TimeoutNow) {
420 LOG.debug("{}: Received TimeoutNow - switching to Candidate", logName());
421 return internalSwitchBehavior(RaftState.Candidate);
422 } else if(noLeaderMessageReceived) {
423 // Check the cluster state to see if the leader is known to be up before we go to Candidate.
424 // However if we haven't heard from the leader in a long time even though the cluster state
425 // indicates it's up then something is wrong - leader might be stuck indefinitely - so switch
427 long maxElectionTimeout = electionTimeoutInMillis * MAX_ELECTION_TIMEOUT_FACTOR;
428 if(isLeaderAvailabilityKnown() && lastLeaderMessageInterval < maxElectionTimeout) {
429 LOG.debug("{}: Received ElectionTimeout but leader appears to be available", logName());
430 scheduleElection(electionDuration());
432 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
433 return internalSwitchBehavior(RaftState.Candidate);
436 LOG.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout {}",
437 logName(), lastLeaderMessageInterval, context.getConfigParams().getElectionTimeOutInterval());
438 scheduleElection(electionDuration());
440 } else if(message instanceof ElectionTimeout) {
441 if(noLeaderMessageReceived) {
445 scheduleElection(electionDuration());
451 private boolean isLeaderAvailabilityKnown() {
452 if(leaderId == null) {
456 Optional<Cluster> cluster = context.getCluster();
457 if(!cluster.isPresent()) {
461 ActorSelection leaderActor = context.getPeerActorSelection(leaderId);
462 if(leaderActor == null) {
466 Address leaderAddress = leaderActor.anchorPath().address();
468 CurrentClusterState state = cluster.get().state();
469 Set<Member> unreachable = state.getUnreachable();
471 LOG.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
474 for(Member m: unreachable) {
475 if(leaderAddress.equals(m.address())) {
476 LOG.info("{}: Leader {} is unreachable", logName(), leaderAddress);
481 for(Member m: state.getMembers()) {
482 if(leaderAddress.equals(m.address())) {
483 if(m.status() == MemberStatus.up() || m.status() == MemberStatus.weaklyUp()) {
484 LOG.debug("{}: Leader {} cluster status is {} - leader is available", logName(),
485 leaderAddress, m.status());
488 LOG.debug("{}: Leader {} cluster status is {} - leader is unavailable", logName(),
489 leaderAddress, m.status());
495 LOG.debug("{}: Leader {} not found in the cluster member set", logName(), leaderAddress);
500 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
502 LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
504 leaderId = installSnapshot.getLeaderId();
506 if(snapshotTracker == null){
507 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks(), installSnapshot.getLeaderId());
510 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
513 final InstallSnapshotReply reply = new InstallSnapshotReply(
514 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
516 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
517 installSnapshot.getLastChunkHashCode())){
518 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
520 installSnapshot.getLastIncludedIndex(),
521 installSnapshot.getLastIncludedTerm(),
522 installSnapshot.getLastIncludedIndex(),
523 installSnapshot.getLastIncludedTerm(),
524 context.getTermInformation().getCurrentTerm(),
525 context.getTermInformation().getVotedFor(),
526 installSnapshot.getServerConfig().orNull());
528 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
530 public void onSuccess() {
531 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
533 sender.tell(reply, actor());
537 public void onFailure() {
538 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
542 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
544 snapshotTracker = null;
546 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
548 sender.tell(reply, actor());
550 } catch (SnapshotTracker.InvalidChunkException e) {
551 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
553 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
554 -1, false), actor());
555 snapshotTracker = null;
557 } catch (Exception e){
558 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
560 //send reply with success as false. The chunk will be sent again on failure
561 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
562 installSnapshot.getChunkIndex(), false), actor());
568 public void close() {
573 SnapshotTracker getSnapshotTracker(){
574 return snapshotTracker;