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 com.google.common.base.Optional;
23 import com.google.protobuf.ByteString;
24 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
25 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
26 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
27 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
28 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
29 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
30 import org.opendaylight.controller.cluster.raft.behaviors.Candidate;
31 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
32 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
33 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
34 import org.opendaylight.controller.cluster.raft.client.messages.AddRaftPeer;
35 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
36 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
37 import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
38 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
39 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
40 import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
42 import java.io.Serializable;
46 * RaftActor encapsulates a state machine that needs to be kept synchronized
47 * in a cluster. It implements the RAFT algorithm as described in the paper
48 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
49 * In Search of an Understandable Consensus Algorithm</a>
51 * RaftActor has 3 states and each state has a certain behavior associated
52 * with it. A Raft actor can behave as,
55 * <li> A Follower (or) </li>
56 * <li> A Candidate </li>
60 * A RaftActor MUST be a Leader in order to accept requests from clients to
61 * change the state of it's encapsulated state machine. Once a RaftActor becomes
62 * a Leader it is also responsible for ensuring that all followers ultimately
63 * have the same log and therefore the same state machine as itself.
66 * The current behavior of a RaftActor determines how election for leadership
67 * is initiated and how peer RaftActors react to request for votes.
70 * Each RaftActor also needs to know the current election term. It uses this
71 * information for a couple of things. One is to simply figure out who it
72 * voted for in the last election. Another is to figure out if the message
73 * it received to update it's state is stale.
76 * The RaftActor uses akka-persistence to store it's replicated log.
77 * Furthermore through it's behaviors a Raft Actor determines
80 * <li> when a log entry should be persisted </li>
81 * <li> when a log entry should be applied to the state machine (and) </li>
82 * <li> when a snapshot should be saved </li>
85 public abstract class RaftActor extends UntypedPersistentActor {
86 protected final LoggingAdapter LOG =
87 Logging.getLogger(getContext().system(), this);
90 * The current state determines the current behavior of a RaftActor
91 * A Raft Actor always starts off in the Follower State
93 private RaftActorBehavior currentBehavior;
96 * This context should NOT be passed directly to any other actor it is
97 * only to be consumed by the RaftActorBehaviors
99 private RaftActorContext context;
102 * The in-memory journal
104 private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
106 private CaptureSnapshot captureSnapshot = null;
108 private volatile boolean hasSnapshotCaptureInitiated = false;
110 public RaftActor(String id, Map<String, String> peerAddresses) {
111 this(id, peerAddresses, Optional.<ConfigParams>absent());
114 public RaftActor(String id, Map<String, String> peerAddresses,
115 Optional<ConfigParams> configParams) {
117 context = new RaftActorContextImpl(this.getSelf(),
118 this.getContext(), id, new ElectionTermImpl(),
119 -1, -1, replicatedLog, peerAddresses,
120 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
124 @Override public void onReceiveRecover(Object message) {
125 if (message instanceof SnapshotOffer) {
126 LOG.debug("SnapshotOffer called..");
127 SnapshotOffer offer = (SnapshotOffer) message;
128 Snapshot snapshot = (Snapshot) offer.snapshot();
130 // Create a replicated log with the snapshot information
131 // The replicated log can be used later on to retrieve this snapshot
132 // when we need to install it on a peer
133 replicatedLog = new ReplicatedLogImpl(snapshot);
135 context.setReplicatedLog(replicatedLog);
136 context.setLastApplied(snapshot.getLastAppliedIndex());
138 LOG.debug("Applied snapshot to replicatedLog. " +
139 "snapshotIndex={}, snapshotTerm={}, journal-size={}",
140 replicatedLog.snapshotIndex, replicatedLog.snapshotTerm,
141 replicatedLog.size());
143 // Apply the snapshot to the actors state
144 applySnapshot(ByteString.copyFrom(snapshot.getState()));
146 } else if (message instanceof ReplicatedLogEntry) {
147 ReplicatedLogEntry logEntry = (ReplicatedLogEntry) message;
149 // Apply State immediately
150 replicatedLog.append(logEntry);
151 applyState(null, "recovery", logEntry.getData());
152 context.setLastApplied(logEntry.getIndex());
153 context.setCommitIndex(logEntry.getIndex());
154 } else if (message instanceof DeleteEntries) {
155 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
156 } else if (message instanceof UpdateElectionTerm) {
157 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor());
158 } else if (message instanceof RecoveryCompleted) {
160 "RecoveryCompleted - Switching actor to Follower - " +
161 "Persistence Id = " + persistenceId() +
162 " Last index in log:{}, snapshotIndex={}, snapshotTerm={}, " +
164 replicatedLog.lastIndex(), replicatedLog.snapshotIndex,
165 replicatedLog.snapshotTerm, replicatedLog.size());
166 currentBehavior = switchBehavior(RaftState.Follower);
171 @Override public void onReceiveCommand(Object message) {
172 if (message instanceof ApplyState){
173 ApplyState applyState = (ApplyState) message;
175 LOG.debug("Applying state for log index {} data {}",
176 applyState.getReplicatedLogEntry().getIndex(),
177 applyState.getReplicatedLogEntry().getData());
179 applyState(applyState.getClientActor(), applyState.getIdentifier(),
180 applyState.getReplicatedLogEntry().getData());
182 } else if(message instanceof ApplySnapshot ) {
183 Snapshot snapshot = ((ApplySnapshot) message).getSnapshot();
185 LOG.debug("ApplySnapshot called on Follower Actor " +
186 "snapshotIndex:{}, snapshotTerm:{}", snapshot.getLastAppliedIndex(),
187 snapshot.getLastAppliedTerm());
188 applySnapshot(ByteString.copyFrom(snapshot.getState()));
190 //clears the followers log, sets the snapshot index to ensure adjusted-index works
191 replicatedLog = new ReplicatedLogImpl(snapshot);
192 context.setReplicatedLog(replicatedLog);
193 context.setLastApplied(snapshot.getLastAppliedIndex());
195 } else if (message instanceof FindLeader) {
197 new FindLeaderReply(getLeaderAddress()),
201 } else if (message instanceof SaveSnapshotSuccess) {
202 SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
203 LOG.info("SaveSnapshotSuccess received for snapshot");
205 context.getReplicatedLog().snapshotCommit();
207 // TODO: Not sure if we want to be this aggressive with trimming stuff
208 trimPersistentData(success.metadata().sequenceNr());
210 } else if (message instanceof SaveSnapshotFailure) {
211 SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message;
213 LOG.info("saveSnapshotFailure.metadata():{}", saveSnapshotFailure.metadata().toString());
214 LOG.error(saveSnapshotFailure.cause(), "SaveSnapshotFailure received for snapshot Cause:");
216 context.getReplicatedLog().snapshotRollback();
218 LOG.info("Replicated Log rollbacked. Snapshot will be attempted in the next cycle." +
219 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}",
220 context.getReplicatedLog().getSnapshotIndex(),
221 context.getReplicatedLog().getSnapshotTerm(),
222 context.getReplicatedLog().size());
224 } else if (message instanceof AddRaftPeer){
226 // FIXME : Do not add raft peers like this.
227 // When adding a new Peer we have to ensure that the a majority of
228 // the peers know about the new Peer. Doing it this way may cause
229 // a situation where multiple Leaders may emerge
230 AddRaftPeer arp = (AddRaftPeer)message;
231 context.addToPeers(arp.getName(), arp.getAddress());
233 } else if (message instanceof RemoveRaftPeer){
235 RemoveRaftPeer rrp = (RemoveRaftPeer)message;
236 context.removePeer(rrp.getName());
238 } else if (message instanceof CaptureSnapshot) {
239 LOG.debug("CaptureSnapshot received by actor");
240 CaptureSnapshot cs = (CaptureSnapshot)message;
241 captureSnapshot = cs;
244 } else if (message instanceof CaptureSnapshotReply){
245 LOG.debug("CaptureSnapshotReply received by actor");
246 CaptureSnapshotReply csr = (CaptureSnapshotReply) message;
248 ByteString stateInBytes = csr.getSnapshot();
249 LOG.debug("CaptureSnapshotReply stateInBytes size:{}", stateInBytes.size());
250 handleCaptureSnapshotReply(stateInBytes);
253 if (!(message instanceof AppendEntriesMessages.AppendEntries)
254 && !(message instanceof AppendEntriesReply) && !(message instanceof SendHeartBeat)) {
255 LOG.debug("onReceiveCommand: message:" + message.getClass());
259 currentBehavior.handleMessage(getSender(), message);
260 RaftActorBehavior oldBehavior = currentBehavior;
261 currentBehavior = switchBehavior(state);
262 if(oldBehavior != currentBehavior){
266 onLeaderChanged(oldBehavior.getLeaderId(), currentBehavior.getLeaderId());
270 public java.util.Set<String> getPeers() {
271 return context.getPeerAddresses().keySet();
274 protected String getReplicatedLogState() {
275 return "snapshotIndex=" + context.getReplicatedLog().getSnapshotIndex()
276 + ", snapshotTerm=" + context.getReplicatedLog().getSnapshotTerm()
277 + ", im-mem journal size=" + context.getReplicatedLog().size();
282 * When a derived RaftActor needs to persist something it must call
289 protected void persistData(ActorRef clientActor, String identifier,
292 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
293 context.getReplicatedLog().lastIndex() + 1,
294 context.getTermInformation().getCurrentTerm(), data);
296 LOG.debug("Persist data {}", replicatedLogEntry);
299 .appendAndPersist(clientActor, identifier, replicatedLogEntry);
302 protected String getId() {
303 return context.getId();
307 * Derived actors can call the isLeader method to check if the current
308 * RaftActor is the Leader or not
310 * @return true it this RaftActor is a Leader false otherwise
312 protected boolean isLeader() {
313 return context.getId().equals(currentBehavior.getLeaderId());
317 * Derived actor can call getLeader if they need a reference to the Leader.
318 * This would be useful for example in forwarding a request to an actor
319 * which is the leader
321 * @return A reference to the leader if known, null otherwise
323 protected ActorSelection getLeader(){
324 String leaderAddress = getLeaderAddress();
326 if(leaderAddress == null){
330 return context.actorSelection(leaderAddress);
335 * @return the current leader's id
337 protected String getLeaderId(){
338 return currentBehavior.getLeaderId();
341 protected RaftState getRaftState() {
342 return currentBehavior.state();
345 protected ReplicatedLogEntry getLastLogEntry() {
346 return replicatedLog.last();
349 protected Long getCurrentTerm(){
350 return context.getTermInformation().getCurrentTerm();
353 protected Long getCommitIndex(){
354 return context.getCommitIndex();
357 protected Long getLastApplied(){
358 return context.getLastApplied();
362 * setPeerAddress sets the address of a known peer at a later time.
364 * This is to account for situations where a we know that a peer
365 * exists but we do not know an address up-front. This may also be used in
366 * situations where a known peer starts off in a different location and we
367 * need to change it's address
369 * Note that if the peerId does not match the list of peers passed to
370 * this actor during construction an IllegalStateException will be thrown.
375 protected void setPeerAddress(String peerId, String peerAddress){
376 context.setPeerAddress(peerId, peerAddress);
382 * The applyState method will be called by the RaftActor when some data
383 * needs to be applied to the actor's state
385 * @param clientActor A reference to the client who sent this message. This
386 * is the same reference that was passed to persistData
387 * by the derived actor. clientActor may be null when
388 * the RaftActor is behaving as a follower or during
390 * @param identifier The identifier of the persisted data. This is also
391 * the same identifier that was passed to persistData by
392 * the derived actor. identifier may be null when
393 * the RaftActor is behaving as a follower or during
395 * @param data A piece of data that was persisted by the persistData call.
396 * This should NEVER be null.
398 protected abstract void applyState(ActorRef clientActor, String identifier,
402 * This method will be called by the RaftActor when a snapshot needs to be
403 * created. The derived actor should respond with its current state.
405 * During recovery the state that is returned by the derived actor will
406 * be passed back to it by calling the applySnapshot method
408 * @return The current state of the actor
410 protected abstract void createSnapshot();
413 * This method will be called by the RaftActor during recovery to
414 * reconstruct the state of the actor.
416 * This method may also be called at any other point during normal
417 * operations when the derived actor is out of sync with it's peers
418 * and the only way to bring it in sync is by applying a snapshot
420 * @param snapshot A snapshot of the state of the actor
422 protected abstract void applySnapshot(ByteString snapshot);
425 * This method will be called by the RaftActor when the state of the
426 * RaftActor changes. The derived actor can then use methods like
427 * isLeader or getLeader to do something useful
429 protected abstract void onStateChanged();
431 protected void onLeaderChanged(String oldLeader, String newLeader){};
433 private RaftActorBehavior switchBehavior(RaftState state) {
434 if (currentBehavior != null) {
435 if (currentBehavior.state() == state) {
436 return currentBehavior;
438 LOG.info("Switching from state " + currentBehavior.state() + " to "
442 currentBehavior.close();
443 } catch (Exception e) {
445 "Failed to close behavior : " + currentBehavior.state());
449 LOG.info("Switching behavior to " + state);
451 RaftActorBehavior behavior = null;
452 if (state == RaftState.Candidate) {
453 behavior = new Candidate(context);
454 } else if (state == RaftState.Follower) {
455 behavior = new Follower(context);
457 behavior = new Leader(context);
465 private void trimPersistentData(long sequenceNumber) {
466 // Trim akka snapshots
467 // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
468 // For now guessing that it is ANDed.
469 deleteSnapshots(new SnapshotSelectionCriteria(
470 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
473 deleteMessages(sequenceNumber);
476 private String getLeaderAddress(){
478 return getSelf().path().toString();
480 String leaderId = currentBehavior.getLeaderId();
481 if (leaderId == null) {
484 String peerAddress = context.getPeerAddress(leaderId);
485 LOG.debug("getLeaderAddress leaderId = " + leaderId + " peerAddress = "
491 private void handleCaptureSnapshotReply(ByteString stateInBytes) {
492 // create a snapshot object from the state provided and save it
493 // when snapshot is saved async, SaveSnapshotSuccess is raised.
495 Snapshot sn = Snapshot.create(stateInBytes.toByteArray(),
496 context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1),
497 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
498 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
502 LOG.info("Persisting of snapshot done:{}", sn.getLogMessage());
504 //be greedy and remove entries from in-mem journal which are in the snapshot
505 // and update snapshotIndex and snapshotTerm without waiting for the success,
507 context.getReplicatedLog().snapshotPreCommit(stateInBytes,
508 captureSnapshot.getLastAppliedIndex(),
509 captureSnapshot.getLastAppliedTerm());
511 LOG.info("Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
512 "and term:{}", captureSnapshot.getLastAppliedIndex(),
513 captureSnapshot.getLastAppliedTerm());
515 captureSnapshot = null;
516 hasSnapshotCaptureInitiated = false;
520 private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
522 public ReplicatedLogImpl(Snapshot snapshot) {
523 super(ByteString.copyFrom(snapshot.getState()),
524 snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
525 snapshot.getUnAppliedEntries());
528 public ReplicatedLogImpl() {
532 @Override public void removeFromAndPersist(long logEntryIndex) {
533 int adjustedIndex = adjustedIndex(logEntryIndex);
535 if (adjustedIndex < 0) {
539 // FIXME: Maybe this should be done after the command is saved
540 journal.subList(adjustedIndex , journal.size()).clear();
542 persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>(){
544 @Override public void apply(DeleteEntries param)
546 //FIXME : Doing nothing for now
551 @Override public void appendAndPersist(
552 final ReplicatedLogEntry replicatedLogEntry) {
553 appendAndPersist(null, null, replicatedLogEntry);
556 public void appendAndPersist(final ActorRef clientActor,
557 final String identifier,
558 final ReplicatedLogEntry replicatedLogEntry) {
559 context.getLogger().debug(
560 "Append log entry and persist {} ", replicatedLogEntry);
561 // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
562 journal.add(replicatedLogEntry);
564 // When persisting events with persist it is guaranteed that the
565 // persistent actor will not receive further commands between the
566 // persist call and the execution(s) of the associated event
567 // handler. This also holds for multiple persist calls in context
568 // of a single command.
569 persist(replicatedLogEntry,
570 new Procedure<ReplicatedLogEntry>() {
571 public void apply(ReplicatedLogEntry evt) throws Exception {
572 // when a snaphsot is being taken, captureSnapshot != null
573 if (hasSnapshotCaptureInitiated == false &&
574 journal.size() % context.getConfigParams().getSnapshotBatchCount() == 0) {
576 LOG.info("Initiating Snapshot Capture..");
577 long lastAppliedIndex = -1;
578 long lastAppliedTerm = -1;
580 ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
581 if (lastAppliedEntry != null) {
582 lastAppliedIndex = lastAppliedEntry.getIndex();
583 lastAppliedTerm = lastAppliedEntry.getTerm();
586 LOG.debug("Snapshot Capture logSize: {}", journal.size());
587 LOG.debug("Snapshot Capture lastApplied:{} ", context.getLastApplied());
588 LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex);
589 LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm);
591 // send a CaptureSnapshot to self to make the expensive operation async.
592 getSelf().tell(new CaptureSnapshot(
593 lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm),
595 hasSnapshotCaptureInitiated = true;
597 // Send message for replication
598 if (clientActor != null) {
599 currentBehavior.handleMessage(getSelf(),
600 new Replicate(clientActor, identifier,
611 private static class DeleteEntries implements Serializable {
612 private final int fromIndex;
615 public DeleteEntries(int fromIndex) {
616 this.fromIndex = fromIndex;
619 public int getFromIndex() {
625 private class ElectionTermImpl implements ElectionTerm {
627 * Identifier of the actor whose election term information this is
629 private long currentTerm = 0;
630 private String votedFor = null;
632 public long getCurrentTerm() {
636 public String getVotedFor() {
640 @Override public void update(long currentTerm, String votedFor) {
641 LOG.debug("Set currentTerm={}, votedFor={}", currentTerm, votedFor);
643 this.currentTerm = currentTerm;
644 this.votedFor = votedFor;
648 public void updateAndPersist(long currentTerm, String votedFor){
649 update(currentTerm, votedFor);
650 // FIXME : Maybe first persist then update the state
651 persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
653 @Override public void apply(UpdateElectionTerm param)
661 private static class UpdateElectionTerm implements Serializable {
662 private final long currentTerm;
663 private final String votedFor;
665 public UpdateElectionTerm(long currentTerm, String votedFor) {
666 this.currentTerm = currentTerm;
667 this.votedFor = votedFor;
670 public long getCurrentTerm() {
674 public String getVotedFor() {