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) {
58 public Follower(RaftActorContext context, String initialLeaderId) {
59 super(context, RaftState.Follower);
60 leaderId = initialLeaderId;
62 initialSyncStatusTracker = new SyncStatusTracker(context.getActor(), getId(), SYNC_THRESHOLD);
64 if(canStartElection()) {
65 if (context.getPeerIds().isEmpty() && getLeaderId() == null) {
66 actor().tell(ELECTION_TIMEOUT, actor());
68 scheduleElection(electionDuration());
74 private boolean isLogEntryPresent(long index){
75 if(index == context.getReplicatedLog().getSnapshotIndex()){
79 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
82 return previousEntry != null;
86 private long getLogEntryTerm(long index){
87 if(index == context.getReplicatedLog().getSnapshotIndex()){
88 return context.getReplicatedLog().getSnapshotTerm();
91 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
94 if(previousEntry != null){
95 return previousEntry.getTerm();
101 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
102 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
105 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
106 AppendEntries appendEntries) {
108 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
109 if(LOG.isTraceEnabled()) {
110 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
111 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
112 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
115 // TODO : Refactor this method into a bunch of smaller methods
116 // to make it easier to read. Before refactoring ensure tests
117 // cover the code properly
119 if (snapshotTracker != null || context.getSnapshotManager().isApplying()) {
120 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
121 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
122 lastIndex(), lastTerm(), context.getPayloadVersion());
124 if(LOG.isDebugEnabled()) {
125 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
127 sender.tell(reply, actor());
132 // If we got here then we do appear to be talking to the leader
133 leaderId = appendEntries.getLeaderId();
135 setLeaderPayloadVersion(appendEntries.getPayloadVersion());
137 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
138 // First check if the logs are in sync or not
139 long lastIndex = lastIndex();
141 if (isOutOfSync(appendEntries)) {
142 // We found that the log was out of sync so just send a negative
145 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
146 logName(), lastIndex, lastTerm());
148 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
149 lastTerm(), context.getPayloadVersion()), actor());
153 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
155 LOG.debug("{}: Number of entries to be appended = {}", logName(),
156 appendEntries.getEntries().size());
158 // 3. If an existing entry conflicts with a new one (same index
159 // but different terms), delete the existing entry and all that
161 int addEntriesFrom = 0;
162 if (context.getReplicatedLog().size() > 0) {
164 // Find the entry up until the one that is not in the follower's log
165 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
166 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
167 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
169 if (newEntry == null) {
170 //newEntry not found in the log
174 if (newEntry.getTerm() == matchEntry.getTerm()) {
178 if(!context.getRaftPolicy().applyModificationToStateBeforeConsensus()) {
180 LOG.debug("{}: Removing entries from log starting at {}", logName(),
181 matchEntry.getIndex());
183 // Entries do not match so remove all subsequent entries
184 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
187 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
188 lastTerm(), context.getPayloadVersion(), true), actor());
194 lastIndex = lastIndex();
195 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
196 (addEntriesFrom + lastIndex));
198 // 4. Append any new entries not already in the log
199 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
200 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
202 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
204 context.getReplicatedLog().appendAndPersist(entry, appendAndPersistCallback);
206 if(entry.getData() instanceof ServerConfigurationPayload) {
207 context.updatePeerIds((ServerConfigurationPayload)entry.getData());
211 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
214 // 5. If leaderCommit > commitIndex, set commitIndex =
215 // min(leaderCommit, index of last new entry)
217 lastIndex = lastIndex();
218 long prevCommitIndex = context.getCommitIndex();
220 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
222 if (prevCommitIndex != context.getCommitIndex()) {
223 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
226 // If commitIndex > lastApplied: increment lastApplied, apply
227 // log[lastApplied] to state machine (ยง5.3)
228 // check if there are any entries to be applied. last-applied can be equal to last-index
229 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
230 context.getLastApplied() < lastIndex) {
231 if(LOG.isDebugEnabled()) {
232 LOG.debug("{}: applyLogToStateMachine, " +
233 "appendEntries.getLeaderCommit(): {}," +
234 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
235 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
238 applyLogToStateMachine(appendEntries.getLeaderCommit());
241 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
242 lastIndex, lastTerm(), context.getPayloadVersion());
244 if(LOG.isTraceEnabled()) {
245 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
246 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
247 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
250 sender.tell(reply, actor());
252 if (!context.getSnapshotManager().isCapturing()) {
253 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
259 private boolean isOutOfSync(AppendEntries appendEntries) {
261 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
262 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
263 long lastIndex = lastIndex();
264 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
265 boolean outOfSync = true;
267 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
269 // The follower's log is out of sync because the leader does have
270 // an entry at prevLogIndex and this follower has no entries in
273 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
274 logName(), appendEntries.getPrevLogIndex());
275 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
277 // The follower's log is out of sync because the Leader's
278 // prevLogIndex entry was not found in it's log
280 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it - lastIndex: {}, snapshotIndex: {}",
281 logName(), appendEntries.getPrevLogIndex(), lastIndex, context.getReplicatedLog().getSnapshotIndex());
282 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
284 // The follower's log is out of sync because the Leader's
285 // prevLogIndex entry does exist in the follower's log but it has
286 // a different term in it
289 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
290 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
291 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
292 && appendEntries.getReplicatedToAllIndex() != -1
293 && !isLogEntryPresent(appendEntries.getReplicatedToAllIndex())
294 && !context.getReplicatedLog().isInSnapshot(appendEntries.getReplicatedToAllIndex())) {
295 // This append entry comes from a leader who has it's log aggressively trimmed and so does not have
296 // the previous entry in it's in-memory journal
299 "{}: Cannot append entries because the replicatedToAllIndex {} does not appear to be in the in-memory journal",
300 logName(), appendEntries.getReplicatedToAllIndex());
301 } else if(appendEntries.getPrevLogIndex() == -1 && appendEntries.getPrevLogTerm() == -1
302 && appendEntries.getReplicatedToAllIndex() != -1 && numLogEntries > 0
303 && !isLogEntryPresent(appendEntries.getEntries().get(0).getIndex() - 1)
304 && !context.getReplicatedLog().isInSnapshot(appendEntries.getEntries().get(0).getIndex() - 1)) {
306 "{}: Cannot append entries because the calculated previousIndex {} was not found in the in-memory journal",
307 logName(), appendEntries.getEntries().get(0).getIndex() - 1);
314 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
315 AppendEntriesReply appendEntriesReply) {
319 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
320 RequestVoteReply requestVoteReply) {
324 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
326 Object message = fromSerializableMessage(originalMessage);
328 if (message instanceof RaftRPC) {
329 RaftRPC rpc = (RaftRPC) message;
330 // If RPC request or response contains term T > currentTerm:
331 // set currentTerm = T, convert to follower (ยง5.1)
332 // This applies to all RPC messages and responses
333 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
334 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
335 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
337 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
341 if (message instanceof ElectionTimeout) {
342 if(canStartElection()) {
343 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
344 return internalSwitchBehavior(RaftState.Candidate);
349 } else if (message instanceof InstallSnapshot) {
350 InstallSnapshot installSnapshot = (InstallSnapshot) message;
351 handleInstallSnapshot(sender, installSnapshot);
354 if(message instanceof RaftRPC && (!(message instanceof RequestVote) || (canGrantVote((RequestVote) message)))){
355 scheduleElection(electionDuration());
358 return super.handleMessage(sender, message);
361 private void handleInstallSnapshot(final ActorRef sender, InstallSnapshot installSnapshot) {
363 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
364 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
365 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
367 leaderId = installSnapshot.getLeaderId();
369 if(snapshotTracker == null){
370 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
373 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
376 final InstallSnapshotReply reply = new InstallSnapshotReply(
377 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
379 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
380 installSnapshot.getLastChunkHashCode())){
381 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
382 new ArrayList<ReplicatedLogEntry>(),
383 installSnapshot.getLastIncludedIndex(),
384 installSnapshot.getLastIncludedTerm(),
385 installSnapshot.getLastIncludedIndex(),
386 installSnapshot.getLastIncludedTerm(),
387 context.getTermInformation().getCurrentTerm(),
388 context.getTermInformation().getVotedFor(),
389 context.getPeerServerInfo(true));
391 ApplySnapshot.Callback applySnapshotCallback = new ApplySnapshot.Callback() {
393 public void onSuccess() {
394 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
396 sender.tell(reply, actor());
400 public void onFailure() {
401 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(), -1, false), actor());
405 actor().tell(new ApplySnapshot(snapshot, applySnapshotCallback), actor());
407 snapshotTracker = null;
409 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
411 sender.tell(reply, actor());
413 } catch (SnapshotTracker.InvalidChunkException e) {
414 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
416 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
417 -1, false), actor());
418 snapshotTracker = null;
420 } catch (Exception e){
421 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
423 //send reply with success as false. The chunk will be sent again on failure
424 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
425 installSnapshot.getChunkIndex(), false), actor());
431 public void close() throws Exception {
436 SnapshotTracker getSnapshotTracker(){
437 return snapshotTracker;