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.internal.messages.ApplyState;
18 import org.opendaylight.controller.cluster.raft.internal.messages.ElectionTimeout;
19 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
20 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
21 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
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;
47 * The maximum election time variance
49 private static final int ELECTION_TIME_MAX_VARIANCE = 100;
52 * The interval at which a heart beat message will be sent to the remote
55 * Since this is set to 100 milliseconds the Election timeout should be
56 * at least 200 milliseconds
58 protected static final FiniteDuration HEART_BEAT_INTERVAL =
59 new FiniteDuration(100, TimeUnit.MILLISECONDS);
62 * The interval in which a new election would get triggered if no leader is found
64 private static final long ELECTION_TIME_INTERVAL =
65 HEART_BEAT_INTERVAL.toMillis() * 2;
70 private Cancellable electionCancel = null;
75 protected String leaderId = null;
78 protected AbstractRaftActorBehavior(RaftActorContext context) {
79 this.context = context;
83 * Derived classes should not directly handle AppendEntries messages it
84 * should let the base class handle it first. Once the base class handles
85 * the AppendEntries message and does the common actions that are applicable
86 * in all RaftState's it will delegate the handling of the AppendEntries
87 * message to the derived class to do more state specific handling by calling
90 * @param sender The actor that sent this message
91 * @param appendEntries The AppendEntries message
92 * @param suggestedState The state that the RaftActor should be in based
93 * on the base class's processing of the AppendEntries
97 protected abstract RaftState handleAppendEntries(ActorRef sender,
98 AppendEntries appendEntries, RaftState suggestedState);
102 * appendEntries first processes the AppendEntries message and then
103 * delegates handling to a specific behavior
106 * @param appendEntries
110 protected RaftState appendEntries(ActorRef sender,
111 AppendEntries appendEntries, RaftState raftState) {
113 if (raftState != state()) {
114 context.getLogger().debug("Suggested state is " + raftState
115 + " current behavior state is " + state());
118 // 1. Reply false if term < currentTerm (§5.1)
119 if (appendEntries.getTerm() < currentTerm()) {
120 context.getLogger().debug(
121 "Cannot append entries because sender term " + appendEntries
122 .getTerm() + " is less than " + currentTerm());
124 new AppendEntriesReply(context.getId(), currentTerm(), false,
125 lastIndex(), lastTerm()), actor()
131 return handleAppendEntries(sender, appendEntries, raftState);
135 * Derived classes should not directly handle AppendEntriesReply messages it
136 * should let the base class handle it first. Once the base class handles
137 * the AppendEntriesReply message and does the common actions that are
138 * applicable in all RaftState's it will delegate the handling of the
139 * AppendEntriesReply message to the derived class to do more state specific
140 * handling by calling this method
142 * @param sender The actor that sent this message
143 * @param appendEntriesReply The AppendEntriesReply message
144 * @param suggestedState The state that the RaftActor should be in based
145 * on the base class's processing of the
146 * AppendEntriesReply message
149 protected abstract RaftState handleAppendEntriesReply(ActorRef sender,
150 AppendEntriesReply appendEntriesReply, RaftState suggestedState);
153 * requestVote handles the RequestVote message. This logic is common
158 * @param suggestedState
161 protected RaftState requestVote(ActorRef sender,
162 RequestVote requestVote, RaftState suggestedState) {
164 boolean grantVote = false;
166 // Reply false if term < currentTerm (§5.1)
167 if (requestVote.getTerm() < currentTerm()) {
170 // If votedFor is null or candidateId, and candidate’s log is at
171 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
172 } else if (votedFor() == null || votedFor()
173 .equals(requestVote.getCandidateId())) {
175 boolean candidateLatest = false;
178 // Raft determines which of two logs is more up-to-date
179 // by comparing the index and term of the last entries in the
180 // logs. If the logs have last entries with different terms, then
181 // the log with the later term is more up-to-date. If the logs
182 // end with the same term, then whichever log is longer is
184 if (requestVote.getLastLogTerm() > lastTerm()) {
185 candidateLatest = true;
186 } else if ((requestVote.getLastLogTerm() == lastTerm())
187 && requestVote.getLastLogIndex() >= lastIndex()) {
188 candidateLatest = true;
191 if (candidateLatest) {
193 context.getTermInformation().update(requestVote.getTerm(),
194 requestVote.getCandidateId());
198 sender.tell(new RequestVoteReply(currentTerm(), grantVote), actor());
200 return suggestedState;
204 * Derived classes should not directly handle RequestVoteReply messages it
205 * should let the base class handle it first. Once the base class handles
206 * the RequestVoteReply message and does the common actions that are
207 * applicable in all RaftState's it will delegate the handling of the
208 * RequestVoteReply message to the derived class to do more state specific
209 * handling by calling this method
211 * @param sender The actor that sent this message
212 * @param requestVoteReply The RequestVoteReply message
213 * @param suggestedState The state that the RaftActor should be in based
214 * on the base class's processing of the RequestVote
218 protected abstract RaftState handleRequestVoteReply(ActorRef sender,
219 RequestVoteReply requestVoteReply, RaftState suggestedState);
222 * Creates a random election duration
226 protected FiniteDuration electionDuration() {
227 long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
228 return new FiniteDuration(ELECTION_TIME_INTERVAL + variance,
229 TimeUnit.MILLISECONDS);
233 * stop the scheduled election
235 protected void stopElection() {
236 if (electionCancel != null && !electionCancel.isCancelled()) {
237 electionCancel.cancel();
242 * schedule a new election
246 protected void scheduleElection(FiniteDuration interval) {
249 // Schedule an election. When the scheduler triggers an ElectionTimeout
250 // message is sent to itself
252 context.getActorSystem().scheduler().scheduleOnce(interval,
253 context.getActor(), new ElectionTimeout(),
254 context.getActorSystem().dispatcher(), context.getActor());
258 * Get the current term
261 protected long currentTerm() {
262 return context.getTermInformation().getCurrentTerm();
266 * Get the candidate for whom we voted in the current term
269 protected String votedFor() {
270 return context.getTermInformation().getVotedFor();
274 * Get the actor associated with this behavior
277 protected ActorRef actor() {
278 return context.getActor();
282 * Get the term from the last entry in the log
286 protected long lastTerm() {
287 return context.getReplicatedLog().lastTerm();
291 * Get the index from the last entry in the log
295 protected long lastIndex() {
296 return context.getReplicatedLog().lastIndex();
300 * Find the client request tracker for a specific logIndex
305 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
310 * Find the log index from the previous to last entry in the log
314 protected long prevLogIndex(long index){
315 ReplicatedLogEntry prevEntry =
316 context.getReplicatedLog().get(index - 1);
317 if (prevEntry != null) {
318 return prevEntry.getIndex();
324 * Find the log term from the previous to last entry in the log
327 protected long prevLogTerm(long index){
328 ReplicatedLogEntry prevEntry =
329 context.getReplicatedLog().get(index - 1);
330 if (prevEntry != null) {
331 return prevEntry.getTerm();
337 * Apply the provided index to the state machine
339 * @param index a log index that is known to be committed
341 protected void applyLogToStateMachine(long index) {
342 // Now maybe we apply to the state machine
343 for (long i = context.getLastApplied() + 1;
344 i < index + 1; i++) {
345 ActorRef clientActor = null;
346 String identifier = null;
347 ClientRequestTracker tracker = findClientRequestTracker(i);
349 if (tracker != null) {
350 clientActor = tracker.getClientActor();
351 identifier = tracker.getIdentifier();
353 ReplicatedLogEntry replicatedLogEntry =
354 context.getReplicatedLog().get(i);
356 if (replicatedLogEntry != null) {
357 actor().tell(new ApplyState(clientActor, identifier,
358 replicatedLogEntry), actor());
360 context.getLogger().error(
361 "Missing index " + i + " from log. Cannot apply state.");
364 // Send a local message to the local RaftActor (it's derived class to be
365 // specific to apply the log to it's index)
366 context.setLastApplied(index);
370 public RaftState handleMessage(ActorRef sender, Object message) {
371 RaftState raftState = state();
372 if (message instanceof RaftRPC) {
373 raftState = applyTerm((RaftRPC) message);
375 if (message instanceof AppendEntries) {
376 raftState = appendEntries(sender, (AppendEntries) message,
378 } else if (message instanceof AppendEntriesReply) {
380 handleAppendEntriesReply(sender, (AppendEntriesReply) message,
382 } else if (message instanceof RequestVote) {
384 requestVote(sender, (RequestVote) message, raftState);
385 } else if (message instanceof RequestVoteReply) {
387 handleRequestVoteReply(sender, (RequestVoteReply) message,
393 @Override public String getLeaderId() {
397 private RaftState applyTerm(RaftRPC rpc) {
398 // If RPC request or response contains term T > currentTerm:
399 // set currentTerm = T, convert to follower (§5.1)
400 // This applies to all RPC messages and responses
401 if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
402 context.getTermInformation().update(rpc.getTerm(), null);
403 return RaftState.Follower;