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;
60 protected String leaderId = null;
62 private short leaderPayloadVersion = -1;
64 private long replicatedToAllIndex = -1;
66 private final String logName;
68 private final RaftState state;
70 AbstractRaftActorBehavior(final RaftActorContext context, final RaftState state) {
71 this.context = Preconditions.checkNotNull(context);
72 this.state = Preconditions.checkNotNull(state);
73 this.LOG = context.getLogger();
75 logName = String.format("%s (%s)", context.getId(), state);
78 public static RaftActorBehavior createBehavior(final RaftActorContext context, final RaftState state) {
81 return new Candidate(context);
83 return new Follower(context);
85 return new IsolatedLeader(context);
87 return new Leader(context);
89 throw new IllegalArgumentException("Unhandled state " + state);
94 public RaftState state() {
98 public String logName() {
103 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
104 this.replicatedToAllIndex = replicatedToAllIndex;
108 public long getReplicatedToAllIndex() {
109 return replicatedToAllIndex;
113 * Derived classes should not directly handle AppendEntries messages it
114 * should let the base class handle it first. Once the base class handles
115 * the AppendEntries message and does the common actions that are applicable
116 * in all RaftState's it will delegate the handling of the AppendEntries
117 * message to the derived class to do more state specific handling by calling
120 * @param sender The actor that sent this message
121 * @param appendEntries The AppendEntries message
122 * @return a new behavior if it was changed or the current behavior
124 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
125 AppendEntries appendEntries);
129 * appendEntries first processes the AppendEntries message and then
130 * delegates handling to a specific behavior
133 * @param appendEntries
134 * @return a new behavior if it was changed or the current behavior
136 protected RaftActorBehavior appendEntries(ActorRef sender,
137 AppendEntries appendEntries) {
139 // 1. Reply false if term < currentTerm (§5.1)
140 if (appendEntries.getTerm() < currentTerm()) {
141 if(LOG.isDebugEnabled()) {
142 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
143 logName(), appendEntries.getTerm(), currentTerm());
147 new AppendEntriesReply(context.getId(), currentTerm(), false,
148 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
154 return handleAppendEntries(sender, appendEntries);
158 * Derived classes should not directly handle AppendEntriesReply messages it
159 * should let the base class handle it first. Once the base class handles
160 * the AppendEntriesReply message and does the common actions that are
161 * applicable in all RaftState's it will delegate the handling of the
162 * AppendEntriesReply message to the derived class to do more state specific
163 * handling by calling this method
165 * @param sender The actor that sent this message
166 * @param appendEntriesReply The AppendEntriesReply message
167 * @return a new behavior if it was changed or the current behavior
169 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
170 AppendEntriesReply appendEntriesReply);
173 * requestVote handles the RequestVote message. This logic is common
178 * @return a new behavior if it was changed or the current behavior
180 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
182 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
184 boolean grantVote = canGrantVote(requestVote);
187 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
190 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
192 LOG.debug("{}: requestVote returning: {}", logName(), reply);
194 sender.tell(reply, actor());
199 protected boolean canGrantVote(RequestVote requestVote){
200 boolean grantVote = false;
202 // Reply false if term < currentTerm (§5.1)
203 if (requestVote.getTerm() < currentTerm()) {
206 // If votedFor is null or candidateId, and candidate’s log is at
207 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
208 } else if (votedFor() == null || votedFor()
209 .equals(requestVote.getCandidateId())) {
211 boolean candidateLatest = false;
214 // Raft determines which of two logs is more up-to-date
215 // by comparing the index and term of the last entries in the
216 // logs. If the logs have last entries with different terms, then
217 // the log with the later term is more up-to-date. If the logs
218 // end with the same term, then whichever log is longer is
220 if (requestVote.getLastLogTerm() > lastTerm()) {
221 candidateLatest = true;
222 } else if ((requestVote.getLastLogTerm() == lastTerm())
223 && requestVote.getLastLogIndex() >= lastIndex()) {
224 candidateLatest = true;
227 if (candidateLatest) {
235 * Derived classes should not directly handle RequestVoteReply messages it
236 * should let the base class handle it first. Once the base class handles
237 * the RequestVoteReply message and does the common actions that are
238 * applicable in all RaftState's it will delegate the handling of the
239 * RequestVoteReply message to the derived class to do more state specific
240 * handling by calling this method
242 * @param sender The actor that sent this message
243 * @param requestVoteReply The RequestVoteReply message
244 * @return a new behavior if it was changed or the current behavior
246 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
247 RequestVoteReply requestVoteReply);
251 * @return a random election duration
253 protected FiniteDuration electionDuration() {
254 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
255 return context.getConfigParams().getElectionTimeOutInterval().$plus(
256 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
260 * stop the scheduled election
262 protected void stopElection() {
263 if (electionCancel != null && !electionCancel.isCancelled()) {
264 electionCancel.cancel();
268 protected boolean canStartElection() {
269 return context.getRaftPolicy().automaticElectionsEnabled() && context.isVotingMember();
273 * schedule a new election
275 * @param interval the duration after which we should trigger a new election
277 protected void scheduleElection(FiniteDuration interval) {
280 if(canStartElection()) {
281 // Schedule an election. When the scheduler triggers an ElectionTimeout message is sent to itself
282 electionCancel = context.getActorSystem().scheduler().scheduleOnce(interval, context.getActor(),
283 ElectionTimeout.INSTANCE, context.getActorSystem().dispatcher(), context.getActor());
288 * @return the current term
290 protected long currentTerm() {
291 return context.getTermInformation().getCurrentTerm();
295 * @return the candidate for whom we voted in the current term
297 protected String votedFor() {
298 return context.getTermInformation().getVotedFor();
302 * @return the actor associated with this behavior
304 protected ActorRef actor() {
305 return context.getActor();
310 * @return the term from the last entry in the log
312 protected long lastTerm() {
313 return context.getReplicatedLog().lastTerm();
317 * @return the index from the last entry in the log
319 protected long lastIndex() {
320 return context.getReplicatedLog().lastIndex();
325 * @return the client request tracker for the specified logIndex
327 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
333 * @return the client request tracker for the specified logIndex
335 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
342 * @return log index from the previous to last entry in the log
344 protected long prevLogIndex(long index){
345 ReplicatedLogEntry prevEntry =
346 context.getReplicatedLog().get(index - 1);
347 if (prevEntry != null) {
348 return prevEntry.getIndex();
354 * @return log term from the previous to last entry in the log
356 protected long prevLogTerm(long index){
357 ReplicatedLogEntry prevEntry =
358 context.getReplicatedLog().get(index - 1);
359 if (prevEntry != null) {
360 return prevEntry.getTerm();
366 * Apply the provided index to the state machine
368 * @param index a log index that is known to be committed
370 protected void applyLogToStateMachine(final long index) {
371 long newLastApplied = context.getLastApplied();
372 // Now maybe we apply to the state machine
373 for (long i = context.getLastApplied() + 1;
374 i < index + 1; i++) {
375 ActorRef clientActor = null;
376 String identifier = null;
377 ClientRequestTracker tracker = removeClientRequestTracker(i);
379 if (tracker != null) {
380 clientActor = tracker.getClientActor();
381 identifier = tracker.getIdentifier();
383 ReplicatedLogEntry replicatedLogEntry =
384 context.getReplicatedLog().get(i);
386 if (replicatedLogEntry != null) {
387 // Send a local message to the local RaftActor (it's derived class to be
388 // specific to apply the log to it's index)
389 actor().tell(new ApplyState(clientActor, identifier,
390 replicatedLogEntry), actor());
393 //if one index is not present in the log, no point in looping
394 // around as the rest wont be present either
396 "{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
397 logName(), i, i, index);
401 if(LOG.isDebugEnabled()) {
402 LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
404 context.setLastApplied(newLastApplied);
406 // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
407 // will be used during recovery
408 //in case if the above code throws an error and this message is not sent, it would be fine
409 // as the append entries received later would initiate add this message to the journal
410 actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
413 protected Object fromSerializableMessage(Object serializable){
414 return SerializationUtils.fromSerializable(serializable);
418 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
419 if (message instanceof AppendEntries) {
420 return appendEntries(sender, (AppendEntries) message);
421 } else if (message instanceof AppendEntriesReply) {
422 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
423 } else if (message instanceof RequestVote) {
424 return requestVote(sender, (RequestVote) message);
425 } else if (message instanceof RequestVoteReply) {
426 return handleRequestVoteReply(sender, (RequestVoteReply) message);
431 @Override public String getLeaderId() {
436 public short getLeaderPayloadVersion() {
437 return leaderPayloadVersion;
440 public void setLeaderPayloadVersion(short leaderPayloadVersion) {
441 this.leaderPayloadVersion = leaderPayloadVersion;
445 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
446 return internalSwitchBehavior(behavior);
449 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
450 if(context.getRaftPolicy().automaticElectionsEnabled()){
451 return internalSwitchBehavior(createBehavior(context, newState));
456 private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
457 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
460 } catch (Exception e) {
461 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
467 protected int getMajorityVoteCount(int numPeers) {
468 // Votes are required from a majority of the peers including self.
469 // The numMajority field therefore stores a calculated value
470 // of the number of votes required for this candidate to win an
471 // election based on it's known peers.
472 // If a peer was added during normal operation and raft replicas
473 // came to know about them then the new peer would also need to be
474 // taken into consideration when calculating this value.
475 // Here are some examples for what the numMajority would be for n
477 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
478 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
479 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
484 numMajority = (numPeers + self) / 2 + 1;
492 * Performs a snapshot with no capture on the replicated log.
493 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
495 * @param snapshotCapturedIndex
497 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
498 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex, this);
500 if(actualIndex != -1){
501 setReplicatedToAllIndex(actualIndex);
505 protected String getId(){
506 return context.getId();