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;
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
94 protected abstract RaftState handleAppendEntries(ActorRef sender,
95 AppendEntries appendEntries);
99 * appendEntries first processes the AppendEntries message and then
100 * delegates handling to a specific behavior
103 * @param appendEntries
106 protected RaftState appendEntries(ActorRef sender,
107 AppendEntries appendEntries) {
109 // 1. Reply false if term < currentTerm (§5.1)
110 if (appendEntries.getTerm() < currentTerm()) {
111 context.getLogger().debug(
112 "Cannot append entries because sender term " + appendEntries
113 .getTerm() + " is less than " + currentTerm());
115 new AppendEntriesReply(context.getId(), currentTerm(), false,
116 lastIndex(), lastTerm()), actor()
122 return handleAppendEntries(sender, appendEntries);
126 * Derived classes should not directly handle AppendEntriesReply messages it
127 * should let the base class handle it first. Once the base class handles
128 * the AppendEntriesReply message and does the common actions that are
129 * applicable in all RaftState's it will delegate the handling of the
130 * AppendEntriesReply message to the derived class to do more state specific
131 * handling by calling this method
133 * @param sender The actor that sent this message
134 * @param appendEntriesReply The AppendEntriesReply message
137 protected abstract RaftState handleAppendEntriesReply(ActorRef sender,
138 AppendEntriesReply appendEntriesReply);
141 * requestVote handles the RequestVote message. This logic is common
148 protected RaftState requestVote(ActorRef sender,
149 RequestVote requestVote) {
151 boolean grantVote = false;
153 // Reply false if term < currentTerm (§5.1)
154 if (requestVote.getTerm() < currentTerm()) {
157 // If votedFor is null or candidateId, and candidate’s log is at
158 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
159 } else if (votedFor() == null || votedFor()
160 .equals(requestVote.getCandidateId())) {
162 boolean candidateLatest = false;
165 // Raft determines which of two logs is more up-to-date
166 // by comparing the index and term of the last entries in the
167 // logs. If the logs have last entries with different terms, then
168 // the log with the later term is more up-to-date. If the logs
169 // end with the same term, then whichever log is longer is
171 if (requestVote.getLastLogTerm() > lastTerm()) {
172 candidateLatest = true;
173 } else if ((requestVote.getLastLogTerm() == lastTerm())
174 && requestVote.getLastLogIndex() >= lastIndex()) {
175 candidateLatest = true;
178 if (candidateLatest) {
180 context.getTermInformation().updateAndPersist(requestVote.getTerm(),
181 requestVote.getCandidateId());
185 sender.tell(new RequestVoteReply(currentTerm(), grantVote), actor());
191 * Derived classes should not directly handle RequestVoteReply messages it
192 * should let the base class handle it first. Once the base class handles
193 * the RequestVoteReply message and does the common actions that are
194 * applicable in all RaftState's it will delegate the handling of the
195 * RequestVoteReply message to the derived class to do more state specific
196 * handling by calling this method
198 * @param sender The actor that sent this message
199 * @param requestVoteReply The RequestVoteReply message
202 protected abstract RaftState handleRequestVoteReply(ActorRef sender,
203 RequestVoteReply requestVoteReply);
206 * Creates a random election duration
210 protected FiniteDuration electionDuration() {
211 long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
212 return new FiniteDuration(ELECTION_TIME_INTERVAL + variance,
213 TimeUnit.MILLISECONDS);
217 * stop the scheduled election
219 protected void stopElection() {
220 if (electionCancel != null && !electionCancel.isCancelled()) {
221 electionCancel.cancel();
226 * schedule a new election
230 protected void scheduleElection(FiniteDuration interval) {
233 // Schedule an election. When the scheduler triggers an ElectionTimeout
234 // message is sent to itself
236 context.getActorSystem().scheduler().scheduleOnce(interval,
237 context.getActor(), new ElectionTimeout(),
238 context.getActorSystem().dispatcher(), context.getActor());
242 * Get the current term
245 protected long currentTerm() {
246 return context.getTermInformation().getCurrentTerm();
250 * Get the candidate for whom we voted in the current term
253 protected String votedFor() {
254 return context.getTermInformation().getVotedFor();
258 * Get the actor associated with this behavior
261 protected ActorRef actor() {
262 return context.getActor();
266 * Get the term from the last entry in the log
270 protected long lastTerm() {
271 return context.getReplicatedLog().lastTerm();
275 * Get the index from the last entry in the log
279 protected long lastIndex() {
280 return context.getReplicatedLog().lastIndex();
284 * Find the client request tracker for a specific logIndex
289 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
294 * Find the log index from the previous to last entry in the log
298 protected long prevLogIndex(long index){
299 ReplicatedLogEntry prevEntry =
300 context.getReplicatedLog().get(index - 1);
301 if (prevEntry != null) {
302 return prevEntry.getIndex();
308 * Find the log term from the previous to last entry in the log
311 protected long prevLogTerm(long index){
312 ReplicatedLogEntry prevEntry =
313 context.getReplicatedLog().get(index - 1);
314 if (prevEntry != null) {
315 return prevEntry.getTerm();
321 * Apply the provided index to the state machine
323 * @param index a log index that is known to be committed
325 protected void applyLogToStateMachine(long index) {
326 // Now maybe we apply to the state machine
327 for (long i = context.getLastApplied() + 1;
328 i < index + 1; i++) {
329 ActorRef clientActor = null;
330 String identifier = null;
331 ClientRequestTracker tracker = findClientRequestTracker(i);
333 if (tracker != null) {
334 clientActor = tracker.getClientActor();
335 identifier = tracker.getIdentifier();
337 ReplicatedLogEntry replicatedLogEntry =
338 context.getReplicatedLog().get(i);
340 if (replicatedLogEntry != null) {
341 actor().tell(new ApplyState(clientActor, identifier,
342 replicatedLogEntry), actor());
344 context.getLogger().error(
345 "Missing index " + i + " from log. Cannot apply state.");
348 // Send a local message to the local RaftActor (it's derived class to be
349 // specific to apply the log to it's index)
350 context.setLastApplied(index);
353 protected Object fromSerializableMessage(Object serializable){
354 return SerializationUtils.fromSerializable(serializable);
358 public RaftState handleMessage(ActorRef sender, Object message) {
359 if (message instanceof AppendEntries) {
360 return appendEntries(sender, (AppendEntries) message);
361 } else if (message instanceof AppendEntriesReply) {
362 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
363 } else if (message instanceof RequestVote) {
364 return requestVote(sender, (RequestVote) message);
365 } else if (message instanceof RequestVoteReply) {
366 return handleRequestVoteReply(sender, (RequestVoteReply) message);
371 @Override public String getLeaderId() {