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.ServerConfigurationPayload;
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 protected static final ElectionTimeout ELECTION_TIMEOUT = new ElectionTimeout();
46 * Information about the RaftActor whose behavior this class represents
48 protected final RaftActorContext context;
53 protected final Logger LOG;
58 private Cancellable electionCancel = null;
63 protected String leaderId = null;
65 private short leaderPayloadVersion = -1;
67 private long replicatedToAllIndex = -1;
69 private final String logName;
71 private final RaftState state;
73 protected AbstractRaftActorBehavior(RaftActorContext context, RaftState state) {
74 this.context = context;
76 this.LOG = context.getLogger();
78 logName = String.format("%s (%s)", context.getId(), state);
82 public RaftState state() {
86 public String logName() {
91 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
92 this.replicatedToAllIndex = replicatedToAllIndex;
96 public long getReplicatedToAllIndex() {
97 return replicatedToAllIndex;
101 * Derived classes should not directly handle AppendEntries messages it
102 * should let the base class handle it first. Once the base class handles
103 * the AppendEntries message and does the common actions that are applicable
104 * in all RaftState's it will delegate the handling of the AppendEntries
105 * message to the derived class to do more state specific handling by calling
108 * @param sender The actor that sent this message
109 * @param appendEntries The AppendEntries message
110 * @return a new behavior if it was changed or the current behavior
112 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
113 AppendEntries appendEntries);
117 * appendEntries first processes the AppendEntries message and then
118 * delegates handling to a specific behavior
121 * @param appendEntries
122 * @return a new behavior if it was changed or the current behavior
124 protected RaftActorBehavior appendEntries(ActorRef sender,
125 AppendEntries appendEntries) {
127 // 1. Reply false if term < currentTerm (§5.1)
128 if (appendEntries.getTerm() < currentTerm()) {
129 if(LOG.isDebugEnabled()) {
130 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
131 logName(), appendEntries.getTerm(), currentTerm());
135 new AppendEntriesReply(context.getId(), currentTerm(), false,
136 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
142 return handleAppendEntries(sender, appendEntries);
146 * Derived classes should not directly handle AppendEntriesReply messages it
147 * should let the base class handle it first. Once the base class handles
148 * the AppendEntriesReply message and does the common actions that are
149 * applicable in all RaftState's it will delegate the handling of the
150 * AppendEntriesReply message to the derived class to do more state specific
151 * handling by calling this method
153 * @param sender The actor that sent this message
154 * @param appendEntriesReply The AppendEntriesReply message
155 * @return a new behavior if it was changed or the current behavior
157 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
158 AppendEntriesReply appendEntriesReply);
161 * requestVote handles the RequestVote message. This logic is common
166 * @return a new behavior if it was changed or the current behavior
168 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
170 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
172 boolean grantVote = canGrantVote(requestVote);
175 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
178 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
180 LOG.debug("{}: requestVote returning: {}", logName(), reply);
182 sender.tell(reply, actor());
187 protected boolean canGrantVote(RequestVote requestVote){
188 boolean grantVote = false;
190 // Reply false if term < currentTerm (§5.1)
191 if (requestVote.getTerm() < currentTerm()) {
194 // If votedFor is null or candidateId, and candidate’s log is at
195 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
196 } else if (votedFor() == null || votedFor()
197 .equals(requestVote.getCandidateId())) {
199 boolean candidateLatest = false;
202 // Raft determines which of two logs is more up-to-date
203 // by comparing the index and term of the last entries in the
204 // logs. If the logs have last entries with different terms, then
205 // the log with the later term is more up-to-date. If the logs
206 // end with the same term, then whichever log is longer is
208 if (requestVote.getLastLogTerm() > lastTerm()) {
209 candidateLatest = true;
210 } else if ((requestVote.getLastLogTerm() == lastTerm())
211 && requestVote.getLastLogIndex() >= lastIndex()) {
212 candidateLatest = true;
215 if (candidateLatest) {
223 * Derived classes should not directly handle RequestVoteReply messages it
224 * should let the base class handle it first. Once the base class handles
225 * the RequestVoteReply message and does the common actions that are
226 * applicable in all RaftState's it will delegate the handling of the
227 * RequestVoteReply message to the derived class to do more state specific
228 * handling by calling this method
230 * @param sender The actor that sent this message
231 * @param requestVoteReply The RequestVoteReply message
232 * @return a new behavior if it was changed or the current behavior
234 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
235 RequestVoteReply requestVoteReply);
239 * @return a random election duration
241 protected FiniteDuration electionDuration() {
242 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
243 return context.getConfigParams().getElectionTimeOutInterval().$plus(
244 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
248 * stop the scheduled election
250 protected void stopElection() {
251 if (electionCancel != null && !electionCancel.isCancelled()) {
252 electionCancel.cancel();
257 * schedule a new election
259 * @param interval the duration after which we should trigger a new election
261 protected void scheduleElection(FiniteDuration interval) {
264 // Schedule an election. When the scheduler triggers an ElectionTimeout
265 // message is sent to itself
267 context.getActorSystem().scheduler().scheduleOnce(interval,
268 context.getActor(), ELECTION_TIMEOUT,
269 context.getActorSystem().dispatcher(), context.getActor());
273 * @return the current term
275 protected long currentTerm() {
276 return context.getTermInformation().getCurrentTerm();
280 * @return the candidate for whom we voted in the current term
282 protected String votedFor() {
283 return context.getTermInformation().getVotedFor();
287 * @return the actor associated with this behavior
289 protected ActorRef actor() {
290 return context.getActor();
295 * @return the term from the last entry in the log
297 protected long lastTerm() {
298 return context.getReplicatedLog().lastTerm();
302 * @return the index from the last entry in the log
304 protected long lastIndex() {
305 return context.getReplicatedLog().lastIndex();
310 * @return the client request tracker for the specified logIndex
312 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
318 * @return the client request tracker for the specified logIndex
320 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
327 * @return log index from the previous to last entry in the log
329 protected long prevLogIndex(long index){
330 ReplicatedLogEntry prevEntry =
331 context.getReplicatedLog().get(index - 1);
332 if (prevEntry != null) {
333 return prevEntry.getIndex();
339 * @return log term from the previous to last entry in the log
341 protected long prevLogTerm(long index){
342 ReplicatedLogEntry prevEntry =
343 context.getReplicatedLog().get(index - 1);
344 if (prevEntry != null) {
345 return prevEntry.getTerm();
351 * Apply the provided index to the state machine
353 * @param index a log index that is known to be committed
355 protected void applyLogToStateMachine(final long index) {
356 long newLastApplied = context.getLastApplied();
357 // Now maybe we apply to the state machine
358 for (long i = context.getLastApplied() + 1;
359 i < index + 1; i++) {
360 ActorRef clientActor = null;
361 String identifier = null;
362 ClientRequestTracker tracker = removeClientRequestTracker(i);
364 if (tracker != null) {
365 clientActor = tracker.getClientActor();
366 identifier = tracker.getIdentifier();
368 ReplicatedLogEntry replicatedLogEntry =
369 context.getReplicatedLog().get(i);
371 if (replicatedLogEntry != null) {
372 // Send a local message to the local RaftActor (it's derived class to be
373 // specific to apply the log to it's index)
374 actor().tell(new ApplyState(clientActor, identifier,
375 replicatedLogEntry), actor());
378 //if one index is not present in the log, no point in looping
379 // around as the rest wont be present either
381 "{}: Missing index {} from log. Cannot apply state. Ignoring {} to {}",
382 logName(), i, i, index);
386 if(LOG.isDebugEnabled()) {
387 LOG.debug("{}: Setting last applied to {}", logName(), newLastApplied);
389 context.setLastApplied(newLastApplied);
391 // send a message to persist a ApplyLogEntries marker message into akka's persistent journal
392 // will be used during recovery
393 //in case if the above code throws an error and this message is not sent, it would be fine
394 // as the append entries received later would initiate add this message to the journal
395 actor().tell(new ApplyJournalEntries(context.getLastApplied()), actor());
398 protected Object fromSerializableMessage(Object serializable){
399 return SerializationUtils.fromSerializable(serializable);
403 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
404 if (message instanceof AppendEntries) {
405 return appendEntries(sender, (AppendEntries) message);
406 } else if (message instanceof AppendEntriesReply) {
407 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
408 } else if (message instanceof RequestVote) {
409 return requestVote(sender, (RequestVote) message);
410 } else if (message instanceof RequestVoteReply) {
411 return handleRequestVoteReply(sender, (RequestVoteReply) message);
416 @Override public String getLeaderId() {
421 public short getLeaderPayloadVersion() {
422 return leaderPayloadVersion;
425 public void setLeaderPayloadVersion(short leaderPayloadVersion) {
426 this.leaderPayloadVersion = leaderPayloadVersion;
430 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
431 return internalSwitchBehavior(behavior);
434 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
435 if(context.getRaftPolicy().automaticElectionsEnabled()){
436 return internalSwitchBehavior(newState.createBehavior(context));
441 private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
442 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
445 } catch (Exception e) {
446 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
452 protected int getMajorityVoteCount(int numPeers) {
453 // Votes are required from a majority of the peers including self.
454 // The numMajority field therefore stores a calculated value
455 // of the number of votes required for this candidate to win an
456 // election based on it's known peers.
457 // If a peer was added during normal operation and raft replicas
458 // came to know about them then the new peer would also need to be
459 // taken into consideration when calculating this value.
460 // Here are some examples for what the numMajority would be for n
462 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
463 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
464 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
469 numMajority = (numPeers + self) / 2 + 1;
477 * Performs a snapshot with no capture on the replicated log.
478 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
480 * @param snapshotCapturedIndex
482 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
483 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex, this);
485 if(actualIndex != -1){
486 setReplicatedToAllIndex(actualIndex);
490 protected String getId(){
491 return context.getId();
494 public void applyServerConfiguration(ServerConfigurationPayload serverConfig) {
495 for(String peerId: context.getPeerAddresses().keySet()) {
496 context.removePeer(peerId);
499 for(String peerId: serverConfig.getNewServerConfig()) {
500 if(!getId().equals(peerId)) {
501 context.addToPeers(peerId, null);