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 java.util.Random;
14 import java.util.concurrent.TimeUnit;
15 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
16 import org.opendaylight.controller.cluster.raft.RaftActorContext;
17 import org.opendaylight.controller.cluster.raft.RaftState;
18 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
19 import org.opendaylight.controller.cluster.raft.SerializationUtils;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
22 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
23 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
24 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
25 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
26 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
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 protected static final ElectionTimeout ELECTION_TIMEOUT = new ElectionTimeout();
45 * Information about the RaftActor whose behavior this class represents
47 protected final RaftActorContext context;
52 protected final Logger LOG;
57 private Cancellable electionCancel = null;
62 protected String leaderId = null;
64 private short leaderPayloadVersion = -1;
66 private long replicatedToAllIndex = -1;
68 private final String logName;
70 private final RaftState state;
72 protected AbstractRaftActorBehavior(RaftActorContext context, RaftState state) {
73 this.context = context;
75 this.LOG = context.getLogger();
77 logName = String.format("%s (%s)", context.getId(), state);
81 public RaftState state() {
85 public String logName() {
90 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
91 this.replicatedToAllIndex = replicatedToAllIndex;
95 public long getReplicatedToAllIndex() {
96 return replicatedToAllIndex;
100 * Derived classes should not directly handle AppendEntries messages it
101 * should let the base class handle it first. Once the base class handles
102 * the AppendEntries message and does the common actions that are applicable
103 * in all RaftState's it will delegate the handling of the AppendEntries
104 * message to the derived class to do more state specific handling by calling
107 * @param sender The actor that sent this message
108 * @param appendEntries The AppendEntries message
109 * @return a new behavior if it was changed or the current behavior
111 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
112 AppendEntries appendEntries);
116 * appendEntries first processes the AppendEntries message and then
117 * delegates handling to a specific behavior
120 * @param appendEntries
121 * @return a new behavior if it was changed or the current behavior
123 protected RaftActorBehavior appendEntries(ActorRef sender,
124 AppendEntries appendEntries) {
126 // 1. Reply false if term < currentTerm (§5.1)
127 if (appendEntries.getTerm() < currentTerm()) {
128 if(LOG.isDebugEnabled()) {
129 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
130 logName(), appendEntries.getTerm(), currentTerm());
134 new AppendEntriesReply(context.getId(), currentTerm(), false,
135 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
141 return handleAppendEntries(sender, appendEntries);
145 * Derived classes should not directly handle AppendEntriesReply messages it
146 * should let the base class handle it first. Once the base class handles
147 * the AppendEntriesReply message and does the common actions that are
148 * applicable in all RaftState's it will delegate the handling of the
149 * AppendEntriesReply message to the derived class to do more state specific
150 * handling by calling this method
152 * @param sender The actor that sent this message
153 * @param appendEntriesReply The AppendEntriesReply message
154 * @return a new behavior if it was changed or the current behavior
156 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
157 AppendEntriesReply appendEntriesReply);
160 * requestVote handles the RequestVote message. This logic is common
165 * @return a new behavior if it was changed or the current behavior
167 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
169 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
171 boolean grantVote = canGrantVote(requestVote);
174 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
177 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
179 LOG.debug("{}: requestVote returning: {}", logName(), reply);
181 sender.tell(reply, actor());
186 protected boolean canGrantVote(RequestVote requestVote){
187 boolean grantVote = false;
189 // Reply false if term < currentTerm (§5.1)
190 if (requestVote.getTerm() < currentTerm()) {
193 // If votedFor is null or candidateId, and candidate’s log is at
194 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
195 } else if (votedFor() == null || votedFor()
196 .equals(requestVote.getCandidateId())) {
198 boolean candidateLatest = false;
201 // Raft determines which of two logs is more up-to-date
202 // by comparing the index and term of the last entries in the
203 // logs. If the logs have last entries with different terms, then
204 // the log with the later term is more up-to-date. If the logs
205 // end with the same term, then whichever log is longer is
207 if (requestVote.getLastLogTerm() > lastTerm()) {
208 candidateLatest = true;
209 } else if ((requestVote.getLastLogTerm() == lastTerm())
210 && requestVote.getLastLogIndex() >= lastIndex()) {
211 candidateLatest = true;
214 if (candidateLatest) {
222 * Derived classes should not directly handle RequestVoteReply messages it
223 * should let the base class handle it first. Once the base class handles
224 * the RequestVoteReply message and does the common actions that are
225 * applicable in all RaftState's it will delegate the handling of the
226 * RequestVoteReply message to the derived class to do more state specific
227 * handling by calling this method
229 * @param sender The actor that sent this message
230 * @param requestVoteReply The RequestVoteReply message
231 * @return a new behavior if it was changed or the current behavior
233 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
234 RequestVoteReply requestVoteReply);
238 * @return a random election duration
240 protected FiniteDuration electionDuration() {
241 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
242 return context.getConfigParams().getElectionTimeOutInterval().$plus(
243 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
247 * stop the scheduled election
249 protected void stopElection() {
250 if (electionCancel != null && !electionCancel.isCancelled()) {
251 electionCancel.cancel();
255 protected boolean canStartElection() {
256 return context.getRaftPolicy().automaticElectionsEnabled() && context.isVotingMember();
260 * schedule a new election
262 * @param interval the duration after which we should trigger a new election
264 protected void scheduleElection(FiniteDuration interval) {
267 if(canStartElection()) {
268 // Schedule an election. When the scheduler triggers an ElectionTimeout message is sent to itself
269 electionCancel = context.getActorSystem().scheduler().scheduleOnce(interval, context.getActor(),
270 ELECTION_TIMEOUT,context.getActorSystem().dispatcher(), context.getActor());
275 * @return the current term
277 protected long currentTerm() {
278 return context.getTermInformation().getCurrentTerm();
282 * @return the candidate for whom we voted in the current term
284 protected String votedFor() {
285 return context.getTermInformation().getVotedFor();
289 * @return the actor associated with this behavior
291 protected ActorRef actor() {
292 return context.getActor();
297 * @return the term from the last entry in the log
299 protected long lastTerm() {
300 return context.getReplicatedLog().lastTerm();
304 * @return the index from the last entry in the log
306 protected long lastIndex() {
307 return context.getReplicatedLog().lastIndex();
312 * @return the client request tracker for the specified logIndex
314 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
320 * @return the client request tracker for the specified logIndex
322 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
329 * @return log index from the previous to last entry in the log
331 protected long prevLogIndex(long index){
332 ReplicatedLogEntry prevEntry =
333 context.getReplicatedLog().get(index - 1);
334 if (prevEntry != null) {
335 return prevEntry.getIndex();
341 * @return log term from the previous to last entry in the log
343 protected long prevLogTerm(long index){
344 ReplicatedLogEntry prevEntry =
345 context.getReplicatedLog().get(index - 1);
346 if (prevEntry != null) {
347 return prevEntry.getTerm();
353 * Apply the provided index to the state machine
355 * @param index a log index that is known to be committed
357 protected void applyLogToStateMachine(final long index) {
358 long newLastApplied = context.getLastApplied();
359 // Now maybe we apply to the state machine
360 for (long i = context.getLastApplied() + 1;
361 i < index + 1; i++) {
362 ActorRef clientActor = null;
363 String identifier = null;
364 ClientRequestTracker tracker = removeClientRequestTracker(i);
366 if (tracker != null) {
367 clientActor = tracker.getClientActor();
368 identifier = tracker.getIdentifier();
370 ReplicatedLogEntry replicatedLogEntry =
371 context.getReplicatedLog().get(i);
373 if (replicatedLogEntry != null) {
374 // Send a local message to the local RaftActor (it's derived class to be
375 // specific to apply the log to it's index)
376 actor().tell(new ApplyState(clientActor, identifier,
377 replicatedLogEntry), actor());
380 //if one index is not present in the log, no point in looping
381 // around as the rest wont be present either
383 "{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
384 logName(), i, i, index);
388 if(LOG.isDebugEnabled()) {
389 LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
391 context.setLastApplied(newLastApplied);
393 // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
394 // will be used during recovery
395 //in case if the above code throws an error and this message is not sent, it would be fine
396 // as the append entries received later would initiate add this message to the journal
397 actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
400 protected Object fromSerializableMessage(Object serializable){
401 return SerializationUtils.fromSerializable(serializable);
405 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
406 if (message instanceof AppendEntries) {
407 return appendEntries(sender, (AppendEntries) message);
408 } else if (message instanceof AppendEntriesReply) {
409 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
410 } else if (message instanceof RequestVote) {
411 return requestVote(sender, (RequestVote) message);
412 } else if (message instanceof RequestVoteReply) {
413 return handleRequestVoteReply(sender, (RequestVoteReply) message);
418 @Override public String getLeaderId() {
423 public short getLeaderPayloadVersion() {
424 return leaderPayloadVersion;
427 public void setLeaderPayloadVersion(short leaderPayloadVersion) {
428 this.leaderPayloadVersion = leaderPayloadVersion;
432 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
433 return internalSwitchBehavior(behavior);
436 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
437 if(context.getRaftPolicy().automaticElectionsEnabled()){
438 return internalSwitchBehavior(newState.createBehavior(context));
443 private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
444 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
447 } catch (Exception e) {
448 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
454 protected int getMajorityVoteCount(int numPeers) {
455 // Votes are required from a majority of the peers including self.
456 // The numMajority field therefore stores a calculated value
457 // of the number of votes required for this candidate to win an
458 // election based on it's known peers.
459 // If a peer was added during normal operation and raft replicas
460 // came to know about them then the new peer would also need to be
461 // taken into consideration when calculating this value.
462 // Here are some examples for what the numMajority would be for n
464 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
465 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
466 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
471 numMajority = (numPeers + self) / 2 + 1;
479 * Performs a snapshot with no capture on the replicated log.
480 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
482 * @param snapshotCapturedIndex
484 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
485 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex, this);
487 if(actualIndex != -1){
488 setReplicatedToAllIndex(actualIndex);
492 protected String getId(){
493 return context.getId();