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 com.google.common.base.Preconditions;
14 import java.util.Random;
15 import java.util.concurrent.TimeUnit;
16 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
17 import org.opendaylight.controller.cluster.raft.RaftActorContext;
18 import org.opendaylight.controller.cluster.raft.RaftState;
19 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
20 import org.opendaylight.controller.cluster.raft.SerializationUtils;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
22 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
23 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
24 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
25 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
26 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
27 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
28 import org.slf4j.Logger;
29 import scala.concurrent.duration.FiniteDuration;
32 * Abstract class that represents the behavior of a RaftActor
36 * <li> If commitIndex > lastApplied: increment lastApplied, apply
37 * log[lastApplied] to state machine (§5.3)
38 * <li> If RPC request or response contains term T > currentTerm:
39 * set currentTerm = T, convert to follower (§5.1)
41 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
43 * Information about the RaftActor whose behavior this class represents
45 protected final RaftActorContext context;
50 protected final Logger LOG;
55 private Cancellable electionCancel = null;
57 private long replicatedToAllIndex = -1;
59 private final String logName;
61 private final RaftState state;
63 AbstractRaftActorBehavior(final RaftActorContext context, final RaftState state) {
64 this.context = Preconditions.checkNotNull(context);
65 this.state = Preconditions.checkNotNull(state);
66 this.LOG = context.getLogger();
68 logName = String.format("%s (%s)", context.getId(), state);
71 public static RaftActorBehavior createBehavior(final RaftActorContext context, final RaftState state) {
74 return new Candidate(context);
76 return new Follower(context);
78 return new IsolatedLeader(context);
80 return new Leader(context);
82 throw new IllegalArgumentException("Unhandled state " + state);
87 public final RaftState state() {
91 protected final String logName() {
96 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
97 this.replicatedToAllIndex = replicatedToAllIndex;
101 public long getReplicatedToAllIndex() {
102 return replicatedToAllIndex;
106 * Derived classes should not directly handle AppendEntries messages it
107 * should let the base class handle it first. Once the base class handles
108 * the AppendEntries message and does the common actions that are applicable
109 * in all RaftState's it will delegate the handling of the AppendEntries
110 * message to the derived class to do more state specific handling by calling
113 * @param sender The actor that sent this message
114 * @param appendEntries The AppendEntries message
115 * @return a new behavior if it was changed or the current behavior
117 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
118 AppendEntries appendEntries);
122 * appendEntries first processes the AppendEntries message and then
123 * delegates handling to a specific behavior
126 * @param appendEntries
127 * @return a new behavior if it was changed or the current behavior
129 protected RaftActorBehavior appendEntries(ActorRef sender,
130 AppendEntries appendEntries) {
132 // 1. Reply false if term < currentTerm (§5.1)
133 if (appendEntries.getTerm() < currentTerm()) {
134 if(LOG.isDebugEnabled()) {
135 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
136 logName(), appendEntries.getTerm(), currentTerm());
140 new AppendEntriesReply(context.getId(), currentTerm(), false,
141 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
147 return handleAppendEntries(sender, appendEntries);
151 * Derived classes should not directly handle AppendEntriesReply messages it
152 * should let the base class handle it first. Once the base class handles
153 * the AppendEntriesReply message and does the common actions that are
154 * applicable in all RaftState's it will delegate the handling of the
155 * AppendEntriesReply message to the derived class to do more state specific
156 * handling by calling this method
158 * @param sender The actor that sent this message
159 * @param appendEntriesReply The AppendEntriesReply message
160 * @return a new behavior if it was changed or the current behavior
162 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
163 AppendEntriesReply appendEntriesReply);
166 * requestVote handles the RequestVote message. This logic is common
171 * @return a new behavior if it was changed or the current behavior
173 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
175 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
177 boolean grantVote = canGrantVote(requestVote);
180 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
183 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
185 LOG.debug("{}: requestVote returning: {}", logName(), reply);
187 sender.tell(reply, actor());
192 protected boolean canGrantVote(RequestVote requestVote){
193 boolean grantVote = false;
195 // Reply false if term < currentTerm (§5.1)
196 if (requestVote.getTerm() < currentTerm()) {
199 // If votedFor is null or candidateId, and candidate’s log is at
200 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
201 } else if (votedFor() == null || votedFor()
202 .equals(requestVote.getCandidateId())) {
204 boolean candidateLatest = false;
207 // Raft determines which of two logs is more up-to-date
208 // by comparing the index and term of the last entries in the
209 // logs. If the logs have last entries with different terms, then
210 // the log with the later term is more up-to-date. If the logs
211 // end with the same term, then whichever log is longer is
213 if (requestVote.getLastLogTerm() > lastTerm()) {
214 candidateLatest = true;
215 } else if ((requestVote.getLastLogTerm() == lastTerm())
216 && requestVote.getLastLogIndex() >= lastIndex()) {
217 candidateLatest = true;
220 if (candidateLatest) {
228 * Derived classes should not directly handle RequestVoteReply messages it
229 * should let the base class handle it first. Once the base class handles
230 * the RequestVoteReply message and does the common actions that are
231 * applicable in all RaftState's it will delegate the handling of the
232 * RequestVoteReply message to the derived class to do more state specific
233 * handling by calling this method
235 * @param sender The actor that sent this message
236 * @param requestVoteReply The RequestVoteReply message
237 * @return a new behavior if it was changed or the current behavior
239 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
240 RequestVoteReply requestVoteReply);
244 * @return a random election duration
246 protected FiniteDuration electionDuration() {
247 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
248 return context.getConfigParams().getElectionTimeOutInterval().$plus(
249 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
253 * stop the scheduled election
255 protected void stopElection() {
256 if (electionCancel != null && !electionCancel.isCancelled()) {
257 electionCancel.cancel();
261 protected boolean canStartElection() {
262 return context.getRaftPolicy().automaticElectionsEnabled() && context.isVotingMember();
266 * schedule a new election
268 * @param interval the duration after which we should trigger a new election
270 protected void scheduleElection(FiniteDuration interval) {
273 // Schedule an election. When the scheduler triggers an ElectionTimeout message is sent to itself
274 electionCancel = context.getActorSystem().scheduler().scheduleOnce(interval, context.getActor(),
275 ElectionTimeout.INSTANCE, context.getActorSystem().dispatcher(), context.getActor());
279 * @return the current term
281 protected long currentTerm() {
282 return context.getTermInformation().getCurrentTerm();
286 * @return the candidate for whom we voted in the current term
288 protected String votedFor() {
289 return context.getTermInformation().getVotedFor();
293 * @return the actor associated with this behavior
295 protected ActorRef actor() {
296 return context.getActor();
301 * @return the term from the last entry in the log
303 protected long lastTerm() {
304 return context.getReplicatedLog().lastTerm();
308 * @return the index from the last entry in the log
310 protected long lastIndex() {
311 return context.getReplicatedLog().lastIndex();
316 * @return the client request tracker for the specified logIndex
318 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
324 * @return log index from the previous to last entry in the log
326 protected long prevLogIndex(long index){
327 ReplicatedLogEntry prevEntry =
328 context.getReplicatedLog().get(index - 1);
329 if (prevEntry != null) {
330 return prevEntry.getIndex();
336 * @return log term from the previous to last entry in the log
338 protected long prevLogTerm(long index){
339 ReplicatedLogEntry prevEntry =
340 context.getReplicatedLog().get(index - 1);
341 if (prevEntry != null) {
342 return prevEntry.getTerm();
348 * Apply the provided index to the state machine
350 * @param index a log index that is known to be committed
352 protected void applyLogToStateMachine(final long index) {
353 long newLastApplied = context.getLastApplied();
354 // Now maybe we apply to the state machine
355 for (long i = context.getLastApplied() + 1; i < index + 1; i++) {
357 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(i);
358 if (replicatedLogEntry != null) {
359 // Send a local message to the local RaftActor (it's derived class to be
360 // specific to apply the log to it's index)
362 final ApplyState msg;
363 final ClientRequestTracker tracker = removeClientRequestTracker(i);
364 if (tracker != null) {
365 msg = new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), replicatedLogEntry);
367 msg = new ApplyState(null, null, replicatedLogEntry);
370 actor().tell(msg, actor());
373 //if one index is not present in the log, no point in looping
374 // around as the rest wont be present either
375 LOG.warn("{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
376 logName(), i, i, index);
380 if(LOG.isDebugEnabled()) {
381 LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
383 context.setLastApplied(newLastApplied);
385 // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
386 // will be used during recovery
387 //in case if the above code throws an error and this message is not sent, it would be fine
388 // as the append entries received later would initiate add this message to the journal
389 actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
392 protected Object fromSerializableMessage(Object serializable){
393 return SerializationUtils.fromSerializable(serializable);
397 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
398 if (message instanceof AppendEntries) {
399 return appendEntries(sender, (AppendEntries) message);
400 } else if (message instanceof AppendEntriesReply) {
401 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
402 } else if (message instanceof RequestVote) {
403 return requestVote(sender, (RequestVote) message);
404 } else if (message instanceof RequestVoteReply) {
405 return handleRequestVoteReply(sender, (RequestVoteReply) message);
412 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
413 return internalSwitchBehavior(behavior);
416 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
417 if(context.getRaftPolicy().automaticElectionsEnabled()){
418 return internalSwitchBehavior(createBehavior(context, newState));
423 private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
424 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
427 } catch (Exception e) {
428 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
434 protected int getMajorityVoteCount(int numPeers) {
435 // Votes are required from a majority of the peers including self.
436 // The numMajority field therefore stores a calculated value
437 // of the number of votes required for this candidate to win an
438 // election based on it's known peers.
439 // If a peer was added during normal operation and raft replicas
440 // came to know about them then the new peer would also need to be
441 // taken into consideration when calculating this value.
442 // Here are some examples for what the numMajority would be for n
444 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
445 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
446 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
451 numMajority = (numPeers + self) / 2 + 1;
459 * Performs a snapshot with no capture on the replicated log.
460 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
462 * @param snapshotCapturedIndex
464 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
465 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex);
467 if(actualIndex != -1){
468 setReplicatedToAllIndex(actualIndex);
472 protected String getId(){
473 return context.getId();