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;
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.event.Logging;
14 import akka.event.LoggingAdapter;
15 import akka.japi.Procedure;
16 import akka.persistence.RecoveryCompleted;
17 import akka.persistence.SaveSnapshotFailure;
18 import akka.persistence.SaveSnapshotSuccess;
19 import akka.persistence.SnapshotOffer;
20 import akka.persistence.SnapshotSelectionCriteria;
21 import akka.persistence.UntypedPersistentActor;
22 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
24 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
25 import com.google.common.base.Optional;
26 import org.opendaylight.controller.cluster.raft.behaviors.Candidate;
27 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
28 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
29 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
30 import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
31 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
32 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
33 import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
34 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
36 import java.io.Serializable;
37 import java.util.List;
41 * RaftActor encapsulates a state machine that needs to be kept synchronized
42 * in a cluster. It implements the RAFT algorithm as described in the paper
43 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
44 * In Search of an Understandable Consensus Algorithm</a>
46 * RaftActor has 3 states and each state has a certain behavior associated
47 * with it. A Raft actor can behave as,
50 * <li> A Follower (or) </li>
51 * <li> A Candidate </li>
55 * A RaftActor MUST be a Leader in order to accept requests from clients to
56 * change the state of it's encapsulated state machine. Once a RaftActor becomes
57 * a Leader it is also responsible for ensuring that all followers ultimately
58 * have the same log and therefore the same state machine as itself.
61 * The current behavior of a RaftActor determines how election for leadership
62 * is initiated and how peer RaftActors react to request for votes.
65 * Each RaftActor also needs to know the current election term. It uses this
66 * information for a couple of things. One is to simply figure out who it
67 * voted for in the last election. Another is to figure out if the message
68 * it received to update it's state is stale.
71 * The RaftActor uses akka-persistence to store it's replicated log.
72 * Furthermore through it's behaviors a Raft Actor determines
75 * <li> when a log entry should be persisted </li>
76 * <li> when a log entry should be applied to the state machine (and) </li>
77 * <li> when a snapshot should be saved </li>
80 public abstract class RaftActor extends UntypedPersistentActor {
81 protected final LoggingAdapter LOG =
82 Logging.getLogger(getContext().system(), this);
85 * The current state determines the current behavior of a RaftActor
86 * A Raft Actor always starts off in the Follower State
88 private RaftActorBehavior currentBehavior;
91 * This context should NOT be passed directly to any other actor it is
92 * only to be consumed by the RaftActorBehaviors
94 private RaftActorContext context;
97 * The in-memory journal
99 private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
102 public RaftActor(String id, Map<String, String> peerAddresses) {
103 this(id, peerAddresses, Optional.<ConfigParams>absent());
106 public RaftActor(String id, Map<String, String> peerAddresses,
107 Optional<ConfigParams> configParams) {
109 context = new RaftActorContextImpl(this.getSelf(),
110 this.getContext(), id, new ElectionTermImpl(),
111 -1, -1, replicatedLog, peerAddresses,
112 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
116 @Override public void onReceiveRecover(Object message) {
117 if (message instanceof SnapshotOffer) {
118 LOG.debug("SnapshotOffer called..");
119 SnapshotOffer offer = (SnapshotOffer) message;
120 Snapshot snapshot = (Snapshot) offer.snapshot();
122 // Create a replicated log with the snapshot information
123 // The replicated log can be used later on to retrieve this snapshot
124 // when we need to install it on a peer
125 replicatedLog = new ReplicatedLogImpl(snapshot);
127 context.setReplicatedLog(replicatedLog);
129 LOG.debug("Applied snapshot to replicatedLog. " +
130 "snapshotIndex={}, snapshotTerm={}, journal-size={}",
131 replicatedLog.snapshotIndex, replicatedLog.snapshotTerm,
132 replicatedLog.size());
134 // Apply the snapshot to the actors state
135 applySnapshot(snapshot.getState());
137 } else if (message instanceof ReplicatedLogEntry) {
138 replicatedLog.append((ReplicatedLogEntry) message);
139 } else if (message instanceof DeleteEntries) {
140 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
141 } else if (message instanceof UpdateElectionTerm) {
142 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor());
143 } else if (message instanceof RecoveryCompleted) {
145 "RecoveryCompleted - Switching actor to Follower - " +
146 "Last index in log:{}, snapshotIndex={}, snapshotTerm={}, " +
148 replicatedLog.lastIndex(), replicatedLog.snapshotIndex,
149 replicatedLog.snapshotTerm, replicatedLog.size());
150 currentBehavior = switchBehavior(RaftState.Follower);
155 @Override public void onReceiveCommand(Object message) {
156 if (message instanceof ApplyState){
157 ApplyState applyState = (ApplyState) message;
159 LOG.debug("Applying state for log index {} data {}",
160 applyState.getReplicatedLogEntry().getIndex(),
161 applyState.getReplicatedLogEntry().getData());
163 applyState(applyState.getClientActor(), applyState.getIdentifier(),
164 applyState.getReplicatedLogEntry().getData());
166 } else if(message instanceof ApplySnapshot ) {
167 applySnapshot(((ApplySnapshot) message).getSnapshot());
169 } else if (message instanceof FindLeader) {
171 new FindLeaderReply(getLeaderAddress()),
175 } else if (message instanceof SaveSnapshotSuccess) {
176 SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
178 // TODO: Not sure if we want to be this aggressive with trimming stuff
179 trimPersistentData(success.metadata().sequenceNr());
181 } else if (message instanceof SaveSnapshotFailure) {
183 // TODO: Handle failure in saving the snapshot
185 } else if (message instanceof AddRaftPeer){
187 // FIXME : Do not add raft peers like this.
188 // When adding a new Peer we have to ensure that the a majority of
189 // the peers know about the new Peer. Doing it this way may cause
190 // a situation where multiple Leaders may emerge
191 AddRaftPeer arp = (AddRaftPeer)message;
192 context.addToPeers(arp.getName(), arp.getAddress());
194 } else if (message instanceof RemoveRaftPeer){
196 RemoveRaftPeer rrp = (RemoveRaftPeer)message;
197 context.removePeer(rrp.getName());
202 currentBehavior.handleMessage(getSender(), message);
203 RaftActorBehavior oldBehavior = currentBehavior;
204 currentBehavior = switchBehavior(state);
205 if(oldBehavior != currentBehavior){
211 public java.util.Set<String> getPeers() {
212 return context.getPeerAddresses().keySet();
215 protected String getReplicatedLogState() {
216 return "snapshotIndex=" + context.getReplicatedLog().getSnapshotIndex()
217 + ", snapshotTerm=" + context.getReplicatedLog().getSnapshotTerm()
218 + ", im-mem journal size=" + context.getReplicatedLog().size();
223 * When a derived RaftActor needs to persist something it must call
230 protected void persistData(ActorRef clientActor, String identifier,
233 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
234 context.getReplicatedLog().lastIndex() + 1,
235 context.getTermInformation().getCurrentTerm(), data);
237 LOG.debug("Persist data {}", replicatedLogEntry);
240 .appendAndPersist(clientActor, identifier, replicatedLogEntry);
243 protected String getId() {
244 return context.getId();
248 * Derived actors can call the isLeader method to check if the current
249 * RaftActor is the Leader or not
251 * @return true it this RaftActor is a Leader false otherwise
253 protected boolean isLeader() {
254 return context.getId().equals(currentBehavior.getLeaderId());
258 * Derived actor can call getLeader if they need a reference to the Leader.
259 * This would be useful for example in forwarding a request to an actor
260 * which is the leader
262 * @return A reference to the leader if known, null otherwise
264 protected ActorSelection getLeader(){
265 String leaderAddress = getLeaderAddress();
267 if(leaderAddress == null){
271 return context.actorSelection(leaderAddress);
276 * @return the current leader's id
278 protected String getLeaderId(){
279 return currentBehavior.getLeaderId();
282 protected RaftState getRaftState() {
283 return currentBehavior.state();
286 protected ReplicatedLogEntry getLastLogEntry() {
287 return replicatedLog.last();
290 protected Long getCurrentTerm(){
291 return context.getTermInformation().getCurrentTerm();
294 protected Long getCommitIndex(){
295 return context.getCommitIndex();
298 protected Long getLastApplied(){
299 return context.getLastApplied();
303 * setPeerAddress sets the address of a known peer at a later time.
305 * This is to account for situations where a we know that a peer
306 * exists but we do not know an address up-front. This may also be used in
307 * situations where a known peer starts off in a different location and we
308 * need to change it's address
310 * Note that if the peerId does not match the list of peers passed to
311 * this actor during construction an IllegalStateException will be thrown.
316 protected void setPeerAddress(String peerId, String peerAddress){
317 context.setPeerAddress(peerId, peerAddress);
323 * The applyState method will be called by the RaftActor when some data
324 * needs to be applied to the actor's state
326 * @param clientActor A reference to the client who sent this message. This
327 * is the same reference that was passed to persistData
328 * by the derived actor. clientActor may be null when
329 * the RaftActor is behaving as a follower or during
331 * @param identifier The identifier of the persisted data. This is also
332 * the same identifier that was passed to persistData by
333 * the derived actor. identifier may be null when
334 * the RaftActor is behaving as a follower or during
336 * @param data A piece of data that was persisted by the persistData call.
337 * This should NEVER be null.
339 protected abstract void applyState(ActorRef clientActor, String identifier,
343 * This method will be called by the RaftActor when a snapshot needs to be
344 * created. The derived actor should respond with its current state.
346 * During recovery the state that is returned by the derived actor will
347 * be passed back to it by calling the applySnapshot method
349 * @return The current state of the actor
351 protected abstract Object createSnapshot();
354 * This method will be called by the RaftActor during recovery to
355 * reconstruct the state of the actor.
357 * This method may also be called at any other point during normal
358 * operations when the derived actor is out of sync with it's peers
359 * and the only way to bring it in sync is by applying a snapshot
361 * @param snapshot A snapshot of the state of the actor
363 protected abstract void applySnapshot(Object snapshot);
366 * This method will be called by the RaftActor when the state of the
367 * RaftActor changes. The derived actor can then use methods like
368 * isLeader or getLeader to do something useful
370 protected abstract void onStateChanged();
372 private RaftActorBehavior switchBehavior(RaftState state) {
373 if (currentBehavior != null) {
374 if (currentBehavior.state() == state) {
375 return currentBehavior;
377 LOG.info("Switching from state " + currentBehavior.state() + " to "
381 currentBehavior.close();
382 } catch (Exception e) {
384 "Failed to close behavior : " + currentBehavior.state());
388 LOG.info("Switching behavior to " + state);
390 RaftActorBehavior behavior = null;
391 if (state == RaftState.Candidate) {
392 behavior = new Candidate(context);
393 } else if (state == RaftState.Follower) {
394 behavior = new Follower(context);
396 behavior = new Leader(context);
404 private void trimPersistentData(long sequenceNumber) {
405 // Trim akka snapshots
406 // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
407 // For now guessing that it is ANDed.
408 deleteSnapshots(new SnapshotSelectionCriteria(
409 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
412 deleteMessages(sequenceNumber);
415 private String getLeaderAddress(){
417 return getSelf().path().toString();
419 String leaderId = currentBehavior.getLeaderId();
420 if (leaderId == null) {
423 String peerAddress = context.getPeerAddress(leaderId);
424 LOG.debug("getLeaderAddress leaderId = " + leaderId + " peerAddress = "
431 private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
433 public ReplicatedLogImpl(Snapshot snapshot) {
434 super(snapshot.getState(),
435 snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
436 snapshot.getUnAppliedEntries());
439 public ReplicatedLogImpl() {
443 @Override public void removeFromAndPersist(long logEntryIndex) {
444 int adjustedIndex = adjustedIndex(logEntryIndex);
446 if (adjustedIndex < 0) {
450 // FIXME: Maybe this should be done after the command is saved
451 journal.subList(adjustedIndex , journal.size()).clear();
453 persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>(){
455 @Override public void apply(DeleteEntries param)
457 //FIXME : Doing nothing for now
462 @Override public void appendAndPersist(
463 final ReplicatedLogEntry replicatedLogEntry) {
464 appendAndPersist(null, null, replicatedLogEntry);
467 public void appendAndPersist(final ActorRef clientActor,
468 final String identifier,
469 final ReplicatedLogEntry replicatedLogEntry) {
470 context.getLogger().debug(
471 "Append log entry and persist {} ", replicatedLogEntry);
472 // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
473 journal.add(replicatedLogEntry);
475 // When persisting events with persist it is guaranteed that the
476 // persistent actor will not receive further commands between the
477 // persist call and the execution(s) of the associated event
478 // handler. This also holds for multiple persist calls in context
479 // of a single command.
480 persist(replicatedLogEntry,
481 new Procedure<ReplicatedLogEntry>() {
482 public void apply(ReplicatedLogEntry evt) throws Exception {
483 // FIXME : Tentatively create a snapshot every hundred thousand entries. To be tuned.
484 if (journal.size() > context.getConfigParams().getSnapshotBatchCount()) {
485 LOG.info("Initiating Snapshot Capture..");
486 long lastAppliedIndex = -1;
487 long lastAppliedTerm = -1;
489 ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
490 if (lastAppliedEntry != null) {
491 lastAppliedIndex = lastAppliedEntry.getIndex();
492 lastAppliedTerm = lastAppliedEntry.getTerm();
495 LOG.debug("Snapshot Capture logSize: {}", journal.size());
496 LOG.debug("Snapshot Capture lastApplied:{} ", context.getLastApplied());
497 LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex);
498 LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm);
500 // create a snapshot object from the state provided and save it
501 // when snapshot is saved async, SaveSnapshotSuccess is raised.
502 Snapshot sn = Snapshot.create(createSnapshot(),
503 getFrom(context.getLastApplied() + 1),
504 lastIndex(), lastTerm(), lastAppliedIndex,
508 LOG.info("Persisting of snapshot done:{}", sn.getLogMessage());
510 //be greedy and remove entries from in-mem journal which are in the snapshot
511 // and update snapshotIndex and snapshotTerm without waiting for the success,
512 // TODO: damage-recovery to be done on failure
513 journal.subList(0, (int) (lastAppliedIndex - snapshotIndex)).clear();
514 snapshotIndex = lastAppliedIndex;
515 snapshotTerm = lastAppliedTerm;
517 LOG.info("Removed in-memory snapshotted entries, " +
518 "adjusted snaphsotIndex:{}" +
519 "and term:{}", snapshotIndex, lastAppliedTerm);
521 // Send message for replication
522 if (clientActor != null) {
523 currentBehavior.handleMessage(getSelf(),
524 new Replicate(clientActor, identifier,
535 private static class DeleteEntries implements Serializable {
536 private final int fromIndex;
539 public DeleteEntries(int fromIndex) {
540 this.fromIndex = fromIndex;
543 public int getFromIndex() {
549 private static class Snapshot implements Serializable {
550 private final Object state;
551 private final List<ReplicatedLogEntry> unAppliedEntries;
552 private final long lastIndex;
553 private final long lastTerm;
554 private final long lastAppliedIndex;
555 private final long lastAppliedTerm;
557 private Snapshot(Object state,
558 List<ReplicatedLogEntry> unAppliedEntries, long lastIndex,
559 long lastTerm, long lastAppliedIndex, long lastAppliedTerm) {
561 this.unAppliedEntries = unAppliedEntries;
562 this.lastIndex = lastIndex;
563 this.lastTerm = lastTerm;
564 this.lastAppliedIndex = lastAppliedIndex;
565 this.lastAppliedTerm = lastAppliedTerm;
569 public static Snapshot create(Object state,
570 List<ReplicatedLogEntry> entries, long lastIndex, long lastTerm,
571 long lastAppliedIndex, long lastAppliedTerm) {
572 return new Snapshot(state, entries, lastIndex, lastTerm,
573 lastAppliedIndex, lastAppliedTerm);
576 public Object getState() {
580 public List<ReplicatedLogEntry> getUnAppliedEntries() {
581 return unAppliedEntries;
584 public long getLastTerm() {
588 public long getLastAppliedIndex() {
589 return lastAppliedIndex;
592 public long getLastAppliedTerm() {
593 return lastAppliedTerm;
596 public String getLogMessage() {
597 StringBuilder sb = new StringBuilder();
598 return sb.append("Snapshot={")
599 .append("lastTerm:" + this.getLastTerm() + ", ")
600 .append("LastAppliedIndex:" + this.getLastAppliedIndex() + ", ")
601 .append("LastAppliedTerm:" + this.getLastAppliedTerm() + ", ")
602 .append("UnAppliedEntries size:" + this.getUnAppliedEntries().size() + "}")
608 private class ElectionTermImpl implements ElectionTerm {
610 * Identifier of the actor whose election term information this is
612 private long currentTerm = 0;
613 private String votedFor = null;
615 public long getCurrentTerm() {
619 public String getVotedFor() {
623 @Override public void update(long currentTerm, String votedFor) {
624 LOG.debug("Set currentTerm={}, votedFor={}", currentTerm, votedFor);
626 this.currentTerm = currentTerm;
627 this.votedFor = votedFor;
631 public void updateAndPersist(long currentTerm, String votedFor){
632 update(currentTerm, votedFor);
633 // FIXME : Maybe first persist then update the state
634 persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
636 @Override public void apply(UpdateElectionTerm param)
644 private static class UpdateElectionTerm implements Serializable {
645 private final long currentTerm;
646 private final String votedFor;
648 public UpdateElectionTerm(long currentTerm, String votedFor) {
649 this.currentTerm = currentTerm;
650 this.votedFor = votedFor;
653 public long getCurrentTerm() {
657 public String getVotedFor() {