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 org.opendaylight.controller.cluster.raft.RaftActorContext;
16 import org.opendaylight.controller.cluster.raft.RaftState;
17 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
18 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
19 import org.opendaylight.controller.cluster.raft.Snapshot;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
22 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
24 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
25 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
26 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
27 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
28 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
31 * The behavior of a RaftActor in the Follower state
34 * <li> Respond to RPCs from candidates and leaders
35 * <li> If election timeout elapses without receiving AppendEntries
36 * RPC from current leader or granting vote to candidate:
37 * convert to candidate
40 public class Follower extends AbstractRaftActorBehavior {
41 private static final int SYNC_THRESHOLD = 10;
43 private final SyncStatusTracker initialSyncStatusTracker;
45 private final Procedure<ReplicatedLogEntry> appendAndPersistCallback = new Procedure<ReplicatedLogEntry>() {
47 public void apply(ReplicatedLogEntry logEntry) {
48 context.getReplicatedLog().captureSnapshotIfReady(logEntry);
52 private SnapshotTracker snapshotTracker = null;
54 public Follower(RaftActorContext context) {
55 this(context, null, (short)-1);
58 public Follower(RaftActorContext context, String initialLeaderId, short initialLeaderPayloadVersion) {
59 super(context, RaftState.Follower);
60 leaderId = initialLeaderId;
61 setLeaderPayloadVersion(initialLeaderPayloadVersion);
63 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
65 if(canStartElection()) {
66 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
67 actor().tell(ElectionTimeout.INSTANCE, actor());
69 scheduleElection(electionDuration());
75 private boolean isLogEntryPresent(long index){
76 if(index == context.getReplicatedLog().getSnapshotIndex()){
80 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
83 return previousEntry != null;
87 private long getLogEntryTerm(long index){
88 if(index == context.getReplicatedLog().getSnapshotIndex()){
89 return context.getReplicatedLog().getSnapshotTerm();
92 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
95 if(previousEntry != null){
96 return previousEntry.getTerm();
102 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
103 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
106 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
107 AppendEntries appendEntries) {
109 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
110 if(LOG.isTraceEnabled()) {
111 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
112 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
113 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
116 // TODO : Refactor this method into a bunch of smaller methods
117 // to make it easier to read. Before refactoring ensure tests
118 // cover the code properly
120 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
121 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
122 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
123 lastIndex(), lastTerm(), context.getPayloadVersion());
125 if(LOG.isDebugEnabled()) {
126 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
128 sender.tell(reply, actor());
133 // If we got here then we do appear to be talking to the leader
134 leaderId = appendEntries.getLeaderId();
136 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
138 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
139 // First check if the logs are in sync or not
140 long lastIndex = lastIndex();
142 if (isOutOfSync(appendEntries)) {
143 // We found that the log was out of sync so just send a negative
146 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
147 logName(), lastIndex, lastTerm());
149 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
150 lastTerm(), context.getPayloadVersion()), actor());
154 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
156 LOG.debug("{}: Number of entries to be appended = {}", logName(),
157 appendEntries.getEntries().size());
159 // 3. If an existing entry conflicts with a new one (same index
160 // but different terms), delete the existing entry and all that
162 int addEntriesFrom = 0;
163 if (context.getReplicatedLog().size() > 0) {
165 // Find the entry up until the one that is not in the follower's log
166 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
167 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
168 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
170 if (newEntry == null) {
171 //newEntry not found in the log
175 if (newEntry.getTerm() == matchEntry.getTerm()) {
179 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
181 LOG.debug("{}: Removing entries from log starting at {}", logName(),
182 matchEntry.getIndex());
184 // Entries do not match so remove all subsequent entries
185 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
188 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
189 lastTerm(), context.getPayloadVersion(), true), actor());
195 lastIndex = lastIndex();
196 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
197 (addEntriesFrom + lastIndex));
199 // 4. Append any new entries not already in the log
200 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
201 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
203 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
205 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
207 if(entry.getData() instanceof ServerConfigurationPayload) {
208 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
212 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
215 // 5. If leaderCommit > commitIndex, set commitIndex =
216 // min(leaderCommit, index of last new entry)
218 lastIndex = lastIndex();
219 long prevCommitIndex = context.getCommitIndex();
221 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
223 if (prevCommitIndex != context.getCommitIndex()) {
224 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
227 // If commitIndex > lastApplied: increment lastApplied, apply
228 // log[lastApplied] to state machine (ยง5.3)
229 // check if there are any entries to be applied. last-applied can be equal to last-index
230 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
231 context.getLastApplied() < lastIndex) {
232 if(LOG.isDebugEnabled()) {
233 LOG.debug("{}: applyLogToStateMachine, " +
234 "appendEntries.getLeaderCommit(): {}," +
235 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
236 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
239 applyLogToStateMachine(appendEntries.getLeaderCommit());
242 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
243 lastIndex, lastTerm(), context.getPayloadVersion());
245 if(LOG.isTraceEnabled()) {
246 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
247 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
248 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
251 sender.tell(reply, actor());
253 if (!context.getSnapshotManager().isCapturing()) {
254 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
260 private boolean isOutOfSync(AppendEntries appendEntries) {
262 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
263 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
264 long lastIndex = lastIndex();
265 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
266 boolean outOfSync = true;
268 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
270 // The follower's log is out of sync because the leader does have
271 // an entry at prevLogIndex and this follower has no entries in
274 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
275 logName(), appendEntries.getPrevLogIndex());
276 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
278 // The follower's log is out of sync because the Leader's
279 // prevLogIndex entry was not found in it's log
281 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
282 logName(), appendEntries.getPrevLogIndex());
283 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
285 // The follower's log is out of sync because the Leader's
286 // prevLogIndex entry does exist in the follower's log but it has
287 // a different term in it
290 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
291 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
292 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
293 && appendEntries.getReplicatedToAllIndex() != -1
294 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())
295 && !context.getReplicatedLog().isInSnapshot(appendEntries.getReplicatedToAllIndex())) {
296 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
297 // the previous entry in it's in-memory journal
300 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
301 logName(), appendEntries.getReplicatedToAllIndex());
302 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
303 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
304 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)
305 && !context.getReplicatedLog().isInSnapshot(appendEntries.getEntries().get(0).getIndex() - 1)) {
307 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
308 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
315 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
316 AppendEntriesReply appendEntriesReply) {
320 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
321 RequestVoteReply requestVoteReply) {
325 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
327 Object message = fromSerializableMessage(originalMessage);
329 if (message instanceof RaftRPC) {
330 RaftRPC rpc = (RaftRPC) message;
331 // If RPC request or response contains term T > currentTerm:
332 // set currentTerm = T, convert to follower (ยง5.1)
333 // This applies to all RPC messages and responses
334 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
335 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
336 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
338 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
342 if (message instanceof ElectionTimeout) {
343 if(canStartElection()) {
344 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
345 return internalSwitchBehavior(RaftState.Candidate);
350 } else if (message instanceof InstallSnapshot) {
351 InstallSnapshot installSnapshot = (InstallSnapshot) message;
352 handleInstallSnapshot(sender, installSnapshot);
355 if(message instanceof RaftRPC && (!(message instanceof RequestVote) || (canGrantVote((RequestVote) message)))){
356 scheduleElection(electionDuration());
359 return super.handleMessage(sender, message);
362 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
364 LOG.debug("{}: handleInstallSnapshot: {}", logName(), installSnapshot);
366 leaderId = installSnapshot.getLeaderId();
368 if(snapshotTracker == null){
369 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
372 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
375 final InstallSnapshotReply reply = new InstallSnapshotReply(
376 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
378 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
379 installSnapshot.getLastChunkHashCode())){
380 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
381 new ArrayList<ReplicatedLogEntry>(),
382 installSnapshot.getLastIncludedIndex(),
383 installSnapshot.getLastIncludedTerm(),
384 installSnapshot.getLastIncludedIndex(),
385 installSnapshot.getLastIncludedTerm(),
386 context.getTermInformation().getCurrentTerm(),
387 context.getTermInformation().getVotedFor(),
388 context.getPeerServerInfo(true));
390 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
392 public void onSuccess() {
393 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
395 sender.tell(reply, actor());
399 public void onFailure() {
400 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
404 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
406 snapshotTracker = null;
408 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
410 sender.tell(reply, actor());
412 } catch (SnapshotTracker.InvalidChunkException e) {
413 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
415 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
416 -1, false), actor());
417 snapshotTracker = null;
419 } catch (Exception e){
420 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
422 //send reply with success as false. The chunk will be sent again on failure
423 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
424 installSnapshot.getChunkIndex(), false), actor());
430 public void close() {
435 SnapshotTracker getSnapshotTracker(){
436 return snapshotTracker;