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.base.messages.ApplySnapshot;
16 import org.opendaylight.controller.cluster.raft.base.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 if(appendEntries.getEntries() != null && appendEntries.getEntries().size() > 0) {
45 .info("Follower: Received {}", appendEntries.toString());
48 // TODO : Refactor this method into a bunch of smaller methods
49 // to make it easier to read. Before refactoring ensure tests
50 // cover the code properly
52 // 1. Reply false if term < currentTerm (§5.1)
53 // This is handled in the appendEntries method of the base class
55 // If we got here then we do appear to be talking to the leader
56 leaderId = appendEntries.getLeaderId();
58 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
59 // whose term matches prevLogTerm (§5.3)
61 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
62 .get(appendEntries.getPrevLogIndex());
65 boolean outOfSync = true;
67 // First check if the logs are in sync or not
69 && appendEntries.getPrevLogIndex() != -1) {
71 // The follower's log is out of sync because the leader does have
72 // an entry at prevLogIndex and this follower has no entries in
75 context.getLogger().debug(
76 "The followers log is empty and the senders prevLogIndex is {}",
77 appendEntries.getPrevLogIndex());
79 } else if (lastIndex() > -1
80 && appendEntries.getPrevLogIndex() != -1
81 && previousEntry == null) {
83 // The follower's log is out of sync because the Leader's
84 // prevLogIndex entry was not found in it's log
86 context.getLogger().debug(
87 "The log is not empty but the prevLogIndex {} was not found in it",
88 appendEntries.getPrevLogIndex());
90 } else if (lastIndex() > -1
91 && previousEntry != null
92 && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
94 // The follower's log is out of sync because the Leader's
95 // prevLogIndex entry does exist in the follower's log but it has
96 // a different term in it
98 context.getLogger().debug(
99 "Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}"
100 , previousEntry.getTerm()
101 , appendEntries.getPrevLogTerm());
107 // We found that the log was out of sync so just send a negative
110 new AppendEntriesReply(context.getId(), currentTerm(), false,
111 lastIndex(), lastTerm()), actor()
116 if (appendEntries.getEntries() != null
117 && appendEntries.getEntries().size() > 0) {
118 context.getLogger().debug(
119 "Number of entries to be appended = " + appendEntries
123 // 3. If an existing entry conflicts with a new one (same index
124 // but different terms), delete the existing entry and all that
126 int addEntriesFrom = 0;
127 if (context.getReplicatedLog().size() > 0) {
129 // Find the entry up until which the one that is not in the
132 i < appendEntries.getEntries()
133 .size(); i++, addEntriesFrom++) {
134 ReplicatedLogEntry matchEntry =
135 appendEntries.getEntries().get(i);
136 ReplicatedLogEntry newEntry = context.getReplicatedLog()
137 .get(matchEntry.getIndex());
139 if (newEntry == null) {
140 //newEntry not found in the log
144 if (newEntry.getTerm() == matchEntry
149 context.getLogger().debug(
150 "Removing entries from log starting at "
151 + matchEntry.getIndex()
154 // Entries do not match so remove all subsequent entries
155 context.getReplicatedLog()
156 .removeFromAndPersist(matchEntry.getIndex());
161 context.getLogger().debug(
162 "After cleanup entries to be added from = " + (addEntriesFrom
166 // 4. Append any new entries not already in the log
167 for (int i = addEntriesFrom;
168 i < appendEntries.getEntries().size(); i++) {
170 context.getLogger().info(
171 "Append entry to log " + appendEntries.getEntries().get(
175 context.getReplicatedLog()
176 .appendAndPersist(appendEntries.getEntries().get(i));
179 context.getLogger().debug(
180 "Log size is now " + context.getReplicatedLog().size());
184 // 5. If leaderCommit > commitIndex, set commitIndex =
185 // min(leaderCommit, index of last new entry)
187 long prevCommitIndex = context.getCommitIndex();
189 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(),
190 context.getReplicatedLog().lastIndex()));
192 if (prevCommitIndex != context.getCommitIndex()) {
194 .debug("Commit index set to " + context.getCommitIndex());
197 // If commitIndex > lastApplied: increment lastApplied, apply
198 // log[lastApplied] to state machine (§5.3)
199 if (appendEntries.getLeaderCommit() > context.getLastApplied()) {
200 applyLogToStateMachine(appendEntries.getLeaderCommit());
203 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), true,
204 lastIndex(), lastTerm()), actor());
209 @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
210 AppendEntriesReply appendEntriesReply) {
214 @Override protected RaftState handleRequestVoteReply(ActorRef sender,
215 RequestVoteReply requestVoteReply) {
219 @Override public RaftState state() {
220 return RaftState.Follower;
223 @Override public RaftState handleMessage(ActorRef sender, Object originalMessage) {
225 Object message = fromSerializableMessage(originalMessage);
227 if (message instanceof RaftRPC) {
228 RaftRPC rpc = (RaftRPC) message;
229 // If RPC request or response contains term T > currentTerm:
230 // set currentTerm = T, convert to follower (§5.1)
231 // This applies to all RPC messages and responses
232 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
233 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
237 if (message instanceof ElectionTimeout) {
238 return RaftState.Candidate;
240 } else if (message instanceof InstallSnapshot) {
241 InstallSnapshot installSnapshot = (InstallSnapshot) message;
242 actor().tell(new ApplySnapshot(installSnapshot.getData()), actor());
245 scheduleElection(electionDuration());
247 return super.handleMessage(sender, message);
250 @Override public void close() throws Exception {