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 org.opendaylight.controller.cluster.raft.RaftActorContext;
13 import org.opendaylight.controller.cluster.raft.RaftState;
14 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
15 import org.opendaylight.controller.cluster.raft.internal.messages.ApplySnapshot;
16 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
18 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
19 import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
20 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
21 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
24 * The behavior of a RaftActor in the Follower state
27 * <li> Respond to RPCs from candidates and leaders
28 * <li> If election timeout elapses without receiving AppendEntries
29 * RPC from current leader or granting vote to candidate:
30 * convert to candidate
33 public class Follower extends AbstractRaftActorBehavior {
34 public Follower(RaftActorContext context) {
37 scheduleElection(electionDuration());
40 @Override protected RaftState handleAppendEntries(ActorRef sender,
41 AppendEntries appendEntries) {
43 // TODO : Refactor this method into a bunch of smaller methods
44 // to make it easier to read. Before refactoring ensure tests
45 // cover the code properly
47 // 1. Reply false if term < currentTerm (§5.1)
48 // This is handled in the appendEntries method of the base class
50 // If we got here then we do appear to be talking to the leader
51 leaderId = appendEntries.getLeaderId();
53 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
54 // whose term matches prevLogTerm (§5.3)
56 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
57 .get(appendEntries.getPrevLogIndex());
60 boolean outOfSync = true;
62 // First check if the logs are in sync or not
64 && appendEntries.getPrevLogIndex() != -1) {
66 // The follower's log is out of sync because the leader does have
67 // an entry at prevLogIndex and this follower has no entries in
70 context.getLogger().debug(
71 "The followers log is empty and the senders prevLogIndex is {}",
72 appendEntries.getPrevLogIndex());
74 } else if (lastIndex() > -1
75 && appendEntries.getPrevLogIndex() != -1
76 && previousEntry == null) {
78 // The follower's log is out of sync because the Leader's
79 // prevLogIndex entry was not found in it's log
81 context.getLogger().debug(
82 "The log is not empty but the prevLogIndex {} was not found in it",
83 appendEntries.getPrevLogIndex());
85 } else if (lastIndex() > -1
86 && previousEntry != null
87 && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
89 // The follower's log is out of sync because the Leader's
90 // prevLogIndex entry does exist in the follower's log but it has
91 // a different term in it
93 context.getLogger().debug(
94 "Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}"
95 , previousEntry.getTerm()
96 , appendEntries.getPrevLogTerm());
102 // We found that the log was out of sync so just send a negative
105 new AppendEntriesReply(context.getId(), currentTerm(), false,
106 lastIndex(), lastTerm()), actor()
111 if (appendEntries.getEntries() != null
112 && appendEntries.getEntries().size() > 0) {
113 context.getLogger().debug(
114 "Number of entries to be appended = " + appendEntries
118 // 3. If an existing entry conflicts with a new one (same index
119 // but different terms), delete the existing entry and all that
121 int addEntriesFrom = 0;
122 if (context.getReplicatedLog().size() > 0) {
124 // Find the entry up until which the one that is not in the
127 i < appendEntries.getEntries()
128 .size(); i++, addEntriesFrom++) {
129 ReplicatedLogEntry matchEntry =
130 appendEntries.getEntries().get(i);
131 ReplicatedLogEntry newEntry = context.getReplicatedLog()
132 .get(matchEntry.getIndex());
134 if (newEntry == null) {
135 //newEntry not found in the log
139 if (newEntry.getTerm() == matchEntry
144 context.getLogger().debug(
145 "Removing entries from log starting at "
146 + matchEntry.getIndex()
149 // Entries do not match so remove all subsequent entries
150 context.getReplicatedLog()
151 .removeFromAndPersist(matchEntry.getIndex());
156 context.getLogger().debug(
157 "After cleanup entries to be added from = " + (addEntriesFrom
161 // 4. Append any new entries not already in the log
162 for (int i = addEntriesFrom;
163 i < appendEntries.getEntries().size(); i++) {
165 context.getLogger().debug(
166 "Append entry to log " + appendEntries.getEntries().get(i).getData()
169 context.getReplicatedLog()
170 .appendAndPersist(appendEntries.getEntries().get(i));
173 context.getLogger().debug(
174 "Log size is now " + context.getReplicatedLog().size());
178 // 5. If leaderCommit > commitIndex, set commitIndex =
179 // min(leaderCommit, index of last new entry)
181 long prevCommitIndex = context.getCommitIndex();
183 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(),
184 context.getReplicatedLog().lastIndex()));
186 if (prevCommitIndex != context.getCommitIndex()) {
188 .debug("Commit index set to " + context.getCommitIndex());
191 // If commitIndex > lastApplied: increment lastApplied, apply
192 // log[lastApplied] to state machine (§5.3)
193 if (appendEntries.getLeaderCommit() > context.getLastApplied()) {
194 applyLogToStateMachine(appendEntries.getLeaderCommit());
197 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), true,
198 lastIndex(), lastTerm()), actor());
203 @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
204 AppendEntriesReply appendEntriesReply) {
208 @Override protected RaftState handleRequestVoteReply(ActorRef sender,
209 RequestVoteReply requestVoteReply) {
213 @Override public RaftState state() {
214 return RaftState.Follower;
217 @Override public RaftState handleMessage(ActorRef sender, Object originalMessage) {
219 Object message = fromSerializableMessage(originalMessage);
221 if (message instanceof RaftRPC) {
222 RaftRPC rpc = (RaftRPC) message;
223 // If RPC request or response contains term T > currentTerm:
224 // set currentTerm = T, convert to follower (§5.1)
225 // This applies to all RPC messages and responses
226 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
227 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
231 if (message instanceof ElectionTimeout) {
232 return RaftState.Candidate;
234 } else if (message instanceof InstallSnapshot) {
235 InstallSnapshot installSnapshot = (InstallSnapshot) message;
236 actor().tell(new ApplySnapshot(installSnapshot.getData()), actor());
239 scheduleElection(electionDuration());
241 return super.handleMessage(sender, message);
244 @Override public void close() throws Exception {