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.RequestVoteReply;
23 * The behavior of a RaftActor in the Follower state
26 * <li> Respond to RPCs from candidates and leaders
27 * <li> If election timeout elapses without receiving AppendEntries
28 * RPC from current leader or granting vote to candidate:
29 * convert to candidate
32 public class Follower extends AbstractRaftActorBehavior {
33 public Follower(RaftActorContext context) {
36 scheduleElection(electionDuration());
39 @Override protected RaftState handleAppendEntries(ActorRef sender,
40 AppendEntries appendEntries, RaftState suggestedState) {
42 // If we got here then we do appear to be talking to the leader
43 leaderId = appendEntries.getLeaderId();
45 // 2. Reply false if log doesn’t contain an entry at prevLogIndex
46 // whose term matches prevLogTerm (§5.3)
47 ReplicatedLogEntry previousEntry = context.getReplicatedLog()
48 .get(appendEntries.getPrevLogIndex());
51 boolean noMatchingTerms = true;
54 && appendEntries.getPrevLogIndex() != -1) {
56 context.getLogger().debug(
57 "The followers log is empty and the senders prevLogIndex is {}",
58 appendEntries.getPrevLogIndex());
60 } else if (lastIndex() > -1
61 && appendEntries.getPrevLogIndex() != -1
62 && previousEntry == null) {
64 context.getLogger().debug(
65 "The log is not empty but the prevLogIndex {} was not found in it",
66 appendEntries.getPrevLogIndex());
68 } else if (lastIndex() > -1
69 && previousEntry != null
70 && previousEntry.getTerm()!= appendEntries.getPrevLogTerm()) {
72 context.getLogger().debug(
73 "Cannot append entries because previous entry term {} is not equal to append entries prevLogTerm {}"
74 , previousEntry.getTerm()
75 , appendEntries.getPrevLogTerm());
77 noMatchingTerms = false;
80 if (noMatchingTerms) {
82 new AppendEntriesReply(context.getId(), currentTerm(), false,
83 lastIndex(), lastTerm()), actor()
88 if (appendEntries.getEntries() != null
89 && appendEntries.getEntries().size() > 0) {
90 context.getLogger().debug(
91 "Number of entries to be appended = " + appendEntries
95 // 3. If an existing entry conflicts with a new one (same index
96 // but different terms), delete the existing entry and all that
98 int addEntriesFrom = 0;
99 if (context.getReplicatedLog().size() > 0) {
101 i < appendEntries.getEntries()
102 .size(); i++, addEntriesFrom++) {
103 ReplicatedLogEntry matchEntry =
104 appendEntries.getEntries().get(i);
105 ReplicatedLogEntry newEntry = context.getReplicatedLog()
106 .get(matchEntry.getIndex());
108 if (newEntry == null) {
109 //newEntry not found in the log
113 if (newEntry != null && newEntry.getTerm() == matchEntry
117 if (newEntry != null && newEntry.getTerm() != matchEntry
119 context.getLogger().debug(
120 "Removing entries from log starting at "
121 + matchEntry.getIndex()
123 context.getReplicatedLog()
124 .removeFrom(matchEntry.getIndex());
130 context.getLogger().debug(
131 "After cleanup entries to be added from = " + (addEntriesFrom
135 // 4. Append any new entries not already in the log
136 for (int i = addEntriesFrom;
137 i < appendEntries.getEntries().size(); i++) {
138 context.getLogger().debug(
139 "Append entry to log " + appendEntries.getEntries().get(i).getData()
142 context.getReplicatedLog()
143 .appendAndPersist(appendEntries.getEntries().get(i));
146 context.getLogger().debug(
147 "Log size is now " + context.getReplicatedLog().size());
151 // 5. If leaderCommit > commitIndex, set commitIndex =
152 // min(leaderCommit, index of last new entry)
154 long prevCommitIndex = context.getCommitIndex();
156 context.setCommitIndex(Math.min(appendEntries.getLeaderCommit(),
157 context.getReplicatedLog().lastIndex()));
159 if (prevCommitIndex != context.getCommitIndex()) {
161 .debug("Commit index set to " + context.getCommitIndex());
164 // If commitIndex > lastApplied: increment lastApplied, apply
165 // log[lastApplied] to state machine (§5.3)
166 if (appendEntries.getLeaderCommit() > context.getLastApplied()) {
167 applyLogToStateMachine(appendEntries.getLeaderCommit());
170 sender.tell(new AppendEntriesReply(context.getId(), currentTerm(), true,
171 lastIndex(), lastTerm()), actor());
173 return suggestedState;
176 @Override protected RaftState handleAppendEntriesReply(ActorRef sender,
177 AppendEntriesReply appendEntriesReply, RaftState suggestedState) {
178 return suggestedState;
181 @Override protected RaftState handleRequestVoteReply(ActorRef sender,
182 RequestVoteReply requestVoteReply, RaftState suggestedState) {
183 return suggestedState;
186 @Override public RaftState state() {
187 return RaftState.Follower;
190 @Override public RaftState handleMessage(ActorRef sender, Object message) {
191 if (message instanceof ElectionTimeout) {
192 return RaftState.Candidate;
193 } else if (message instanceof InstallSnapshot) {
194 InstallSnapshot snapshot = (InstallSnapshot) message;
195 actor().tell(new ApplySnapshot(snapshot), actor());
198 scheduleElection(electionDuration());
200 return super.handleMessage(sender, message);
203 @Override public void close() throws Exception {