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.base.messages.ApplyState;
21 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
22 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
24 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
25 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
26 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
27 import org.slf4j.Logger;
28 import scala.concurrent.duration.FiniteDuration;
31 * Abstract class that represents the behavior of a RaftActor
35 * <li> If commitIndex > lastApplied: increment lastApplied, apply
36 * log[lastApplied] to state machine (§5.3)
37 * <li> If RPC request or response contains term T > currentTerm:
38 * set currentTerm = T, convert to follower (§5.1)
40 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
42 * Information about the RaftActor whose behavior this class represents
44 protected final RaftActorContext context;
49 protected final Logger LOG;
54 private Cancellable electionCancel = null;
56 private long replicatedToAllIndex = -1;
58 private final String logName;
60 private final RaftState state;
62 AbstractRaftActorBehavior(final RaftActorContext context, final RaftState state) {
63 this.context = Preconditions.checkNotNull(context);
64 this.state = Preconditions.checkNotNull(state);
65 this.LOG = context.getLogger();
67 logName = String.format("%s (%s)", context.getId(), state);
70 public static RaftActorBehavior createBehavior(final RaftActorContext context, final RaftState state) {
73 return new Candidate(context);
75 return new Follower(context);
77 return new IsolatedLeader(context);
79 return new Leader(context);
81 return new PreLeader(context);
83 throw new IllegalArgumentException("Unhandled state " + state);
88 public final RaftState state() {
92 protected final String logName() {
97 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
98 this.replicatedToAllIndex = replicatedToAllIndex;
102 public long getReplicatedToAllIndex() {
103 return replicatedToAllIndex;
107 * Derived classes should not directly handle AppendEntries messages it
108 * should let the base class handle it first. Once the base class handles
109 * the AppendEntries message and does the common actions that are applicable
110 * in all RaftState's it will delegate the handling of the AppendEntries
111 * message to the derived class to do more state specific handling by calling
114 * @param sender The actor that sent this message
115 * @param appendEntries The AppendEntries message
116 * @return a new behavior if it was changed or the current behavior
118 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
119 AppendEntries appendEntries);
123 * appendEntries first processes the AppendEntries message and then
124 * delegates handling to a specific behavior
127 * @param appendEntries
128 * @return a new behavior if it was changed or the current behavior
130 protected RaftActorBehavior appendEntries(ActorRef sender,
131 AppendEntries appendEntries) {
133 // 1. Reply false if term < currentTerm (§5.1)
134 if (appendEntries.getTerm() < currentTerm()) {
135 if(LOG.isDebugEnabled()) {
136 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
137 logName(), appendEntries.getTerm(), currentTerm());
141 new AppendEntriesReply(context.getId(), currentTerm(), false,
142 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
148 return handleAppendEntries(sender, appendEntries);
152 * Derived classes should not directly handle AppendEntriesReply messages it
153 * should let the base class handle it first. Once the base class handles
154 * the AppendEntriesReply message and does the common actions that are
155 * applicable in all RaftState's it will delegate the handling of the
156 * AppendEntriesReply message to the derived class to do more state specific
157 * handling by calling this method
159 * @param sender The actor that sent this message
160 * @param appendEntriesReply The AppendEntriesReply message
161 * @return a new behavior if it was changed or the current behavior
163 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
164 AppendEntriesReply appendEntriesReply);
167 * requestVote handles the RequestVote message. This logic is common
172 * @return a new behavior if it was changed or the current behavior
174 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
176 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
178 boolean grantVote = canGrantVote(requestVote);
181 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
184 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
186 LOG.debug("{}: requestVote returning: {}", logName(), reply);
188 sender.tell(reply, actor());
193 protected boolean canGrantVote(RequestVote requestVote){
194 boolean grantVote = false;
196 // Reply false if term < currentTerm (§5.1)
197 if (requestVote.getTerm() < currentTerm()) {
200 // If votedFor is null or candidateId, and candidate’s log is at
201 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
202 } else if (votedFor() == null || votedFor()
203 .equals(requestVote.getCandidateId())) {
205 boolean candidateLatest = false;
208 // Raft determines which of two logs is more up-to-date
209 // by comparing the index and term of the last entries in the
210 // logs. If the logs have last entries with different terms, then
211 // the log with the later term is more up-to-date. If the logs
212 // end with the same term, then whichever log is longer is
214 if (requestVote.getLastLogTerm() > lastTerm()) {
215 candidateLatest = true;
216 } else if ((requestVote.getLastLogTerm() == lastTerm())
217 && requestVote.getLastLogIndex() >= lastIndex()) {
218 candidateLatest = true;
221 if (candidateLatest) {
229 * Derived classes should not directly handle RequestVoteReply messages it
230 * should let the base class handle it first. Once the base class handles
231 * the RequestVoteReply message and does the common actions that are
232 * applicable in all RaftState's it will delegate the handling of the
233 * RequestVoteReply message to the derived class to do more state specific
234 * handling by calling this method
236 * @param sender The actor that sent this message
237 * @param requestVoteReply The RequestVoteReply message
238 * @return a new behavior if it was changed or the current behavior
240 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
241 RequestVoteReply requestVoteReply);
245 * @return a random election duration
247 protected FiniteDuration electionDuration() {
248 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
249 return context.getConfigParams().getElectionTimeOutInterval().$plus(
250 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
254 * stop the scheduled election
256 protected void stopElection() {
257 if (electionCancel != null && !electionCancel.isCancelled()) {
258 electionCancel.cancel();
262 protected boolean canStartElection() {
263 return context.getRaftPolicy().automaticElectionsEnabled() && context.isVotingMember();
267 * schedule a new election
269 * @param interval the duration after which we should trigger a new election
271 protected void scheduleElection(FiniteDuration interval) {
274 // Schedule an election. When the scheduler triggers an ElectionTimeout message is sent to itself
275 electionCancel = context.getActorSystem().scheduler().scheduleOnce(interval, context.getActor(),
276 ElectionTimeout.INSTANCE, context.getActorSystem().dispatcher(), context.getActor());
280 * @return the current term
282 protected long currentTerm() {
283 return context.getTermInformation().getCurrentTerm();
287 * @return the candidate for whom we voted in the current term
289 protected String votedFor() {
290 return context.getTermInformation().getVotedFor();
294 * @return the actor associated with this behavior
296 protected ActorRef actor() {
297 return context.getActor();
302 * @return the term from the last entry in the log
304 protected long lastTerm() {
305 return context.getReplicatedLog().lastTerm();
309 * @return the index from the last entry in the log
311 protected long lastIndex() {
312 return context.getReplicatedLog().lastIndex();
317 * @return the client request tracker for the specified logIndex
319 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
325 * @return the log entry index for the given index or -1 if not found
327 protected long getLogEntryIndex(long index){
328 if(index == context.getReplicatedLog().getSnapshotIndex()){
329 return context.getReplicatedLog().getSnapshotIndex();
332 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
334 return entry.getIndex();
341 * @return the log entry term for the given index or -1 if not found
343 protected long getLogEntryTerm(long index){
344 if(index == context.getReplicatedLog().getSnapshotIndex()){
345 return context.getReplicatedLog().getSnapshotTerm();
348 ReplicatedLogEntry entry = context.getReplicatedLog().get(index);
350 return entry.getTerm();
357 * Apply the provided index to the state machine
359 * @param index a log index that is known to be committed
361 protected void applyLogToStateMachine(final long index) {
362 long newLastApplied = context.getLastApplied();
363 // Now maybe we apply to the state machine
364 for (long i = context.getLastApplied() + 1; i < index + 1; i++) {
366 ReplicatedLogEntry replicatedLogEntry = context.getReplicatedLog().get(i);
367 if (replicatedLogEntry != null) {
368 // Send a local message to the local RaftActor (it's derived class to be
369 // specific to apply the log to it's index)
371 final ApplyState msg;
372 final ClientRequestTracker tracker = removeClientRequestTracker(i);
373 if (tracker != null) {
374 msg = new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), replicatedLogEntry);
376 msg = new ApplyState(null, null, replicatedLogEntry);
379 actor().tell(msg, actor());
382 //if one index is not present in the log, no point in looping
383 // around as the rest wont be present either
384 LOG.warn("{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
385 logName(), i, i, index);
389 if(LOG.isDebugEnabled()) {
390 LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
392 context.setLastApplied(newLastApplied);
394 // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
395 // will be used during recovery
396 //in case if the above code throws an error and this message is not sent, it would be fine
397 // as the append entries received later would initiate add this message to the journal
398 actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
402 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
403 if (message instanceof AppendEntries) {
404 return appendEntries(sender, (AppendEntries) message);
405 } else if (message instanceof AppendEntriesReply) {
406 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
407 } else if (message instanceof RequestVote) {
408 return requestVote(sender, (RequestVote) message);
409 } else if (message instanceof RequestVoteReply) {
410 return handleRequestVoteReply(sender, (RequestVoteReply) message);
417 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
418 return internalSwitchBehavior(behavior);
421 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
422 return internalSwitchBehavior(createBehavior(context, newState));
425 protected RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
426 if(!context.getRaftPolicy().automaticElectionsEnabled()) {
430 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
433 } catch (Exception e) {
434 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
440 protected int getMajorityVoteCount(int numPeers) {
441 // Votes are required from a majority of the peers including self.
442 // The numMajority field therefore stores a calculated value
443 // of the number of votes required for this candidate to win an
444 // election based on it's known peers.
445 // If a peer was added during normal operation and raft replicas
446 // came to know about them then the new peer would also need to be
447 // taken into consideration when calculating this value.
448 // Here are some examples for what the numMajority would be for n
450 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
451 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
452 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
457 numMajority = (numPeers + self) / 2 + 1;
465 * Performs a snapshot with no capture on the replicated log.
466 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
468 * @param snapshotCapturedIndex
470 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
471 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex);
473 if(actualIndex != -1){
474 setReplicatedToAllIndex(actualIndex);
478 protected String getId(){
479 return context.getId();