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.japi.Procedure;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Stopwatch;
15 import java.util.ArrayList;
16 import java.util.concurrent.TimeUnit;
17 import javax.annotation.Nullable;
18 import org.opendaylight.controller.cluster.raft.RaftActorContext;
19 import org.opendaylight.controller.cluster.raft.RaftState;
20 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
21 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
22 import org.opendaylight.controller.cluster.raft.Snapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
24 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
25 import org.opendaylight.controller.cluster.raft.base.messages.TimeoutNow;
26 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
27 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
28 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
29 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
30 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
31 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
32 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
35 * The behavior of a RaftActor in the Follower state
38 * <li> Respond to RPCs from candidates and leaders
39 * <li> If election timeout elapses without receiving AppendEntries
40 * RPC from current leader or granting vote to candidate:
41 * convert to candidate
44 public class Follower extends AbstractRaftActorBehavior {
45 private static final int SYNC_THRESHOLD = 10;
47 private final SyncStatusTracker initialSyncStatusTracker;
49 private final Procedure<ReplicatedLogEntry> appendAndPersistCallback = new Procedure<ReplicatedLogEntry>() {
51 public void apply(ReplicatedLogEntry logEntry) {
52 context.getReplicatedLog().captureSnapshotIfReady(logEntry);
56 private final Stopwatch lastLeaderMessageTimer = Stopwatch.createUnstarted();
57 private SnapshotTracker snapshotTracker = null;
58 private String leaderId;
59 private short leaderPayloadVersion;
61 public Follower(RaftActorContext context) {
62 this(context, null, (short)-1);
65 public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
66 super(context, RaftState.Follower);
67 this.leaderId = initialLeaderId;
68 this.leaderPayloadVersion = initialLeaderPayloadVersion;
70 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
72 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
73 actor().tell(TimeoutNow.INSTANCE, actor());
75 scheduleElection(electionDuration());
80 public final String getLeaderId() {
85 protected final void setLeaderId(@Nullable final String leaderId) {
86 this.leaderId = leaderId;
90 public short getLeaderPayloadVersion() {
91 return leaderPayloadVersion;
95 protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
96 this.leaderPayloadVersion = leaderPayloadVersion;
99 private void restartLastLeaderMessageTimer() {
100 if (lastLeaderMessageTimer.isRunning()) {
101 lastLeaderMessageTimer.reset();
104 lastLeaderMessageTimer.start();
107 private boolean isLogEntryPresent(long index){
108 if(context.getReplicatedLog().isInSnapshot(index)) {
112 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
113 return entry != null;
117 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
118 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
122 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
124 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
125 if(LOG.isTraceEnabled()) {
126 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
127 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
128 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
131 // TODO : Refactor this method into a bunch of smaller methods
132 // to make it easier to read. Before refactoring ensure tests
133 // cover the code properly
135 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
136 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
137 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
138 lastIndex(), lastTerm(), context.getPayloadVersion());
140 if(LOG.isDebugEnabled()) {
141 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
143 sender.tell(reply, actor());
148 // If we got here then we do appear to be talking to the leader
149 leaderId = appendEntries.getLeaderId();
150 leaderPayloadVersion = appendEntries.getPayloadVersion();
152 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
153 // First check if the logs are in sync or not
154 long lastIndex = lastIndex();
156 if (isOutOfSync(appendEntries)) {
157 // We found that the log was out of sync so just send a negative
160 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
161 logName(), lastIndex, lastTerm());
163 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
164 lastTerm(), context.getPayloadVersion()), actor());
168 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
170 LOG.debug("{}: Number of entries to be appended = {}", logName(),
171 appendEntries.getEntries().size());
173 // 3. If an existing entry conflicts with a new one (same index
174 // but different terms), delete the existing entry and all that
176 int addEntriesFrom = 0;
177 if (context.getReplicatedLog().size() > 0) {
179 // Find the entry up until the one that is not in the follower's log
180 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
181 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
183 if(!isLogEntryPresent(matchEntry.getIndex())) {
184 // newEntry not found in the log
188 long existingEntryTerm = getLogEntryTerm(matchEntry.getIndex());
190 LOG.debug("{}: matchEntry {} is present: existingEntryTerm: {}", logName(), matchEntry,
193 // existingEntryTerm == -1 means it's in the snapshot and not in the log. We don't know
194 // what the term was so we'll assume it matches.
195 if(existingEntryTerm == -1 || existingEntryTerm == matchEntry.getTerm()) {
199 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
201 LOG.debug("{}: Removing entries from log starting at {}", logName(),
202 matchEntry.getIndex());
204 // Entries do not match so remove all subsequent entries
205 if(!context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex())) {
206 // Could not remove the entries - this means the matchEntry index must be in the
207 // snapshot and not the log. In this case the prior entries are part of the state
208 // so we must send back a reply to force a snapshot to completely re-sync the
209 // follower's log and state.
211 LOG.debug("{}: Could not remove entries - sending reply to force snapshot", logName());
212 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
213 lastTerm(), context.getPayloadVersion(), true), actor());
219 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
220 lastTerm(), context.getPayloadVersion(), true), actor());
226 lastIndex = lastIndex();
227 LOG.debug("{}: After cleanup, lastIndex: {}, entries to be added from: {}", logName(),
228 lastIndex, addEntriesFrom);
230 // 4. Append any new entries not already in the log
231 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
232 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
234 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
236 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
238 if(entry.getData() instanceof ServerConfigurationPayload) {
239 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
243 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
246 // 5. If leaderCommit > commitIndex, set commitIndex =
247 // min(leaderCommit, index of last new entry)
249 lastIndex = lastIndex();
250 long prevCommitIndex = context.getCommitIndex();
252 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
254 if (prevCommitIndex != context.getCommitIndex()) {
255 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
258 // If commitIndex > lastApplied: increment lastApplied, apply
259 // log[lastApplied] to state machine (ยง5.3)
260 // check if there are any entries to be applied. last-applied can be equal to last-index
261 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
262 context.getLastApplied() < lastIndex) {
263 if(LOG.isDebugEnabled()) {
264 LOG.debug("{}: applyLogToStateMachine, " +
265 "appendEntries.getLeaderCommit(): {}," +
266 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
267 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
270 applyLogToStateMachine(appendEntries.getLeaderCommit());
273 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
274 lastIndex, lastTerm(), context.getPayloadVersion());
276 if(LOG.isTraceEnabled()) {
277 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
278 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
279 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
282 sender.tell(reply, actor());
284 if (!context.getSnapshotManager().isCapturing()) {
285 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
291 private boolean isOutOfSync(AppendEntries appendEntries) {
293 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
294 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
295 long lastIndex = lastIndex();
296 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
297 boolean outOfSync = true;
299 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
301 // The follower's log is out of sync because the leader does have
302 // an entry at prevLogIndex and this follower has no entries in
305 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
306 logName(), appendEntries.getPrevLogIndex());
307 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
309 // The follower's log is out of sync because the Leader's
310 // prevLogIndex entry was not found in it's log
312 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
313 logName(), appendEntries.getPrevLogIndex(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
314 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
316 // The follower's log is out of sync because the Leader's
317 // prevLogIndex entry does exist in the follower's log but it has
318 // a different term in it
321 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
322 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
323 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
324 && appendEntries.getReplicatedToAllIndex() != -1
325 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
326 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
327 // the previous entry in it's in-memory journal
330 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
331 logName(), appendEntries.getReplicatedToAllIndex());
332 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
333 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
334 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
336 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
337 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
345 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
346 AppendEntriesReply appendEntriesReply) {
351 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
352 RequestVoteReply requestVoteReply) {
357 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
358 if (originalMessage instanceof ElectionTimeout || originalMessage instanceof TimeoutNow) {
359 return handleElectionTimeout(originalMessage);
362 final Object message = fromSerializableMessage(originalMessage);
363 if (!(message instanceof RaftRPC)) {
364 // The rest of the processing requires the message to be a RaftRPC
368 final RaftRPC rpc = (RaftRPC) message;
369 // If RPC request or response contains term T > currentTerm:
370 // set currentTerm = T, convert to follower (ยง5.1)
371 // This applies to all RPC messages and responses
372 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
373 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
374 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
376 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
379 if (rpc instanceof InstallSnapshot) {
380 handleInstallSnapshot(sender, (InstallSnapshot) rpc);
381 restartLastLeaderMessageTimer();
382 scheduleElection(electionDuration());
386 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
387 restartLastLeaderMessageTimer();
388 scheduleElection(electionDuration());
391 return super.handleMessage(sender, rpc);
394 private RaftActorBehavior handleElectionTimeout(Object message) {
395 // If the message is ElectionTimeout, verify we haven't actually seen a message from the leader
396 // during the election timeout interval. It may that the election timer expired b/c this actor
397 // was busy and messages got delayed, in which case leader messages would be backed up in the
398 // queue but would be processed before the ElectionTimeout message and thus would restart the
399 // lastLeaderMessageTimer.
400 long lastLeaderMessageInterval = lastLeaderMessageTimer.elapsed(TimeUnit.MILLISECONDS);
401 boolean noLeaderMessageReceived = !lastLeaderMessageTimer.isRunning() || lastLeaderMessageInterval >=
402 context.getConfigParams().getElectionTimeOutInterval().toMillis();
404 if(canStartElection()) {
405 if(message instanceof TimeoutNow || noLeaderMessageReceived) {
406 LOG.debug("{}: Received {} - switching to Candidate", logName(), message.getClass().getSimpleName());
407 return internalSwitchBehavior(RaftState.Candidate);
409 LOG.debug("{}: Received ElectionTimeout but lastLeaderMessageInterval {} < election timeout",
410 logName(), lastLeaderMessageInterval);
411 scheduleElection(electionDuration());
413 } else if(message instanceof ElectionTimeout) {
414 if(noLeaderMessageReceived) {
418 scheduleElection(electionDuration());
424 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
426 LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
428 leaderId = installSnapshot.getLeaderId();
430 if(snapshotTracker == null){
431 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
434 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
437 final InstallSnapshotReply reply = new InstallSnapshotReply(
438 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
440 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
441 installSnapshot.getLastChunkHashCode())){
442 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
443 new ArrayList<ReplicatedLogEntry>(),
444 installSnapshot.getLastIncludedIndex(),
445 installSnapshot.getLastIncludedTerm(),
446 installSnapshot.getLastIncludedIndex(),
447 installSnapshot.getLastIncludedTerm(),
448 context.getTermInformation().getCurrentTerm(),
449 context.getTermInformation().getVotedFor(),
450 installSnapshot.getServerConfig().orNull());
452 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
454 public void onSuccess() {
455 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
457 sender.tell(reply, actor());
461 public void onFailure() {
462 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
466 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
468 snapshotTracker = null;
470 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
472 sender.tell(reply, actor());
474 } catch (SnapshotTracker.InvalidChunkException e) {
475 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
477 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
478 -1, false), actor());
479 snapshotTracker = null;
481 } catch (Exception e){
482 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
484 //send reply with success as false. The chunk will be sent again on failure
485 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
486 installSnapshot.getChunkIndex(), false), actor());
492 public void close() {
497 SnapshotTracker getSnapshotTracker(){
498 return snapshotTracker;