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 akka.actor.Cancellable;
13 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
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.SerializationUtils;
18 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
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.RequestVote;
23 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
24 import scala.concurrent.duration.FiniteDuration;
26 import java.util.Random;
27 import java.util.concurrent.TimeUnit;
30 * Abstract class that represents the behavior of a RaftActor
34 * <li> If commitIndex > lastApplied: increment lastApplied, apply
35 * log[lastApplied] to state machine (§5.3)
36 * <li> If RPC request or response contains term T > currentTerm:
37 * set currentTerm = T, convert to follower (§5.1)
39 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
42 * Information about the RaftActor whose behavior this class represents
44 protected final RaftActorContext context;
49 private Cancellable electionCancel = null;
54 protected String leaderId = null;
57 protected AbstractRaftActorBehavior(RaftActorContext context) {
58 this.context = context;
62 * Derived classes should not directly handle AppendEntries messages it
63 * should let the base class handle it first. Once the base class handles
64 * the AppendEntries message and does the common actions that are applicable
65 * in all RaftState's it will delegate the handling of the AppendEntries
66 * message to the derived class to do more state specific handling by calling
69 * @param sender The actor that sent this message
70 * @param appendEntries The AppendEntries message
73 protected abstract RaftState handleAppendEntries(ActorRef sender,
74 AppendEntries appendEntries);
78 * appendEntries first processes the AppendEntries message and then
79 * delegates handling to a specific behavior
82 * @param appendEntries
85 protected RaftState appendEntries(ActorRef sender,
86 AppendEntries appendEntries) {
88 // 1. Reply false if term < currentTerm (§5.1)
89 if (appendEntries.getTerm() < currentTerm()) {
90 context.getLogger().debug(
91 "Cannot append entries because sender term " + appendEntries
92 .getTerm() + " is less than " + currentTerm());
94 new AppendEntriesReply(context.getId(), currentTerm(), false,
95 lastIndex(), lastTerm()), actor()
101 return handleAppendEntries(sender, appendEntries);
105 * Derived classes should not directly handle AppendEntriesReply messages it
106 * should let the base class handle it first. Once the base class handles
107 * the AppendEntriesReply message and does the common actions that are
108 * applicable in all RaftState's it will delegate the handling of the
109 * AppendEntriesReply message to the derived class to do more state specific
110 * handling by calling this method
112 * @param sender The actor that sent this message
113 * @param appendEntriesReply The AppendEntriesReply message
116 protected abstract RaftState handleAppendEntriesReply(ActorRef sender,
117 AppendEntriesReply appendEntriesReply);
120 * requestVote handles the RequestVote message. This logic is common
127 protected RaftState requestVote(ActorRef sender,
128 RequestVote requestVote) {
130 boolean grantVote = false;
132 // Reply false if term < currentTerm (§5.1)
133 if (requestVote.getTerm() < currentTerm()) {
136 // If votedFor is null or candidateId, and candidate’s log is at
137 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
138 } else if (votedFor() == null || votedFor()
139 .equals(requestVote.getCandidateId())) {
141 boolean candidateLatest = false;
144 // Raft determines which of two logs is more up-to-date
145 // by comparing the index and term of the last entries in the
146 // logs. If the logs have last entries with different terms, then
147 // the log with the later term is more up-to-date. If the logs
148 // end with the same term, then whichever log is longer is
150 if (requestVote.getLastLogTerm() > lastTerm()) {
151 candidateLatest = true;
152 } else if ((requestVote.getLastLogTerm() == lastTerm())
153 && requestVote.getLastLogIndex() >= lastIndex()) {
154 candidateLatest = true;
157 if (candidateLatest) {
159 context.getTermInformation().updateAndPersist(requestVote.getTerm(),
160 requestVote.getCandidateId());
164 sender.tell(new RequestVoteReply(currentTerm(), grantVote), actor());
170 * Derived classes should not directly handle RequestVoteReply messages it
171 * should let the base class handle it first. Once the base class handles
172 * the RequestVoteReply message and does the common actions that are
173 * applicable in all RaftState's it will delegate the handling of the
174 * RequestVoteReply message to the derived class to do more state specific
175 * handling by calling this method
177 * @param sender The actor that sent this message
178 * @param requestVoteReply The RequestVoteReply message
181 protected abstract RaftState handleRequestVoteReply(ActorRef sender,
182 RequestVoteReply requestVoteReply);
185 * Creates a random election duration
189 protected FiniteDuration electionDuration() {
190 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
191 return context.getConfigParams().getElectionTimeOutInterval().$plus(
192 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
196 * stop the scheduled election
198 protected void stopElection() {
199 if (electionCancel != null && !electionCancel.isCancelled()) {
200 electionCancel.cancel();
205 * schedule a new election
209 protected void scheduleElection(FiniteDuration interval) {
212 // Schedule an election. When the scheduler triggers an ElectionTimeout
213 // message is sent to itself
215 context.getActorSystem().scheduler().scheduleOnce(interval,
216 context.getActor(), new ElectionTimeout(),
217 context.getActorSystem().dispatcher(), context.getActor());
221 * Get the current term
224 protected long currentTerm() {
225 return context.getTermInformation().getCurrentTerm();
229 * Get the candidate for whom we voted in the current term
232 protected String votedFor() {
233 return context.getTermInformation().getVotedFor();
237 * Get the actor associated with this behavior
240 protected ActorRef actor() {
241 return context.getActor();
245 * Get the term from the last entry in the log
249 protected long lastTerm() {
250 return context.getReplicatedLog().lastTerm();
254 * Get the index from the last entry in the log
258 protected long lastIndex() {
259 return context.getReplicatedLog().lastIndex();
263 * Find the client request tracker for a specific logIndex
268 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
273 * Find the log index from the previous to last entry in the log
277 protected long prevLogIndex(long index){
278 ReplicatedLogEntry prevEntry =
279 context.getReplicatedLog().get(index - 1);
280 if (prevEntry != null) {
281 return prevEntry.getIndex();
287 * Find the log term from the previous to last entry in the log
290 protected long prevLogTerm(long index){
291 ReplicatedLogEntry prevEntry =
292 context.getReplicatedLog().get(index - 1);
293 if (prevEntry != null) {
294 return prevEntry.getTerm();
300 * Apply the provided index to the state machine
302 * @param index a log index that is known to be committed
304 protected void applyLogToStateMachine(long index) {
305 // Now maybe we apply to the state machine
306 for (long i = context.getLastApplied() + 1;
307 i < index + 1; i++) {
308 ActorRef clientActor = null;
309 String identifier = null;
310 ClientRequestTracker tracker = findClientRequestTracker(i);
312 if (tracker != null) {
313 clientActor = tracker.getClientActor();
314 identifier = tracker.getIdentifier();
316 ReplicatedLogEntry replicatedLogEntry =
317 context.getReplicatedLog().get(i);
319 if (replicatedLogEntry != null) {
320 actor().tell(new ApplyState(clientActor, identifier,
321 replicatedLogEntry), actor());
323 context.getLogger().error(
324 "Missing index " + i + " from log. Cannot apply state.");
327 // Send a local message to the local RaftActor (it's derived class to be
328 // specific to apply the log to it's index)
329 context.setLastApplied(index);
332 protected Object fromSerializableMessage(Object serializable){
333 return SerializationUtils.fromSerializable(serializable);
337 public RaftState handleMessage(ActorRef sender, Object message) {
338 if (message instanceof AppendEntries) {
339 return appendEntries(sender, (AppendEntries) message);
340 } else if (message instanceof AppendEntriesReply) {
341 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
342 } else if (message instanceof RequestVote) {
343 return requestVote(sender, (RequestVote) message);
344 } else if (message instanceof RequestVoteReply) {
345 return handleRequestVoteReply(sender, (RequestVoteReply) message);
350 @Override public String getLeaderId() {