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 com.google.common.annotations.VisibleForTesting;
13 import java.util.ArrayList;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
17 import org.opendaylight.controller.cluster.raft.Snapshot;
18 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
19 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
20 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
21 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
22 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
23 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
24 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
25 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
26 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
29 * The behavior of a RaftActor in the Follower state
32 * <li> Respond to RPCs from candidates and leaders
33 * <li> If election timeout elapses without receiving AppendEntries
34 * RPC from current leader or granting vote to candidate:
35 * convert to candidate
38 public class Follower extends AbstractRaftActorBehavior {
42 private SnapshotTracker snapshotTracker = null;
44 private final InitialSyncStatusTracker initialSyncStatusTracker;
46 public Follower(RaftActorContext context) {
47 super(context, RaftState.Follower);
49 scheduleElection(electionDuration());
51 initialSyncStatusTracker = new InitialSyncStatusTracker(context.getActor());
54 private boolean isLogEntryPresent(long index){
55 if(index == context.getReplicatedLog().getSnapshotIndex()){
59 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
62 return previousEntry != null;
66 private long getLogEntryTerm(long index){
67 if(index == context.getReplicatedLog().getSnapshotIndex()){
68 return context.getReplicatedLog().getSnapshotTerm();
71 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
74 if(previousEntry != null){
75 return previousEntry.getTerm();
81 private void updateInitialSyncStatus(long currentLeaderCommit, String leaderId){
82 initialSyncStatusTracker.update(leaderId, currentLeaderCommit, context.getCommitIndex());
85 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
86 AppendEntries appendEntries) {
88 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
89 if(LOG.isTraceEnabled()) {
90 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
91 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
92 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
95 // TODO : Refactor this method into a bunch of smaller methods
96 // to make it easier to read. Before refactoring ensure tests
97 // cover the code properly
99 if (snapshotTracker != null) {
100 // if snapshot install is in progress, follower should just acknowledge append entries with a reply.
101 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
102 lastIndex(), lastTerm());
104 if(LOG.isDebugEnabled()) {
105 LOG.debug("{}: snapshot install is in progress, replying immediately with {}", logName(), reply);
107 sender.tell(reply, actor());
112 // 1. Reply false if term < currentTerm (§5.1)
113 // This is handled in the appendEntries method of the base class
115 // If we got here then we do appear to be talking to the leader
116 leaderId = appendEntries.getLeaderId();
118 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
119 // whose term matches prevLogTerm (§5.3)
121 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
122 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
124 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
126 boolean outOfSync = true;
128 // First check if the logs are in sync or not
129 long lastIndex = lastIndex();
130 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
132 // The follower's log is out of sync because the leader does have
133 // an entry at prevLogIndex and this follower has no entries in
136 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
137 logName(), appendEntries.getPrevLogIndex());
138 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
140 // The follower's log is out of sync because the Leader's
141 // prevLogIndex entry was not found in it's log
143 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
144 logName(), appendEntries.getPrevLogIndex());
145 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
147 // The follower's log is out of sync because the Leader's
148 // prevLogIndex entry does exist in the follower's log but it has
149 // a different term in it
152 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
153 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
159 // We found that the log was out of sync so just send a negative
162 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
163 logName(), lastIndex, lastTerm());
165 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
166 lastTerm()), actor());
170 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
172 LOG.debug("{}: Number of entries to be appended = {}", logName(),
173 appendEntries.getEntries().size());
175 // 3. If an existing entry conflicts with a new one (same index
176 // but different terms), delete the existing entry and all that
178 int addEntriesFrom = 0;
179 if (context.getReplicatedLog().size() > 0) {
181 // Find the entry up until which the one that is not in the follower's log
182 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
183 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
184 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
186 if (newEntry == null) {
187 //newEntry not found in the log
191 if (newEntry.getTerm() == matchEntry.getTerm()) {
195 LOG.debug("{}: Removing entries from log starting at {}", logName(),
196 matchEntry.getIndex());
198 // Entries do not match so remove all subsequent entries
199 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
204 lastIndex = lastIndex();
205 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
206 (addEntriesFrom + lastIndex));
208 // 4. Append any new entries not already in the log
209 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
210 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
212 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
214 context.getReplicatedLog().appendAndPersist(entry);
217 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
220 // 5. If leaderCommit > commitIndex, set commitIndex =
221 // min(leaderCommit, index of last new entry)
223 lastIndex = lastIndex();
224 long prevCommitIndex = context.getCommitIndex();
226 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
228 if (prevCommitIndex != context.getCommitIndex()) {
229 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
232 // If commitIndex > lastApplied: increment lastApplied, apply
233 // log[lastApplied] to state machine (§5.3)
234 // check if there are any entries to be applied. last-applied can be equal to last-index
235 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
236 context.getLastApplied() < lastIndex) {
237 if(LOG.isDebugEnabled()) {
238 LOG.debug("{}: applyLogToStateMachine, " +
239 "appendEntries.getLeaderCommit(): {}," +
240 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
241 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
244 applyLogToStateMachine(appendEntries.getLeaderCommit());
247 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
248 lastIndex, lastTerm());
250 if(LOG.isTraceEnabled()) {
251 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
252 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
253 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
256 sender.tell(reply, actor());
258 if (!context.isSnapshotCaptureInitiated()) {
259 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
265 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
266 AppendEntriesReply appendEntriesReply) {
270 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
271 RequestVoteReply requestVoteReply) {
275 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
277 Object message = fromSerializableMessage(originalMessage);
279 if (message instanceof RaftRPC) {
280 RaftRPC rpc = (RaftRPC) message;
281 // If RPC request or response contains term T > currentTerm:
282 // set currentTerm = T, convert to follower (§5.1)
283 // This applies to all RPC messages and responses
284 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
285 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
286 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
288 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
292 if (message instanceof ElectionTimeout) {
293 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
294 return switchBehavior(new Candidate(context));
296 } else if (message instanceof InstallSnapshot) {
297 InstallSnapshot installSnapshot = (InstallSnapshot) message;
298 handleInstallSnapshot(sender, installSnapshot);
301 scheduleElection(electionDuration());
303 return super.handleMessage(sender, message);
306 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
308 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
309 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
310 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
312 if(snapshotTracker == null){
313 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
316 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
319 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
320 installSnapshot.getLastChunkHashCode())){
321 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
322 new ArrayList<ReplicatedLogEntry>(),
323 installSnapshot.getLastIncludedIndex(),
324 installSnapshot.getLastIncludedTerm(),
325 installSnapshot.getLastIncludedIndex(),
326 installSnapshot.getLastIncludedTerm());
328 actor().tell(new ApplySnapshot(snapshot), actor());
330 snapshotTracker = null;
334 InstallSnapshotReply reply = new InstallSnapshotReply(
335 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
337 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
339 sender.tell(reply, actor());
341 } catch (SnapshotTracker.InvalidChunkException e) {
342 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
344 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
345 -1, false), actor());
346 snapshotTracker = null;
348 } catch (Exception e){
349 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
351 //send reply with success as false. The chunk will be sent again on failure
352 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
353 installSnapshot.getChunkIndex(), false), actor());
359 public void close() throws Exception {
364 SnapshotTracker getSnapshotTracker(){
365 return snapshotTracker;
368 private class InitialSyncStatusTracker {
370 private static final long INVALID_LOG_INDEX = -2L;
371 private long initialLeaderCommit = INVALID_LOG_INDEX;
372 private boolean initialSyncUpDone = false;
373 private String syncedLeaderId = null;
374 private final ActorRef actor;
376 public InitialSyncStatusTracker(ActorRef actor) {
380 public void update(String leaderId, long leaderCommit, long commitIndex){
382 if(!leaderId.equals(syncedLeaderId)){
383 initialSyncUpDone = false;
384 initialLeaderCommit = INVALID_LOG_INDEX;
385 syncedLeaderId = leaderId;
388 if(!initialSyncUpDone){
389 if(initialLeaderCommit == INVALID_LOG_INDEX){
390 actor.tell(new FollowerInitialSyncUpStatus(false, getId()), ActorRef.noSender());
391 initialLeaderCommit = leaderCommit;
392 } else if(commitIndex >= initialLeaderCommit){
393 actor.tell(new FollowerInitialSyncUpStatus(true, getId()), ActorRef.noSender());
394 initialSyncUpDone = true;