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.messages.AppendEntries;
21 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
22 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
23 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
24 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
25 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
28 * The behavior of a RaftActor in the Follower state
31 * <li> Respond to RPCs from candidates and leaders
32 * <li> If election timeout elapses without receiving AppendEntries
33 * RPC from current leader or granting vote to candidate:
34 * convert to candidate
37 public class Follower extends AbstractRaftActorBehavior {
39 private SnapshotTracker snapshotTracker = null;
41 public Follower(RaftActorContext context) {
42 super(context, RaftState.Follower);
44 scheduleElection(electionDuration());
47 private boolean isLogEntryPresent(long index){
48 if(index == context.getReplicatedLog().getSnapshotIndex()){
52 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
55 return previousEntry != null;
59 private long getLogEntryTerm(long index){
60 if(index == context.getReplicatedLog().getSnapshotIndex()){
61 return context.getReplicatedLog().getSnapshotTerm();
64 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
67 if(previousEntry != null){
68 return previousEntry.getTerm();
74 @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
75 AppendEntries appendEntries) {
77 int numLogEntries = appendEntries.getEntries() != null ? appendEntries.getEntries().size() : 0;
78 if(LOG.isTraceEnabled()) {
79 LOG.trace("{}: handleAppendEntries: {}", logName(), appendEntries);
80 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
81 LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
84 // TODO : Refactor this method into a bunch of smaller methods
85 // to make it easier to read. Before refactoring ensure tests
86 // cover the code properly
88 // 1. Reply false if term < currentTerm (§5.1)
89 // This is handled in the appendEntries method of the base class
91 // If we got here then we do appear to be talking to the leader
92 leaderId = appendEntries.getLeaderId();
94 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
95 // whose term matches prevLogTerm (§5.3)
97 long prevLogTerm = getLogEntryTerm(appendEntries.getPrevLogIndex());
98 boolean prevEntryPresent = isLogEntryPresent(appendEntries.getPrevLogIndex());
101 boolean outOfSync = true;
103 // First check if the logs are in sync or not
104 long lastIndex = lastIndex();
105 if (lastIndex == -1 && appendEntries.getPrevLogIndex() != -1) {
107 // The follower's log is out of sync because the leader does have
108 // an entry at prevLogIndex and this follower has no entries in
111 LOG.debug("{}: The followers log is empty and the senders prevLogIndex is {}",
112 logName(), appendEntries.getPrevLogIndex());
113 } else if (lastIndex > -1 && appendEntries.getPrevLogIndex() != -1 && !prevEntryPresent) {
115 // The follower's log is out of sync because the Leader's
116 // prevLogIndex entry was not found in it's log
118 LOG.debug("{}: The log is not empty but the prevLogIndex {} was not found in it",
119 logName(), appendEntries.getPrevLogIndex());
120 } else if (lastIndex > -1 && prevEntryPresent && prevLogTerm != appendEntries.getPrevLogTerm()) {
122 // The follower's log is out of sync because the Leader's
123 // prevLogIndex entry does exist in the follower's log but it has
124 // a different term in it
127 "{}: Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}",
128 logName(), prevLogTerm, appendEntries.getPrevLogTerm());
134 // We found that the log was out of sync so just send a negative
137 LOG.debug("{}: Follower is out-of-sync, so sending negative reply, lastIndex: {}, lastTerm: {}",
138 logName(), lastIndex, lastTerm());
140 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), false, lastIndex,
141 lastTerm()), actor());
145 if (appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
147 LOG.debug("{}: Number of entries to be appended = {}", logName(),
148 appendEntries.getEntries().size());
150 // 3. If an existing entry conflicts with a new one (same index
151 // but different terms), delete the existing entry and all that
153 int addEntriesFrom = 0;
154 if (context.getReplicatedLog().size() > 0) {
156 // Find the entry up until which the one that is not in the follower's log
157 for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
158 ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
159 ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
161 if (newEntry == null) {
162 //newEntry not found in the log
166 if (newEntry.getTerm() == matchEntry.getTerm()) {
170 LOG.debug("{}: Removing entries from log starting at {}", logName(),
171 matchEntry.getIndex());
173 // Entries do not match so remove all subsequent entries
174 context.getReplicatedLog().removeFromAndPersist(matchEntry.getIndex());
179 lastIndex = lastIndex();
180 LOG.debug("{}: After cleanup entries to be added from = {}", logName(),
181 (addEntriesFrom + lastIndex));
183 // 4. Append any new entries not already in the log
184 for (int i = addEntriesFrom; i < appendEntries.getEntries().size(); i++) {
185 ReplicatedLogEntry entry = appendEntries.getEntries().get(i);
187 LOG.debug("{}: Append entry to log {}", logName(), entry.getData());
189 context.getReplicatedLog().appendAndPersist(entry);
192 LOG.debug("{}: Log size is now {}", logName(), context.getReplicatedLog().size());
195 // 5. If leaderCommit > commitIndex, set commitIndex =
196 // min(leaderCommit, index of last new entry)
198 lastIndex = lastIndex();
199 long prevCommitIndex = context.getCommitIndex();
201 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(), lastIndex));
203 if (prevCommitIndex != context.getCommitIndex()) {
204 LOG.debug("{}: Commit index set to {}", logName(), context.getCommitIndex());
207 // If commitIndex > lastApplied: increment lastApplied, apply
208 // log[lastApplied] to state machine (§5.3)
209 // check if there are any entries to be applied. last-applied can be equal to last-index
210 if (appendEntries.getLeaderCommit() > context.getLastApplied() &&
211 context.getLastApplied() < lastIndex) {
212 if(LOG.isDebugEnabled()) {
213 LOG.debug("{}: applyLogToStateMachine, " +
214 "appendEntries.getLeaderCommit(): {}," +
215 "context.getLastApplied(): {}, lastIndex(): {}", logName(),
216 appendEntries.getLeaderCommit(), context.getLastApplied(), lastIndex);
219 applyLogToStateMachine(appendEntries.getLeaderCommit());
222 AppendEntriesReply reply = new AppendEntriesReply(context.getId(), currentTerm(), true,
223 lastIndex, lastTerm());
225 if(LOG.isTraceEnabled()) {
226 LOG.trace("{}: handleAppendEntries returning : {}", logName(), reply);
227 } else if(LOG.isDebugEnabled() && numLogEntries > 0) {
228 LOG.debug("{}: handleAppendEntries returning : {}", logName(), reply);
231 sender.tell(reply, actor());
233 if (!context.isSnapshotCaptureInitiated()) {
234 super.performSnapshotWithoutCapture(appendEntries.getReplicatedToAllIndex());
240 @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
241 AppendEntriesReply appendEntriesReply) {
245 @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
246 RequestVoteReply requestVoteReply) {
250 @Override public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
252 Object message = fromSerializableMessage(originalMessage);
254 if (message instanceof RaftRPC) {
255 RaftRPC rpc = (RaftRPC) message;
256 // If RPC request or response contains term T > currentTerm:
257 // set currentTerm = T, convert to follower (§5.1)
258 // This applies to all RPC messages and responses
259 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
260 LOG.debug("{}: Term {} in \"{}\" message is greater than follower's term {} - updating term",
261 logName(), rpc.getTerm(), rpc, context.getTermInformation().getCurrentTerm());
263 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
267 if (message instanceof ElectionTimeout) {
268 LOG.debug("{}: Received ElectionTimeout - switching to Candidate", logName());
269 return switchBehavior(new Candidate(context));
271 } else if (message instanceof InstallSnapshot) {
272 InstallSnapshot installSnapshot = (InstallSnapshot) message;
273 handleInstallSnapshot(sender, installSnapshot);
276 scheduleElection(electionDuration());
278 return super.handleMessage(sender, message);
281 private void handleInstallSnapshot(ActorRef sender, InstallSnapshot installSnapshot) {
284 LOG.debug("{}: InstallSnapshot received from leader {}, datasize: {} , Chunk: {}/{}",
285 logName(), installSnapshot.getLeaderId(), installSnapshot.getData().size(),
286 installSnapshot.getChunkIndex(), installSnapshot.getTotalChunks());
288 if(snapshotTracker == null){
289 snapshotTracker = new SnapshotTracker(LOG, installSnapshot.getTotalChunks());
293 if(snapshotTracker.addChunk(installSnapshot.getChunkIndex(), installSnapshot.getData(),
294 installSnapshot.getLastChunkHashCode())){
295 Snapshot snapshot = Snapshot.create(snapshotTracker.getSnapshot(),
296 new ArrayList<ReplicatedLogEntry>(),
297 installSnapshot.getLastIncludedIndex(),
298 installSnapshot.getLastIncludedTerm(),
299 installSnapshot.getLastIncludedIndex(),
300 installSnapshot.getLastIncludedTerm());
302 actor().tell(new ApplySnapshot(snapshot), actor());
304 snapshotTracker = null;
308 InstallSnapshotReply reply = new InstallSnapshotReply(
309 currentTerm(), context.getId(), installSnapshot.getChunkIndex(), true);
311 LOG.debug("{}: handleInstallSnapshot returning: {}", logName(), reply);
313 sender.tell(reply, actor());
315 } catch (SnapshotTracker.InvalidChunkException e) {
316 LOG.debug("{}: Exception in InstallSnapshot of follower", logName(), e);
318 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
319 -1, false), actor());
320 snapshotTracker = null;
322 } catch (Exception e){
323 LOG.error("{}: Exception in InstallSnapshot of follower", logName(), e);
325 //send reply with success as false. The chunk will be sent again on failure
326 sender.tell(new InstallSnapshotReply(currentTerm(), context.getId(),
327 installSnapshot.getChunkIndex(), false), actor());
333 public void close() throws Exception {
338 SnapshotTracker getSnapshotTracker(){
339 return snapshotTracker;