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.HashSet;
14 import java.util.Random;
16 import java.util.concurrent.TimeUnit;
17 import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
18 import org.opendaylight.controller.cluster.raft.RaftActorContext;
19 import org.opendaylight.controller.cluster.raft.RaftState;
20 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
21 import org.opendaylight.controller.cluster.raft.SerializationUtils;
22 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload;
23 import org.opendaylight.controller.cluster.raft.VotingState;
24 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
25 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
26 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
27 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
28 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
29 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
30 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
31 import org.slf4j.Logger;
32 import scala.concurrent.duration.FiniteDuration;
35 * Abstract class that represents the behavior of a RaftActor
39 * <li> If commitIndex > lastApplied: increment lastApplied, apply
40 * log[lastApplied] to state machine (§5.3)
41 * <li> If RPC request or response contains term T > currentTerm:
42 * set currentTerm = T, convert to follower (§5.1)
44 public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
46 protected static final ElectionTimeout ELECTION_TIMEOUT = new ElectionTimeout();
49 * Information about the RaftActor whose behavior this class represents
51 protected final RaftActorContext context;
56 protected final Logger LOG;
61 private Cancellable electionCancel = null;
66 protected String leaderId = null;
68 private short leaderPayloadVersion = -1;
70 private long replicatedToAllIndex = -1;
72 private final String logName;
74 private final RaftState state;
76 protected AbstractRaftActorBehavior(RaftActorContext context, RaftState state) {
77 this.context = context;
79 this.LOG = context.getLogger();
81 logName = String.format("%s (%s)", context.getId(), state);
85 public RaftState state() {
89 public String logName() {
94 public void setReplicatedToAllIndex(long replicatedToAllIndex) {
95 this.replicatedToAllIndex = replicatedToAllIndex;
99 public long getReplicatedToAllIndex() {
100 return replicatedToAllIndex;
104 * Derived classes should not directly handle AppendEntries messages it
105 * should let the base class handle it first. Once the base class handles
106 * the AppendEntries message and does the common actions that are applicable
107 * in all RaftState's it will delegate the handling of the AppendEntries
108 * message to the derived class to do more state specific handling by calling
111 * @param sender The actor that sent this message
112 * @param appendEntries The AppendEntries message
113 * @return a new behavior if it was changed or the current behavior
115 protected abstract RaftActorBehavior handleAppendEntries(ActorRef sender,
116 AppendEntries appendEntries);
120 * appendEntries first processes the AppendEntries message and then
121 * delegates handling to a specific behavior
124 * @param appendEntries
125 * @return a new behavior if it was changed or the current behavior
127 protected RaftActorBehavior appendEntries(ActorRef sender,
128 AppendEntries appendEntries) {
130 // 1. Reply false if term < currentTerm (§5.1)
131 if (appendEntries.getTerm() < currentTerm()) {
132 if(LOG.isDebugEnabled()) {
133 LOG.debug("{}: Cannot append entries because sender term {} is less than {}",
134 logName(), appendEntries.getTerm(), currentTerm());
138 new AppendEntriesReply(context.getId(), currentTerm(), false,
139 lastIndex(), lastTerm(), context.getPayloadVersion()), actor()
145 return handleAppendEntries(sender, appendEntries);
149 * Derived classes should not directly handle AppendEntriesReply messages it
150 * should let the base class handle it first. Once the base class handles
151 * the AppendEntriesReply message and does the common actions that are
152 * applicable in all RaftState's it will delegate the handling of the
153 * AppendEntriesReply message to the derived class to do more state specific
154 * handling by calling this method
156 * @param sender The actor that sent this message
157 * @param appendEntriesReply The AppendEntriesReply message
158 * @return a new behavior if it was changed or the current behavior
160 protected abstract RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
161 AppendEntriesReply appendEntriesReply);
164 * requestVote handles the RequestVote message. This logic is common
169 * @return a new behavior if it was changed or the current behavior
171 protected RaftActorBehavior requestVote(ActorRef sender, RequestVote requestVote) {
173 LOG.debug("{}: In requestVote: {}", logName(), requestVote);
175 boolean grantVote = canGrantVote(requestVote);
178 context.getTermInformation().updateAndPersist(requestVote.getTerm(), requestVote.getCandidateId());
181 RequestVoteReply reply = new RequestVoteReply(currentTerm(), grantVote);
183 LOG.debug("{}: requestVote returning: {}", logName(), reply);
185 sender.tell(reply, actor());
190 protected boolean canGrantVote(RequestVote requestVote){
191 boolean grantVote = false;
193 // Reply false if term < currentTerm (§5.1)
194 if (requestVote.getTerm() < currentTerm()) {
197 // If votedFor is null or candidateId, and candidate’s log is at
198 // least as up-to-date as receiver’s log, grant vote (§5.2, §5.4)
199 } else if (votedFor() == null || votedFor()
200 .equals(requestVote.getCandidateId())) {
202 boolean candidateLatest = false;
205 // Raft determines which of two logs is more up-to-date
206 // by comparing the index and term of the last entries in the
207 // logs. If the logs have last entries with different terms, then
208 // the log with the later term is more up-to-date. If the logs
209 // end with the same term, then whichever log is longer is
211 if (requestVote.getLastLogTerm() > lastTerm()) {
212 candidateLatest = true;
213 } else if ((requestVote.getLastLogTerm() == lastTerm())
214 && requestVote.getLastLogIndex() >= lastIndex()) {
215 candidateLatest = true;
218 if (candidateLatest) {
226 * Derived classes should not directly handle RequestVoteReply messages it
227 * should let the base class handle it first. Once the base class handles
228 * the RequestVoteReply message and does the common actions that are
229 * applicable in all RaftState's it will delegate the handling of the
230 * RequestVoteReply message to the derived class to do more state specific
231 * handling by calling this method
233 * @param sender The actor that sent this message
234 * @param requestVoteReply The RequestVoteReply message
235 * @return a new behavior if it was changed or the current behavior
237 protected abstract RaftActorBehavior handleRequestVoteReply(ActorRef sender,
238 RequestVoteReply requestVoteReply);
242 * @return a random election duration
244 protected FiniteDuration electionDuration() {
245 long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
246 return context.getConfigParams().getElectionTimeOutInterval().$plus(
247 new FiniteDuration(variance, TimeUnit.MILLISECONDS));
251 * stop the scheduled election
253 protected void stopElection() {
254 if (electionCancel != null && !electionCancel.isCancelled()) {
255 electionCancel.cancel();
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 // Schedule an election. When the scheduler triggers an ElectionTimeout
268 // message is sent to itself
270 context.getActorSystem().scheduler().scheduleOnce(interval,
271 context.getActor(), ELECTION_TIMEOUT,
272 context.getActorSystem().dispatcher(), context.getActor());
276 * @return the current term
278 protected long currentTerm() {
279 return context.getTermInformation().getCurrentTerm();
283 * @return the candidate for whom we voted in the current term
285 protected String votedFor() {
286 return context.getTermInformation().getVotedFor();
290 * @return the actor associated with this behavior
292 protected ActorRef actor() {
293 return context.getActor();
298 * @return the term from the last entry in the log
300 protected long lastTerm() {
301 return context.getReplicatedLog().lastTerm();
305 * @return the index from the last entry in the log
307 protected long lastIndex() {
308 return context.getReplicatedLog().lastIndex();
313 * @return the client request tracker for the specified logIndex
315 protected ClientRequestTracker findClientRequestTracker(long logIndex) {
321 * @return the client request tracker for the specified logIndex
323 protected ClientRequestTracker removeClientRequestTracker(long logIndex) {
330 * @return log index from the previous to last entry in the log
332 protected long prevLogIndex(long index){
333 ReplicatedLogEntry prevEntry =
334 context.getReplicatedLog().get(index - 1);
335 if (prevEntry != null) {
336 return prevEntry.getIndex();
342 * @return log term from the previous to last entry in the log
344 protected long prevLogTerm(long index){
345 ReplicatedLogEntry prevEntry =
346 context.getReplicatedLog().get(index - 1);
347 if (prevEntry != null) {
348 return prevEntry.getTerm();
354 * Apply the provided index to the state machine
356 * @param index a log index that is known to be committed
358 protected void applyLogToStateMachine(final long index) {
359 long newLastApplied = context.getLastApplied();
360 // Now maybe we apply to the state machine
361 for (long i = context.getLastApplied() + 1;
362 i < index + 1; i++) {
363 ActorRef clientActor = null;
364 String identifier = null;
365 ClientRequestTracker tracker = removeClientRequestTracker(i);
367 if (tracker != null) {
368 clientActor = tracker.getClientActor();
369 identifier = tracker.getIdentifier();
371 ReplicatedLogEntry replicatedLogEntry =
372 context.getReplicatedLog().get(i);
374 if (replicatedLogEntry != null) {
375 // Send a local message to the local RaftActor (it's derived class to be
376 // specific to apply the log to it's index)
377 actor().tell(new ApplyState(clientActor, identifier,
378 replicatedLogEntry), actor());
381 //if one index is not present in the log, no point in looping
382 // around as the rest wont be present either
384 "{}: 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());
401 protected Object fromSerializableMessage(Object serializable){
402 return SerializationUtils.fromSerializable(serializable);
406 public RaftActorBehavior handleMessage(ActorRef sender, Object message) {
407 if (message instanceof AppendEntries) {
408 return appendEntries(sender, (AppendEntries) message);
409 } else if (message instanceof AppendEntriesReply) {
410 return handleAppendEntriesReply(sender, (AppendEntriesReply) message);
411 } else if (message instanceof RequestVote) {
412 return requestVote(sender, (RequestVote) message);
413 } else if (message instanceof RequestVoteReply) {
414 return handleRequestVoteReply(sender, (RequestVoteReply) message);
419 @Override public String getLeaderId() {
424 public short getLeaderPayloadVersion() {
425 return leaderPayloadVersion;
428 public void setLeaderPayloadVersion(short leaderPayloadVersion) {
429 this.leaderPayloadVersion = leaderPayloadVersion;
433 public RaftActorBehavior switchBehavior(RaftActorBehavior behavior) {
434 return internalSwitchBehavior(behavior);
437 protected RaftActorBehavior internalSwitchBehavior(RaftState newState) {
438 if(context.getRaftPolicy().automaticElectionsEnabled()){
439 return internalSwitchBehavior(newState.createBehavior(context));
444 private RaftActorBehavior internalSwitchBehavior(RaftActorBehavior newBehavior) {
445 LOG.info("{} :- Switching from behavior {} to {}", logName(), this.state(), newBehavior.state());
448 } catch (Exception e) {
449 LOG.error("{}: Failed to close behavior : {}", logName(), this.state(), e);
455 protected int getMajorityVoteCount(int numPeers) {
456 // Votes are required from a majority of the peers including self.
457 // The numMajority field therefore stores a calculated value
458 // of the number of votes required for this candidate to win an
459 // election based on it's known peers.
460 // If a peer was added during normal operation and raft replicas
461 // came to know about them then the new peer would also need to be
462 // taken into consideration when calculating this value.
463 // Here are some examples for what the numMajority would be for n
465 // 0 peers = 1 numMajority -: (0 + 1) / 2 + 1 = 1
466 // 2 peers = 2 numMajority -: (2 + 1) / 2 + 1 = 2
467 // 4 peers = 3 numMajority -: (4 + 1) / 2 + 1 = 3
472 numMajority = (numPeers + self) / 2 + 1;
480 * Performs a snapshot with no capture on the replicated log.
481 * It clears the log from the supplied index or last-applied-1 which ever is minimum.
483 * @param snapshotCapturedIndex
485 protected void performSnapshotWithoutCapture(final long snapshotCapturedIndex) {
486 long actualIndex = context.getSnapshotManager().trimLog(snapshotCapturedIndex, this);
488 if(actualIndex != -1){
489 setReplicatedToAllIndex(actualIndex);
493 protected String getId(){
494 return context.getId();
497 public void applyServerConfiguration(ServerConfigurationPayload serverConfig) {
498 Set<String> currentPeers = new HashSet<>(context.getPeerIds());
499 for(String peerId: serverConfig.getNewServerConfig()) {
500 if(!getId().equals(peerId)) {
501 if(!currentPeers.contains(peerId)) {
502 context.addToPeers(peerId, null, VotingState.VOTING);
504 currentPeers.remove(peerId);
509 for(String peerIdToRemove: currentPeers) {
510 context.removePeer(peerIdToRemove);