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 java.util.ArrayList;
15 import javax.annotation.Nullable;
16 import org.opendaylight.controller.cluster.raft.RaftActorContext;
17 import org.opendaylight.controller.cluster.raft.RaftState;
18 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
19 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
20 import org.opendaylight.controller.cluster.raft.Snapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
22 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
24 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
25 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
26 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
27 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
28 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
29 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
32 * The behavior of a RaftActor in the Follower state
35 * <li> Respond to RPCs from candidates and leaders
36 * <li> If election timeout elapses without receiving AppendEntries
37 * RPC from current leader or granting vote to candidate:
38 * convert to candidate
41 public class Follower extends AbstractRaftActorBehavior {
42 private static final int SYNC_THRESHOLD = 10;
44 private final SyncStatusTracker initialSyncStatusTracker;
46 private final Procedure<ReplicatedLogEntry> appendAndPersistCallback = new Procedure<ReplicatedLogEntry>() {
48 public void apply(ReplicatedLogEntry logEntry) {
49 context.getReplicatedLog().captureSnapshotIfReady(logEntry);
53 private SnapshotTracker snapshotTracker = null;
54 private String leaderId;
55 private short leaderPayloadVersion;
57 public Follower(RaftActorContext context) {
58 this(context, null, (short)-1);
61 public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
62 super(context, RaftState.Follower);
63 this.leaderId = initialLeaderId;
64 this.leaderPayloadVersion = initialLeaderPayloadVersion;
66 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
68 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
69 actor().tell(ElectionTimeout.INSTANCE, actor());
71 scheduleElection(electionDuration());
76 public final String getLeaderId() {
81 protected final void setLeaderId(@Nullable final String leaderId) {
82 this.leaderId = leaderId;
86 public short getLeaderPayloadVersion() {
87 return leaderPayloadVersion;
91 protected final void setLeaderPayloadVersion(short leaderPayloadVersion) {
92 this.leaderPayloadVersion = leaderPayloadVersion;
95 private boolean isLogEntryPresent(long index){
96 if(context.getReplicatedLog().isInSnapshot(index)) {
100 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
103 return previousEntry != null;
107 private long getLogEntryTerm(long index){
108 if(index == context.getReplicatedLog().getSnapshotIndex()){
109 return context.getReplicatedLog().getSnapshotTerm();
112 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
115 if(previousEntry != null){
116 return previousEntry.getTerm();
122 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
123 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
127 protected RaftActorBehavior handleAppendEntries(ActorRef sender, AppendEntries appendEntries) {
129 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
130 if(LOG.isTraceEnabled()) {
131 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
132 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
133 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
136 // TODO : Refactor this method into a bunch of smaller methods
137 // to make it easier to read. Before refactoring ensure tests
138 // cover the code properly
140 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
141 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
142 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
143 lastIndex(), lastTerm(), context.getPayloadVersion());
145 if(LOG.isDebugEnabled()) {
146 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
148 sender.tell(reply, actor());
153 // If we got here then we do appear to be talking to the leader
154 leaderId = appendEntries.getLeaderId();
155 leaderPayloadVersion = appendEntries.getPayloadVersion();
157 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
158 // First check if the logs are in sync or not
159 long lastIndex = lastIndex();
161 if (isOutOfSync(appendEntries)) {
162 // We found that the log was out of sync so just send a negative
165 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
166 logName(), lastIndex, lastTerm());
168 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
169 lastTerm(), context.getPayloadVersion()), actor());
173 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
175 LOG.debug("{}: Number of entries to be appended = {}", logName(),
176 appendEntries.getEntries().size());
178 // 3. If an existing entry conflicts with a new one (same index
179 // but different terms), delete the existing entry and all that
181 int addEntriesFrom = 0;
182 if (context.getReplicatedLog().size() > 0) {
184 // Find the entry up until the one that is not in the follower's log
185 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
186 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
187 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
189 if (newEntry == null) {
190 //newEntry not found in the log
194 if (newEntry.getTerm() == matchEntry.getTerm()) {
198 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
200 LOG.debug("{}: Removing entries from log starting at {}", logName(),
201 matchEntry.getIndex());
203 // Entries do not match so remove all subsequent entries
204 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
207 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
208 lastTerm(), context.getPayloadVersion(), true), actor());
214 lastIndex = lastIndex();
215 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
216 (addEntriesFrom + lastIndex));
218 // 4. Append any new entries not already in the log
219 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
220 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
222 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
224 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
226 if(entry.getData() instanceof ServerConfigurationPayload) {
227 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
231 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
234 // 5. If leaderCommit > commitIndex, set commitIndex =
235 // min(leaderCommit, index of last new entry)
237 lastIndex = lastIndex();
238 long prevCommitIndex = context.getCommitIndex();
240 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
242 if (prevCommitIndex != context.getCommitIndex()) {
243 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
246 // If commitIndex > lastApplied: increment lastApplied, apply
247 // log[lastApplied] to state machine (ยง5.3)
248 // check if there are any entries to be applied. last-applied can be equal to last-index
249 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
250 context.getLastApplied() < lastIndex) {
251 if(LOG.isDebugEnabled()) {
252 LOG.debug("{}: applyLogToStateMachine, " +
253 "appendEntries.getLeaderCommit(): {}," +
254 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
255 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
258 applyLogToStateMachine(appendEntries.getLeaderCommit());
261 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
262 lastIndex, lastTerm(), context.getPayloadVersion());
264 if(LOG.isTraceEnabled()) {
265 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
266 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
267 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
270 sender.tell(reply, actor());
272 if (!context.getSnapshotManager().isCapturing()) {
273 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
279 private boolean isOutOfSync(AppendEntries appendEntries) {
281 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
282 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
283 long lastIndex = lastIndex();
284 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
285 boolean outOfSync = true;
287 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
289 // The follower's log is out of sync because the leader does have
290 // an entry at prevLogIndex and this follower has no entries in
293 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
294 logName(), appendEntries.getPrevLogIndex());
295 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
297 // The follower's log is out of sync because the Leader's
298 // prevLogIndex entry was not found in it's log
300 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
301 logName(), appendEntries.getPrevLogIndex(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
302 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
304 // The follower's log is out of sync because the Leader's
305 // prevLogIndex entry does exist in the follower's log but it has
306 // a different term in it
309 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
310 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
311 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
312 && appendEntries.getReplicatedToAllIndex() != -1
313 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())) {
314 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
315 // the previous entry in it's in-memory journal
318 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
319 logName(), appendEntries.getReplicatedToAllIndex());
320 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
321 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
322 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)) {
324 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
325 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
333 protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
334 AppendEntriesReply appendEntriesReply) {
339 protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
340 RequestVoteReply requestVoteReply) {
345 public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
346 if (originalMessage instanceof ElectionTimeout) {
347 if (canStartElection()) {
348 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
349 return internalSwitchBehavior(RaftState.Candidate);
352 scheduleElection(electionDuration());
357 final Object message = fromSerializableMessage(originalMessage);
358 if (!(message instanceof RaftRPC)) {
359 // The rest of the processing requires the message to be a RaftRPC
363 final RaftRPC rpc = (RaftRPC) message;
364 // If RPC request or response contains term T > currentTerm:
365 // set currentTerm = T, convert to follower (ยง5.1)
366 // This applies to all RPC messages and responses
367 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
368 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
369 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
371 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
374 if (rpc instanceof InstallSnapshot) {
375 InstallSnapshot installSnapshot = (InstallSnapshot) rpc;
376 handleInstallSnapshot(sender, installSnapshot);
377 scheduleElection(electionDuration());
381 if (!(rpc instanceof RequestVote) || canGrantVote((RequestVote) rpc)) {
382 scheduleElection(electionDuration());
385 return super.handleMessage(sender, rpc);
388 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
390 LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
392 leaderId = installSnapshot.getLeaderId();
394 if(snapshotTracker == null){
395 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
398 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
401 final InstallSnapshotReply reply = new InstallSnapshotReply(
402 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
404 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
405 installSnapshot.getLastChunkHashCode())){
406 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
407 new ArrayList<ReplicatedLogEntry>(),
408 installSnapshot.getLastIncludedIndex(),
409 installSnapshot.getLastIncludedTerm(),
410 installSnapshot.getLastIncludedIndex(),
411 installSnapshot.getLastIncludedTerm(),
412 context.getTermInformation().getCurrentTerm(),
413 context.getTermInformation().getVotedFor(),
414 installSnapshot.getServerConfig().orNull());
416 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
418 public void onSuccess() {
419 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
421 sender.tell(reply, actor());
425 public void onFailure() {
426 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
430 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
432 snapshotTracker = null;
434 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
436 sender.tell(reply, actor());
438 } catch (SnapshotTracker.InvalidChunkException e) {
439 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
441 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
442 -1, false), actor());
443 snapshotTracker = null;
445 } catch (Exception e){
446 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
448 //send reply with success as false. The chunk will be sent again on failure
449 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
450 installSnapshot.getChunkIndex(), false), actor());
456 public void close() {
461 SnapshotTracker getSnapshotTracker(){
462 return snapshotTracker;