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 com.google.common.annotations.VisibleForTesting;
22 import com.google.common.base.Optional;
23 import com.google.common.base.Stopwatch;
24 import com.google.protobuf.ByteString;
25 import java.io.Serializable;
27 import org.opendaylight.controller.cluster.DataPersistenceProvider;
28 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
29 import org.opendaylight.controller.cluster.notifications.RoleChanged;
30 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
31 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
32 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
33 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
34 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
35 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
36 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
37 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
38 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
39 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
40 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
41 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
42 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
43 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
44 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
45 import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
48 * RaftActor encapsulates a state machine that needs to be kept synchronized
49 * in a cluster. It implements the RAFT algorithm as described in the paper
50 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
51 * In Search of an Understandable Consensus Algorithm</a>
53 * RaftActor has 3 states and each state has a certain behavior associated
54 * with it. A Raft actor can behave as,
57 * <li> A Follower (or) </li>
58 * <li> A Candidate </li>
62 * A RaftActor MUST be a Leader in order to accept requests from clients to
63 * change the state of it's encapsulated state machine. Once a RaftActor becomes
64 * a Leader it is also responsible for ensuring that all followers ultimately
65 * have the same log and therefore the same state machine as itself.
68 * The current behavior of a RaftActor determines how election for leadership
69 * is initiated and how peer RaftActors react to request for votes.
72 * Each RaftActor also needs to know the current election term. It uses this
73 * information for a couple of things. One is to simply figure out who it
74 * voted for in the last election. Another is to figure out if the message
75 * it received to update it's state is stale.
78 * The RaftActor uses akka-persistence to store it's replicated log.
79 * Furthermore through it's behaviors a Raft Actor determines
82 * <li> when a log entry should be persisted </li>
83 * <li> when a log entry should be applied to the state machine (and) </li>
84 * <li> when a snapshot should be saved </li>
87 public abstract class RaftActor extends AbstractUntypedPersistentActor {
88 protected final LoggingAdapter LOG =
89 Logging.getLogger(getContext().system(), this);
92 * The current state determines the current behavior of a RaftActor
93 * A Raft Actor always starts off in the Follower State
95 private RaftActorBehavior currentBehavior;
98 * This context should NOT be passed directly to any other actor it is
99 * only to be consumed by the RaftActorBehaviors
101 private final RaftActorContext context;
104 * The in-memory journal
106 private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
108 private CaptureSnapshot captureSnapshot = null;
110 private Stopwatch recoveryTimer;
112 private int currentRecoveryBatchCount;
114 public RaftActor(String id, Map<String, String> peerAddresses) {
115 this(id, peerAddresses, Optional.<ConfigParams>absent());
118 public RaftActor(String id, Map<String, String> peerAddresses,
119 Optional<ConfigParams> configParams) {
121 context = new RaftActorContextImpl(this.getSelf(),
122 this.getContext(), id, new ElectionTermImpl(),
123 -1, -1, replicatedLog, peerAddresses,
124 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
128 private void initRecoveryTimer() {
129 if(recoveryTimer == null) {
130 recoveryTimer = new Stopwatch();
131 recoveryTimer.start();
136 public void preStart() throws Exception {
137 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
138 context.getConfigParams().getJournalRecoveryLogBatchSize());
144 public void handleRecover(Object message) {
145 if(persistence().isRecoveryApplicable()) {
146 if (message instanceof SnapshotOffer) {
147 onRecoveredSnapshot((SnapshotOffer) message);
148 } else if (message instanceof ReplicatedLogEntry) {
149 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
150 } else if (message instanceof ApplyLogEntries) {
151 onRecoveredApplyLogEntries((ApplyLogEntries) message);
152 } else if (message instanceof DeleteEntries) {
153 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
154 } else if (message instanceof UpdateElectionTerm) {
155 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
156 ((UpdateElectionTerm) message).getVotedFor());
157 } else if (message instanceof RecoveryCompleted) {
158 onRecoveryCompletedMessage();
161 if (message instanceof RecoveryCompleted) {
162 // Delete all the messages from the akka journal so that we do not end up with consistency issues
163 // Note I am not using the dataPersistenceProvider and directly using the akka api here
164 deleteMessages(lastSequenceNr());
166 // Delete all the akka snapshots as they will not be needed
167 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
169 onRecoveryComplete();
171 initializeBehavior();
176 private void onRecoveredSnapshot(SnapshotOffer offer) {
177 if(LOG.isDebugEnabled()) {
178 LOG.debug("{}: SnapshotOffer called..", persistenceId());
183 Snapshot snapshot = (Snapshot) offer.snapshot();
185 // Create a replicated log with the snapshot information
186 // The replicated log can be used later on to retrieve this snapshot
187 // when we need to install it on a peer
188 replicatedLog = new ReplicatedLogImpl(snapshot);
190 context.setReplicatedLog(replicatedLog);
191 context.setLastApplied(snapshot.getLastAppliedIndex());
192 context.setCommitIndex(snapshot.getLastAppliedIndex());
194 Stopwatch timer = new Stopwatch();
197 // Apply the snapshot to the actors state
198 applyRecoverySnapshot(snapshot.getState());
201 LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" +
202 replicatedLog.size(), persistenceId(), timer.toString(),
203 replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm());
206 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
207 if(LOG.isDebugEnabled()) {
208 LOG.debug("{}: Received ReplicatedLogEntry for recovery: {}", persistenceId(), logEntry.getIndex());
211 replicatedLog.append(logEntry);
214 private void onRecoveredApplyLogEntries(ApplyLogEntries ale) {
215 if(LOG.isDebugEnabled()) {
216 LOG.debug("{}: Received ApplyLogEntries for recovery, applying to state: {} to {}",
217 persistenceId(), context.getLastApplied() + 1, ale.getToIndex());
220 for (long i = context.getLastApplied() + 1; i <= ale.getToIndex(); i++) {
221 batchRecoveredLogEntry(replicatedLog.get(i));
224 context.setLastApplied(ale.getToIndex());
225 context.setCommitIndex(ale.getToIndex());
228 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
231 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
232 if(currentRecoveryBatchCount == 0) {
233 startLogRecoveryBatch(batchSize);
236 appendRecoveredLogEntry(logEntry.getData());
238 if(++currentRecoveryBatchCount >= batchSize) {
239 endCurrentLogRecoveryBatch();
243 private void endCurrentLogRecoveryBatch() {
244 applyCurrentLogRecoveryBatch();
245 currentRecoveryBatchCount = 0;
248 private void onRecoveryCompletedMessage() {
249 if(currentRecoveryBatchCount > 0) {
250 endCurrentLogRecoveryBatch();
253 onRecoveryComplete();
255 String recoveryTime = "";
256 if(recoveryTimer != null) {
257 recoveryTimer.stop();
258 recoveryTime = " in " + recoveryTimer.toString();
259 recoveryTimer = null;
263 "Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
264 "Persistence Id = " + persistenceId() +
265 " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " +
267 replicatedLog.lastIndex(), replicatedLog.getSnapshotIndex(),
268 replicatedLog.getSnapshotTerm(), replicatedLog.size());
270 initializeBehavior();
273 protected void initializeBehavior(){
274 changeCurrentBehavior(new Follower(context));
277 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
278 RaftActorBehavior oldBehavior = currentBehavior;
279 currentBehavior = newBehavior;
280 handleBehaviorChange(oldBehavior, currentBehavior);
283 @Override public void handleCommand(Object message) {
284 if (message instanceof ApplyState){
285 ApplyState applyState = (ApplyState) message;
287 if(LOG.isDebugEnabled()) {
288 LOG.debug("{}: Applying state for log index {} data {}",
289 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
290 applyState.getReplicatedLogEntry().getData());
293 applyState(applyState.getClientActor(), applyState.getIdentifier(),
294 applyState.getReplicatedLogEntry().getData());
296 } else if (message instanceof ApplyLogEntries){
297 ApplyLogEntries ale = (ApplyLogEntries) message;
298 if(LOG.isDebugEnabled()) {
299 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), ale.getToIndex());
301 persistence().persist(new ApplyLogEntries(ale.getToIndex()), new Procedure<ApplyLogEntries>() {
303 public void apply(ApplyLogEntries param) throws Exception {
307 } else if(message instanceof ApplySnapshot ) {
308 Snapshot snapshot = ((ApplySnapshot) message).getSnapshot();
310 if(LOG.isDebugEnabled()) {
311 LOG.debug("{}: ApplySnapshot called on Follower Actor " +
312 "snapshotIndex:{}, snapshotTerm:{}", persistenceId(), snapshot.getLastAppliedIndex(),
313 snapshot.getLastAppliedTerm()
317 applySnapshot(snapshot.getState());
319 //clears the followers log, sets the snapshot index to ensure adjusted-index works
320 replicatedLog = new ReplicatedLogImpl(snapshot);
321 context.setReplicatedLog(replicatedLog);
322 context.setLastApplied(snapshot.getLastAppliedIndex());
324 } else if (message instanceof FindLeader) {
326 new FindLeaderReply(getLeaderAddress()),
330 } else if (message instanceof SaveSnapshotSuccess) {
331 SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
332 LOG.info("{}: SaveSnapshotSuccess received for snapshot", persistenceId());
334 long sequenceNumber = success.metadata().sequenceNr();
336 commitSnapshot(sequenceNumber);
338 } else if (message instanceof SaveSnapshotFailure) {
339 SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message;
341 LOG.error(saveSnapshotFailure.cause(), "{}: SaveSnapshotFailure received for snapshot Cause:",
344 context.getReplicatedLog().snapshotRollback();
346 LOG.info("{}: Replicated Log rollbacked. Snapshot will be attempted in the next cycle." +
347 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
348 context.getReplicatedLog().getSnapshotIndex(),
349 context.getReplicatedLog().getSnapshotTerm(),
350 context.getReplicatedLog().size());
352 } else if (message instanceof CaptureSnapshot) {
353 LOG.info("{}: CaptureSnapshot received by actor", persistenceId());
355 if(captureSnapshot == null) {
356 captureSnapshot = (CaptureSnapshot)message;
360 } else if (message instanceof CaptureSnapshotReply){
361 handleCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot());
364 if (!(message instanceof AppendEntriesMessages.AppendEntries)
365 && !(message instanceof AppendEntriesReply) && !(message instanceof SendHeartBeat)) {
366 if(LOG.isDebugEnabled()) {
367 LOG.debug("{}: onReceiveCommand: message: {}", persistenceId(), message.getClass());
371 RaftActorBehavior oldBehavior = currentBehavior;
372 currentBehavior = currentBehavior.handleMessage(getSender(), message);
374 handleBehaviorChange(oldBehavior, currentBehavior);
378 private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) {
379 if (oldBehavior != currentBehavior){
383 String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId();
384 String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name();
386 // it can happen that the state has not changed but the leader has changed.
387 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
389 if (getRoleChangeNotifier().isPresent() &&
390 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
391 getRoleChangeNotifier().get().tell(
392 new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()),
398 * When a derived RaftActor needs to persist something it must call
405 protected void persistData(final ActorRef clientActor, final String identifier,
406 final Payload data) {
408 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
409 context.getReplicatedLog().lastIndex() + 1,
410 context.getTermInformation().getCurrentTerm(), data);
412 if(LOG.isDebugEnabled()) {
413 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
416 final RaftActorContext raftContext = getRaftActorContext();
419 .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
421 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
423 // Increment the Commit Index and the Last Applied values
424 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
425 raftContext.setLastApplied(replicatedLogEntry.getIndex());
427 // Apply the state immediately
428 applyState(clientActor, identifier, data);
430 // Send a ApplyLogEntries message so that we write the fact that we applied
431 // the state to durable storage
432 self().tell(new ApplyLogEntries((int) replicatedLogEntry.getIndex()), self());
434 // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot
435 if(!context.isSnapshotCaptureInitiated()){
436 raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(),
437 raftContext.getTermInformation().getCurrentTerm());
438 raftContext.getReplicatedLog().snapshotCommit();
440 LOG.debug("{}: Skipping fake snapshotting for {} because real snapshotting is in progress",
441 persistenceId(), getId());
443 } else if (clientActor != null) {
444 // Send message for replication
445 currentBehavior.handleMessage(getSelf(),
446 new Replicate(clientActor, identifier,
454 protected String getId() {
455 return context.getId();
459 * Derived actors can call the isLeader method to check if the current
460 * RaftActor is the Leader or not
462 * @return true it this RaftActor is a Leader false otherwise
464 protected boolean isLeader() {
465 return context.getId().equals(currentBehavior.getLeaderId());
469 * Derived actor can call getLeader if they need a reference to the Leader.
470 * This would be useful for example in forwarding a request to an actor
471 * which is the leader
473 * @return A reference to the leader if known, null otherwise
475 protected ActorSelection getLeader(){
476 String leaderAddress = getLeaderAddress();
478 if(leaderAddress == null){
482 return context.actorSelection(leaderAddress);
487 * @return the current leader's id
489 protected String getLeaderId(){
490 return currentBehavior.getLeaderId();
493 protected RaftState getRaftState() {
494 return currentBehavior.state();
497 protected ReplicatedLogEntry getLastLogEntry() {
498 return replicatedLog.last();
501 protected Long getCurrentTerm(){
502 return context.getTermInformation().getCurrentTerm();
505 protected Long getCommitIndex(){
506 return context.getCommitIndex();
509 protected Long getLastApplied(){
510 return context.getLastApplied();
513 protected RaftActorContext getRaftActorContext() {
518 * setPeerAddress sets the address of a known peer at a later time.
520 * This is to account for situations where a we know that a peer
521 * exists but we do not know an address up-front. This may also be used in
522 * situations where a known peer starts off in a different location and we
523 * need to change it's address
525 * Note that if the peerId does not match the list of peers passed to
526 * this actor during construction an IllegalStateException will be thrown.
531 protected void setPeerAddress(String peerId, String peerAddress){
532 context.setPeerAddress(peerId, peerAddress);
535 protected void commitSnapshot(long sequenceNumber) {
536 context.getReplicatedLog().snapshotCommit();
538 // TODO: Not sure if we want to be this aggressive with trimming stuff
539 trimPersistentData(sequenceNumber);
543 * The applyState method will be called by the RaftActor when some data
544 * needs to be applied to the actor's state
546 * @param clientActor A reference to the client who sent this message. This
547 * is the same reference that was passed to persistData
548 * by the derived actor. clientActor may be null when
549 * the RaftActor is behaving as a follower or during
551 * @param identifier The identifier of the persisted data. This is also
552 * the same identifier that was passed to persistData by
553 * the derived actor. identifier may be null when
554 * the RaftActor is behaving as a follower or during
556 * @param data A piece of data that was persisted by the persistData call.
557 * This should NEVER be null.
559 protected abstract void applyState(ActorRef clientActor, String identifier,
563 * This method is called during recovery at the start of a batch of state entries. Derived
564 * classes should perform any initialization needed to start a batch.
566 protected abstract void startLogRecoveryBatch(int maxBatchSize);
569 * This method is called during recovery to append state data to the current batch. This method
570 * is called 1 or more times after {@link #startLogRecoveryBatch}.
572 * @param data the state data
574 protected abstract void appendRecoveredLogEntry(Payload data);
577 * This method is called during recovery to reconstruct the state of the actor.
579 * @param snapshot A snapshot of the state of the actor
581 protected abstract void applyRecoverySnapshot(byte[] snapshotBytes);
584 * This method is called during recovery at the end of a batch to apply the current batched
585 * log entries. This method is called after {@link #appendRecoveredLogEntry}.
587 protected abstract void applyCurrentLogRecoveryBatch();
590 * This method is called when recovery is complete.
592 protected abstract void onRecoveryComplete();
595 * This method will be called by the RaftActor when a snapshot needs to be
596 * created. The derived actor should respond with its current state.
598 * During recovery the state that is returned by the derived actor will
599 * be passed back to it by calling the applySnapshot method
601 * @return The current state of the actor
603 protected abstract void createSnapshot();
606 * This method can be called at any other point during normal
607 * operations when the derived actor is out of sync with it's peers
608 * and the only way to bring it in sync is by applying a snapshot
610 * @param snapshotBytes A snapshot of the state of the actor
612 protected abstract void applySnapshot(byte[] snapshotBytes);
615 * This method will be called by the RaftActor when the state of the
616 * RaftActor changes. The derived actor can then use methods like
617 * isLeader or getLeader to do something useful
619 protected abstract void onStateChanged();
621 protected abstract DataPersistenceProvider persistence();
624 * Notifier Actor for this RaftActor to notify when a role change happens
625 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
627 protected abstract Optional<ActorRef> getRoleChangeNotifier();
629 protected void onLeaderChanged(String oldLeader, String newLeader){};
631 private void trimPersistentData(long sequenceNumber) {
632 // Trim akka snapshots
633 // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
634 // For now guessing that it is ANDed.
635 persistence().deleteSnapshots(new SnapshotSelectionCriteria(
636 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
639 persistence().deleteMessages(sequenceNumber);
642 private String getLeaderAddress(){
644 return getSelf().path().toString();
646 String leaderId = currentBehavior.getLeaderId();
647 if (leaderId == null) {
650 String peerAddress = context.getPeerAddress(leaderId);
651 if(LOG.isDebugEnabled()) {
652 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
653 persistenceId(), leaderId, peerAddress);
659 private void handleCaptureSnapshotReply(byte[] snapshotBytes) {
660 LOG.info("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length);
662 // create a snapshot object from the state provided and save it
663 // when snapshot is saved async, SaveSnapshotSuccess is raised.
665 Snapshot sn = Snapshot.create(snapshotBytes,
666 context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1),
667 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
668 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
670 persistence().saveSnapshot(sn);
672 LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage());
674 //be greedy and remove entries from in-mem journal which are in the snapshot
675 // and update snapshotIndex and snapshotTerm without waiting for the success,
677 context.getReplicatedLog().snapshotPreCommit(
678 captureSnapshot.getLastAppliedIndex(),
679 captureSnapshot.getLastAppliedTerm());
681 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
682 "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
683 captureSnapshot.getLastAppliedTerm());
685 if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) {
686 // this would be call straight to the leader and won't initiate in serialization
687 currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(
688 ByteString.copyFrom(snapshotBytes)));
691 captureSnapshot = null;
692 context.setSnapshotCaptureInitiated(false);
695 protected boolean hasFollowers(){
696 return getRaftActorContext().getPeerAddresses().keySet().size() > 0;
699 private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
701 private static final int DATA_SIZE_DIVIDER = 5;
702 private long dataSizeSinceLastSnapshot = 0;
704 public ReplicatedLogImpl(Snapshot snapshot) {
705 super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
706 snapshot.getUnAppliedEntries());
709 public ReplicatedLogImpl() {
713 @Override public void removeFromAndPersist(long logEntryIndex) {
714 int adjustedIndex = adjustedIndex(logEntryIndex);
716 if (adjustedIndex < 0) {
720 // FIXME: Maybe this should be done after the command is saved
721 journal.subList(adjustedIndex , journal.size()).clear();
723 persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>(){
725 @Override public void apply(DeleteEntries param)
727 //FIXME : Doing nothing for now
729 for(ReplicatedLogEntry entry : journal){
730 dataSize += entry.size();
736 @Override public void appendAndPersist(
737 final ReplicatedLogEntry replicatedLogEntry) {
738 appendAndPersist(replicatedLogEntry, null);
742 public int dataSize() {
746 public void appendAndPersist(
747 final ReplicatedLogEntry replicatedLogEntry,
748 final Procedure<ReplicatedLogEntry> callback) {
750 if(LOG.isDebugEnabled()) {
751 LOG.debug("{}: Append log entry and persist {} ", persistenceId(), replicatedLogEntry);
754 // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
755 journal.add(replicatedLogEntry);
757 // When persisting events with persist it is guaranteed that the
758 // persistent actor will not receive further commands between the
759 // persist call and the execution(s) of the associated event
760 // handler. This also holds for multiple persist calls in context
761 // of a single command.
762 persistence().persist(replicatedLogEntry,
763 new Procedure<ReplicatedLogEntry>() {
765 public void apply(ReplicatedLogEntry evt) throws Exception {
766 int logEntrySize = replicatedLogEntry.size();
768 dataSize += logEntrySize;
769 long dataSizeForCheck = dataSize;
771 dataSizeSinceLastSnapshot += logEntrySize;
772 long journalSize = lastIndex()+1;
774 if(!hasFollowers()) {
775 // When we do not have followers we do not maintain an in-memory log
776 // due to this the journalSize will never become anything close to the
777 // snapshot batch count. In fact will mostly be 1.
778 // Similarly since the journal's dataSize depends on the entries in the
779 // journal the journal's dataSize will never reach a value close to the
781 // By maintaining the dataSize outside the journal we are tracking essentially
782 // what we have written to the disk however since we no longer are in
783 // need of doing a snapshot just for the sake of freeing up memory we adjust
784 // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often
785 // as if we were maintaining a real snapshot
786 dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER;
789 long dataThreshold = Runtime.getRuntime().totalMemory() *
790 getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100;
792 // when a snaphsot is being taken, captureSnapshot != null
793 if (!context.isSnapshotCaptureInitiated() &&
794 ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 ||
795 dataSizeForCheck > dataThreshold)) {
797 dataSizeSinceLastSnapshot = 0;
799 LOG.info("{}: Initiating Snapshot Capture..", persistenceId());
800 long lastAppliedIndex = -1;
801 long lastAppliedTerm = -1;
803 ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
804 if (!hasFollowers()) {
805 lastAppliedIndex = replicatedLogEntry.getIndex();
806 lastAppliedTerm = replicatedLogEntry.getTerm();
807 } else if (lastAppliedEntry != null) {
808 lastAppliedIndex = lastAppliedEntry.getIndex();
809 lastAppliedTerm = lastAppliedEntry.getTerm();
812 if(LOG.isDebugEnabled()) {
813 LOG.debug("{}: Snapshot Capture logSize: {}", persistenceId(), journal.size());
814 LOG.debug("{}: Snapshot Capture lastApplied:{} ",
815 persistenceId(), context.getLastApplied());
816 LOG.debug("{}: Snapshot Capture lastAppliedIndex:{}", persistenceId(),
818 LOG.debug("{}: Snapshot Capture lastAppliedTerm:{}", persistenceId(),
822 // send a CaptureSnapshot to self to make the expensive operation async.
823 getSelf().tell(new CaptureSnapshot(
824 lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm),
826 context.setSnapshotCaptureInitiated(true);
828 if(callback != null){
829 callback.apply(replicatedLogEntry);
838 static class DeleteEntries implements Serializable {
839 private static final long serialVersionUID = 1L;
840 private final int fromIndex;
842 public DeleteEntries(int fromIndex) {
843 this.fromIndex = fromIndex;
846 public int getFromIndex() {
852 private class ElectionTermImpl implements ElectionTerm {
854 * Identifier of the actor whose election term information this is
856 private long currentTerm = 0;
857 private String votedFor = null;
860 public long getCurrentTerm() {
865 public String getVotedFor() {
869 @Override public void update(long currentTerm, String votedFor) {
870 if(LOG.isDebugEnabled()) {
871 LOG.debug("{}: Set currentTerm={}, votedFor={}", persistenceId(), currentTerm, votedFor);
873 this.currentTerm = currentTerm;
874 this.votedFor = votedFor;
878 public void updateAndPersist(long currentTerm, String votedFor){
879 update(currentTerm, votedFor);
880 // FIXME : Maybe first persist then update the state
881 persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
883 @Override public void apply(UpdateElectionTerm param)
891 static class UpdateElectionTerm implements Serializable {
892 private static final long serialVersionUID = 1L;
893 private final long currentTerm;
894 private final String votedFor;
896 public UpdateElectionTerm(long currentTerm, String votedFor) {
897 this.currentTerm = currentTerm;
898 this.votedFor = votedFor;
901 public long getCurrentTerm() {
905 public String getVotedFor() {
910 protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider {
912 public NonPersistentRaftDataProvider(){
917 * The way snapshotting works is,
919 * <li> RaftActor calls createSnapshot on the Shard
920 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
921 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot.
922 * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot
923 * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done
924 * in SaveSnapshotSuccess.
929 public void saveSnapshot(Object o) {
930 // Make saving Snapshot successful
936 void setCurrentBehavior(AbstractRaftActorBehavior behavior) {
937 currentBehavior = behavior;
940 protected RaftActorBehavior getCurrentBehavior() {
941 return currentBehavior;