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 // 1. Reply false if term < currentTerm (§5.1)
100 // This is handled in the appendEntries method of the base class
102 // If we got here then we do appear to be talking to the leader
103 leaderId = appendEntries.getLeaderId();
105 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
106 // whose term matches prevLogTerm (§5.3)
108 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
109 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
111 updateInitialSyncStatus(appendEntries.getLeaderCommit(), appendEntries.getLeaderId());
113 boolean outOfSync = true;
115 // First check if the logs are in sync or not
116 long lastIndex = lastIndex();
117 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
119 // The follower's log is out of sync because the leader does have
120 // an entry at prevLogIndex and this follower has no entries in
123 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
124 logName(), appendEntries.getPrevLogIndex());
125 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
127 // The follower's log is out of sync because the Leader's
128 // prevLogIndex entry was not found in it's log
130 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
131 logName(), appendEntries.getPrevLogIndex());
132 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
134 // The follower's log is out of sync because the Leader's
135 // prevLogIndex entry does exist in the follower's log but it has
136 // a different term in it
139 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
140 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
146 // We found that the log was out of sync so just send a negative
149 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
150 logName(), lastIndex, lastTerm());
152 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
153 lastTerm()), actor());
157 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
159 LOG.debug("{}: Number of entries to be appended = {}", logName(),
160 appendEntries.getEntries().size());
162 // 3. If an existing entry conflicts with a new one (same index
163 // but different terms), delete the existing entry and all that
165 int addEntriesFrom = 0;
166 if (context.getReplicatedLog().size() > 0) {
168 // Find the entry up until which the one that is not in the follower's log
169 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
170 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
171 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
173 if (newEntry == null) {
174 //newEntry not found in the log
178 if (newEntry.getTerm() == matchEntry.getTerm()) {
182 LOG.debug("{}: Removing entries from log starting at {}", logName(),
183 matchEntry.getIndex());
185 // Entries do not match so remove all subsequent entries
186 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
191 lastIndex = lastIndex();
192 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
193 (addEntriesFrom + lastIndex));
195 // 4. Append any new entries not already in the log
196 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
197 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
199 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
201 context.getReplicatedLog().appendAndPersist(entry);
204 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
207 // 5. If leaderCommit > commitIndex, set commitIndex =
208 // min(leaderCommit, index of last new entry)
210 lastIndex = lastIndex();
211 long prevCommitIndex = context.getCommitIndex();
213 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
215 if (prevCommitIndex != context.getCommitIndex()) {
216 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
219 // If commitIndex > lastApplied: increment lastApplied, apply
220 // log[lastApplied] to state machine (§5.3)
221 // check if there are any entries to be applied. last-applied can be equal to last-index
222 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
223 context.getLastApplied() < lastIndex) {
224 if(LOG.isDebugEnabled()) {
225 LOG.debug("{}: applyLogToStateMachine, " +
226 "appendEntries.getLeaderCommit(): {}," +
227 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
228 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
231 applyLogToStateMachine(appendEntries.getLeaderCommit());
234 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
235 lastIndex, lastTerm());
237 if(LOG.isTraceEnabled()) {
238 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
239 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
240 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
243 sender.tell(reply, actor());
245 if (!context.isSnapshotCaptureInitiated()) {
246 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
252 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
253 AppendEntriesReply appendEntriesReply) {
257 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
258 RequestVoteReply requestVoteReply) {
262 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
264 Object message = fromSerializableMessage(originalMessage);
266 if (message instanceof RaftRPC) {
267 RaftRPC rpc = (RaftRPC) message;
268 // If RPC request or response contains term T > currentTerm:
269 // set currentTerm = T, convert to follower (§5.1)
270 // This applies to all RPC messages and responses
271 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
272 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
273 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
275 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
279 if (message instanceof ElectionTimeout) {
280 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
281 return switchBehavior(new Candidate(context));
283 } else if (message instanceof InstallSnapshot) {
284 InstallSnapshot installSnapshot = (InstallSnapshot) message;
285 handleInstallSnapshot(sender, installSnapshot);
288 scheduleElection(electionDuration());
290 return super.handleMessage(sender, message);
293 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
295 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
296 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
297 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
299 if(snapshotTracker == null){
300 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
303 updateInitialSyncStatus(installSnapshot.getLastIncludedIndex(), installSnapshot.getLeaderId());
306 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
307 installSnapshot.getLastChunkHashCode())){
308 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
309 new ArrayList<ReplicatedLogEntry>(),
310 installSnapshot.getLastIncludedIndex(),
311 installSnapshot.getLastIncludedTerm(),
312 installSnapshot.getLastIncludedIndex(),
313 installSnapshot.getLastIncludedTerm());
315 actor().tell(new ApplySnapshot(snapshot), actor());
317 snapshotTracker = null;
321 InstallSnapshotReply reply = new InstallSnapshotReply(
322 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
324 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
326 sender.tell(reply, actor());
328 } catch (SnapshotTracker.InvalidChunkException e) {
329 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
331 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
332 -1, false), actor());
333 snapshotTracker = null;
335 } catch (Exception e){
336 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
338 //send reply with success as false. The chunk will be sent again on failure
339 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
340 installSnapshot.getChunkIndex(), false), actor());
346 public void close() throws Exception {
351 SnapshotTracker getSnapshotTracker(){
352 return snapshotTracker;
355 private static class InitialSyncStatusTracker {
357 private static final long INVALID_LOG_INDEX = -2L;
358 private long initialLeaderCommit = INVALID_LOG_INDEX;
359 private boolean initialSyncUpDone = false;
360 private String syncedLeaderId = null;
361 private final ActorRef actor;
363 public InitialSyncStatusTracker(ActorRef actor) {
367 public void update(String leaderId, long leaderCommit, long commitIndex){
369 if(!leaderId.equals(syncedLeaderId)){
370 initialSyncUpDone = false;
371 initialLeaderCommit = INVALID_LOG_INDEX;
372 syncedLeaderId = leaderId;
375 if(!initialSyncUpDone){
376 if(initialLeaderCommit == INVALID_LOG_INDEX){
377 actor.tell(new FollowerInitialSyncUpStatus(false), ActorRef.noSender());
378 initialLeaderCommit = leaderCommit;
379 } else if(commitIndex >= initialLeaderCommit){
380 actor.tell(new FollowerInitialSyncUpStatus(true), ActorRef.noSender());
381 initialSyncUpDone = true;