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.japi.Procedure;
14 import akka.persistence.RecoveryCompleted;
15 import akka.persistence.SaveSnapshotFailure;
16 import akka.persistence.SaveSnapshotSuccess;
17 import akka.persistence.SnapshotOffer;
18 import akka.persistence.SnapshotSelectionCriteria;
19 import com.google.common.annotations.VisibleForTesting;
20 import com.google.common.base.Optional;
21 import com.google.common.base.Stopwatch;
22 import com.google.protobuf.ByteString;
23 import java.io.Serializable;
25 import org.opendaylight.controller.cluster.DataPersistenceProvider;
26 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
27 import org.opendaylight.controller.cluster.notifications.RoleChanged;
28 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
29 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
30 import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
31 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
32 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
33 import org.opendaylight.controller.cluster.raft.base.messages.Replicate;
34 import org.opendaylight.controller.cluster.raft.base.messages.SendHeartBeat;
35 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
36 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
37 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
38 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
39 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
40 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
41 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
42 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
43 import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
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 Logger LOG = LoggerFactory.getLogger(getClass());
91 * The current state determines the current behavior of a RaftActor
92 * A Raft Actor always starts off in the Follower State
94 private RaftActorBehavior currentBehavior;
97 * This context should NOT be passed directly to any other actor it is
98 * only to be consumed by the RaftActorBehaviors
100 private final RaftActorContext context;
103 * The in-memory journal
105 private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
107 private CaptureSnapshot captureSnapshot = null;
109 private Stopwatch recoveryTimer;
111 private int currentRecoveryBatchCount;
113 public RaftActor(String id, Map<String, String> peerAddresses) {
114 this(id, peerAddresses, Optional.<ConfigParams>absent());
117 public RaftActor(String id, Map<String, String> peerAddresses,
118 Optional<ConfigParams> configParams) {
120 context = new RaftActorContextImpl(this.getSelf(),
121 this.getContext(), id, new ElectionTermImpl(),
122 -1, -1, replicatedLog, peerAddresses,
123 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
127 private void initRecoveryTimer() {
128 if(recoveryTimer == null) {
129 recoveryTimer = new Stopwatch();
130 recoveryTimer.start();
135 public void preStart() throws Exception {
136 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
137 context.getConfigParams().getJournalRecoveryLogBatchSize());
143 public void handleRecover(Object message) {
144 if(persistence().isRecoveryApplicable()) {
145 if (message instanceof SnapshotOffer) {
146 onRecoveredSnapshot((SnapshotOffer) message);
147 } else if (message instanceof ReplicatedLogEntry) {
148 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
149 } else if (message instanceof ApplyLogEntries) {
150 onRecoveredApplyLogEntries((ApplyLogEntries) message);
151 } else if (message instanceof DeleteEntries) {
152 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
153 } else if (message instanceof UpdateElectionTerm) {
154 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
155 ((UpdateElectionTerm) message).getVotedFor());
156 } else if (message instanceof RecoveryCompleted) {
157 onRecoveryCompletedMessage();
160 if (message instanceof RecoveryCompleted) {
161 // Delete all the messages from the akka journal so that we do not end up with consistency issues
162 // Note I am not using the dataPersistenceProvider and directly using the akka api here
163 deleteMessages(lastSequenceNr());
165 // Delete all the akka snapshots as they will not be needed
166 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
168 onRecoveryComplete();
170 initializeBehavior();
175 private void onRecoveredSnapshot(SnapshotOffer offer) {
176 if(LOG.isDebugEnabled()) {
177 LOG.debug("{}: SnapshotOffer called..", persistenceId());
182 Snapshot snapshot = (Snapshot) offer.snapshot();
184 // Create a replicated log with the snapshot information
185 // The replicated log can be used later on to retrieve this snapshot
186 // when we need to install it on a peer
187 replicatedLog = new ReplicatedLogImpl(snapshot);
189 context.setReplicatedLog(replicatedLog);
190 context.setLastApplied(snapshot.getLastAppliedIndex());
191 context.setCommitIndex(snapshot.getLastAppliedIndex());
193 Stopwatch timer = new Stopwatch();
196 // Apply the snapshot to the actors state
197 applyRecoverySnapshot(snapshot.getState());
200 LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" +
201 replicatedLog.size(), persistenceId(), timer.toString(),
202 replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm());
205 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
206 if(LOG.isDebugEnabled()) {
207 LOG.debug("{}: Received ReplicatedLogEntry for recovery: {}", persistenceId(), logEntry.getIndex());
210 replicatedLog.append(logEntry);
213 private void onRecoveredApplyLogEntries(ApplyLogEntries ale) {
214 if(LOG.isDebugEnabled()) {
215 LOG.debug("{}: Received ApplyLogEntries for recovery, applying to state: {} to {}",
216 persistenceId(), context.getLastApplied() + 1, ale.getToIndex());
219 for (long i = context.getLastApplied() + 1; i <= ale.getToIndex(); i++) {
220 batchRecoveredLogEntry(replicatedLog.get(i));
223 context.setLastApplied(ale.getToIndex());
224 context.setCommitIndex(ale.getToIndex());
227 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
230 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
231 if(currentRecoveryBatchCount == 0) {
232 startLogRecoveryBatch(batchSize);
235 appendRecoveredLogEntry(logEntry.getData());
237 if(++currentRecoveryBatchCount >= batchSize) {
238 endCurrentLogRecoveryBatch();
242 private void endCurrentLogRecoveryBatch() {
243 applyCurrentLogRecoveryBatch();
244 currentRecoveryBatchCount = 0;
247 private void onRecoveryCompletedMessage() {
248 if(currentRecoveryBatchCount > 0) {
249 endCurrentLogRecoveryBatch();
252 onRecoveryComplete();
254 String recoveryTime = "";
255 if(recoveryTimer != null) {
256 recoveryTimer.stop();
257 recoveryTime = " in " + recoveryTimer.toString();
258 recoveryTimer = null;
262 "Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
263 "Persistence Id = " + persistenceId() +
264 " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " +
266 replicatedLog.lastIndex(), replicatedLog.getSnapshotIndex(),
267 replicatedLog.getSnapshotTerm(), replicatedLog.size());
269 initializeBehavior();
272 protected void initializeBehavior(){
273 changeCurrentBehavior(new Follower(context));
276 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
277 RaftActorBehavior oldBehavior = currentBehavior;
278 currentBehavior = newBehavior;
279 handleBehaviorChange(oldBehavior, currentBehavior);
282 @Override public void handleCommand(Object message) {
283 if (message instanceof ApplyState){
284 ApplyState applyState = (ApplyState) message;
286 if(LOG.isDebugEnabled()) {
287 LOG.debug("{}: Applying state for log index {} data {}",
288 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
289 applyState.getReplicatedLogEntry().getData());
292 applyState(applyState.getClientActor(), applyState.getIdentifier(),
293 applyState.getReplicatedLogEntry().getData());
295 } else if (message instanceof ApplyLogEntries){
296 ApplyLogEntries ale = (ApplyLogEntries) message;
297 if(LOG.isDebugEnabled()) {
298 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), ale.getToIndex());
300 persistence().persist(new ApplyLogEntries(ale.getToIndex()), new Procedure<ApplyLogEntries>() {
302 public void apply(ApplyLogEntries param) throws Exception {
306 } else if(message instanceof ApplySnapshot ) {
307 Snapshot snapshot = ((ApplySnapshot) message).getSnapshot();
309 if(LOG.isDebugEnabled()) {
310 LOG.debug("{}: ApplySnapshot called on Follower Actor " +
311 "snapshotIndex:{}, snapshotTerm:{}", persistenceId(), snapshot.getLastAppliedIndex(),
312 snapshot.getLastAppliedTerm()
316 applySnapshot(snapshot.getState());
318 //clears the followers log, sets the snapshot index to ensure adjusted-index works
319 replicatedLog = new ReplicatedLogImpl(snapshot);
320 context.setReplicatedLog(replicatedLog);
321 context.setLastApplied(snapshot.getLastAppliedIndex());
323 } else if (message instanceof FindLeader) {
325 new FindLeaderReply(getLeaderAddress()),
329 } else if (message instanceof SaveSnapshotSuccess) {
330 SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
331 LOG.info("{}: SaveSnapshotSuccess received for snapshot", persistenceId());
333 long sequenceNumber = success.metadata().sequenceNr();
335 commitSnapshot(sequenceNumber);
337 } else if (message instanceof SaveSnapshotFailure) {
338 SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message;
340 LOG.error("{}: SaveSnapshotFailure received for snapshot Cause:",
341 persistenceId(), saveSnapshotFailure.cause());
343 context.getReplicatedLog().snapshotRollback();
345 LOG.info("{}: Replicated Log rollbacked. Snapshot will be attempted in the next cycle." +
346 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
347 context.getReplicatedLog().getSnapshotIndex(),
348 context.getReplicatedLog().getSnapshotTerm(),
349 context.getReplicatedLog().size());
351 } else if (message instanceof CaptureSnapshot) {
352 LOG.info("{}: CaptureSnapshot received by actor", persistenceId());
354 if(captureSnapshot == null) {
355 captureSnapshot = (CaptureSnapshot)message;
359 } else if (message instanceof CaptureSnapshotReply){
360 handleCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot());
363 if (!(message instanceof AppendEntriesMessages.AppendEntries)
364 && !(message instanceof AppendEntriesReply) && !(message instanceof SendHeartBeat)) {
365 if(LOG.isDebugEnabled()) {
366 LOG.debug("{}: onReceiveCommand: message: {}", persistenceId(), message.getClass());
370 RaftActorBehavior oldBehavior = currentBehavior;
371 currentBehavior = currentBehavior.handleMessage(getSender(), message);
373 handleBehaviorChange(oldBehavior, currentBehavior);
377 private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) {
378 if (oldBehavior != currentBehavior){
382 String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId();
383 String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name();
385 // it can happen that the state has not changed but the leader has changed.
386 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
388 if (getRoleChangeNotifier().isPresent() &&
389 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
390 getRoleChangeNotifier().get().tell(
391 new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()),
397 * When a derived RaftActor needs to persist something it must call
404 protected void persistData(final ActorRef clientActor, final String identifier,
405 final Payload data) {
407 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
408 context.getReplicatedLog().lastIndex() + 1,
409 context.getTermInformation().getCurrentTerm(), data);
411 if(LOG.isDebugEnabled()) {
412 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
415 final RaftActorContext raftContext = getRaftActorContext();
418 .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
420 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
422 // Increment the Commit Index and the Last Applied values
423 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
424 raftContext.setLastApplied(replicatedLogEntry.getIndex());
426 // Apply the state immediately
427 applyState(clientActor, identifier, data);
429 // Send a ApplyLogEntries message so that we write the fact that we applied
430 // the state to durable storage
431 self().tell(new ApplyLogEntries((int) replicatedLogEntry.getIndex()), self());
433 // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot
434 if(!context.isSnapshotCaptureInitiated()){
435 raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(),
436 raftContext.getTermInformation().getCurrentTerm());
437 raftContext.getReplicatedLog().snapshotCommit();
439 LOG.debug("{}: Skipping fake snapshotting for {} because real snapshotting is in progress",
440 persistenceId(), getId());
442 } else if (clientActor != null) {
443 // Send message for replication
444 currentBehavior.handleMessage(getSelf(),
445 new Replicate(clientActor, identifier,
453 protected String getId() {
454 return context.getId();
458 * Derived actors can call the isLeader method to check if the current
459 * RaftActor is the Leader or not
461 * @return true it this RaftActor is a Leader false otherwise
463 protected boolean isLeader() {
464 return context.getId().equals(currentBehavior.getLeaderId());
468 * Derived actor can call getLeader if they need a reference to the Leader.
469 * This would be useful for example in forwarding a request to an actor
470 * which is the leader
472 * @return A reference to the leader if known, null otherwise
474 protected ActorSelection getLeader(){
475 String leaderAddress = getLeaderAddress();
477 if(leaderAddress == null){
481 return context.actorSelection(leaderAddress);
486 * @return the current leader's id
488 protected String getLeaderId(){
489 return currentBehavior.getLeaderId();
492 protected RaftState getRaftState() {
493 return currentBehavior.state();
496 protected ReplicatedLogEntry getLastLogEntry() {
497 return replicatedLog.last();
500 protected Long getCurrentTerm(){
501 return context.getTermInformation().getCurrentTerm();
504 protected Long getCommitIndex(){
505 return context.getCommitIndex();
508 protected Long getLastApplied(){
509 return context.getLastApplied();
512 protected RaftActorContext getRaftActorContext() {
517 * setPeerAddress sets the address of a known peer at a later time.
519 * This is to account for situations where a we know that a peer
520 * exists but we do not know an address up-front. This may also be used in
521 * situations where a known peer starts off in a different location and we
522 * need to change it's address
524 * Note that if the peerId does not match the list of peers passed to
525 * this actor during construction an IllegalStateException will be thrown.
530 protected void setPeerAddress(String peerId, String peerAddress){
531 context.setPeerAddress(peerId, peerAddress);
534 protected void commitSnapshot(long sequenceNumber) {
535 context.getReplicatedLog().snapshotCommit();
537 // TODO: Not sure if we want to be this aggressive with trimming stuff
538 trimPersistentData(sequenceNumber);
542 * The applyState method will be called by the RaftActor when some data
543 * needs to be applied to the actor's state
545 * @param clientActor A reference to the client who sent this message. This
546 * is the same reference that was passed to persistData
547 * by the derived actor. clientActor may be null when
548 * the RaftActor is behaving as a follower or during
550 * @param identifier The identifier of the persisted data. This is also
551 * the same identifier that was passed to persistData by
552 * the derived actor. identifier may be null when
553 * the RaftActor is behaving as a follower or during
555 * @param data A piece of data that was persisted by the persistData call.
556 * This should NEVER be null.
558 protected abstract void applyState(ActorRef clientActor, String identifier,
562 * This method is called during recovery at the start of a batch of state entries. Derived
563 * classes should perform any initialization needed to start a batch.
565 protected abstract void startLogRecoveryBatch(int maxBatchSize);
568 * This method is called during recovery to append state data to the current batch. This method
569 * is called 1 or more times after {@link #startLogRecoveryBatch}.
571 * @param data the state data
573 protected abstract void appendRecoveredLogEntry(Payload data);
576 * This method is called during recovery to reconstruct the state of the actor.
578 * @param snapshot A snapshot of the state of the actor
580 protected abstract void applyRecoverySnapshot(byte[] snapshotBytes);
583 * This method is called during recovery at the end of a batch to apply the current batched
584 * log entries. This method is called after {@link #appendRecoveredLogEntry}.
586 protected abstract void applyCurrentLogRecoveryBatch();
589 * This method is called when recovery is complete.
591 protected abstract void onRecoveryComplete();
594 * This method will be called by the RaftActor when a snapshot needs to be
595 * created. The derived actor should respond with its current state.
597 * During recovery the state that is returned by the derived actor will
598 * be passed back to it by calling the applySnapshot method
600 * @return The current state of the actor
602 protected abstract void createSnapshot();
605 * This method can be called at any other point during normal
606 * operations when the derived actor is out of sync with it's peers
607 * and the only way to bring it in sync is by applying a snapshot
609 * @param snapshotBytes A snapshot of the state of the actor
611 protected abstract void applySnapshot(byte[] snapshotBytes);
614 * This method will be called by the RaftActor when the state of the
615 * RaftActor changes. The derived actor can then use methods like
616 * isLeader or getLeader to do something useful
618 protected abstract void onStateChanged();
620 protected abstract DataPersistenceProvider persistence();
623 * Notifier Actor for this RaftActor to notify when a role change happens
624 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
626 protected abstract Optional<ActorRef> getRoleChangeNotifier();
628 protected void onLeaderChanged(String oldLeader, String newLeader){};
630 private void trimPersistentData(long sequenceNumber) {
631 // Trim akka snapshots
632 // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
633 // For now guessing that it is ANDed.
634 persistence().deleteSnapshots(new SnapshotSelectionCriteria(
635 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
638 persistence().deleteMessages(sequenceNumber);
641 private String getLeaderAddress(){
643 return getSelf().path().toString();
645 String leaderId = currentBehavior.getLeaderId();
646 if (leaderId == null) {
649 String peerAddress = context.getPeerAddress(leaderId);
650 if(LOG.isDebugEnabled()) {
651 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
652 persistenceId(), leaderId, peerAddress);
658 private void handleCaptureSnapshotReply(byte[] snapshotBytes) {
659 LOG.info("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length);
661 // create a snapshot object from the state provided and save it
662 // when snapshot is saved async, SaveSnapshotSuccess is raised.
664 Snapshot sn = Snapshot.create(snapshotBytes,
665 context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1),
666 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
667 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
669 persistence().saveSnapshot(sn);
671 LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage());
673 //be greedy and remove entries from in-mem journal which are in the snapshot
674 // and update snapshotIndex and snapshotTerm without waiting for the success,
676 context.getReplicatedLog().snapshotPreCommit(
677 captureSnapshot.getLastAppliedIndex(),
678 captureSnapshot.getLastAppliedTerm());
680 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
681 "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
682 captureSnapshot.getLastAppliedTerm());
684 if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) {
685 // this would be call straight to the leader and won't initiate in serialization
686 currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(
687 ByteString.copyFrom(snapshotBytes)));
690 captureSnapshot = null;
691 context.setSnapshotCaptureInitiated(false);
694 protected boolean hasFollowers(){
695 return getRaftActorContext().getPeerAddresses().keySet().size() > 0;
698 private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
700 private static final int DATA_SIZE_DIVIDER = 5;
701 private long dataSizeSinceLastSnapshot = 0;
703 public ReplicatedLogImpl(Snapshot snapshot) {
704 super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
705 snapshot.getUnAppliedEntries());
708 public ReplicatedLogImpl() {
712 @Override public void removeFromAndPersist(long logEntryIndex) {
713 int adjustedIndex = adjustedIndex(logEntryIndex);
715 if (adjustedIndex < 0) {
719 // FIXME: Maybe this should be done after the command is saved
720 journal.subList(adjustedIndex , journal.size()).clear();
722 persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>(){
724 @Override public void apply(DeleteEntries param)
726 //FIXME : Doing nothing for now
728 for(ReplicatedLogEntry entry : journal){
729 dataSize += entry.size();
735 @Override public void appendAndPersist(
736 final ReplicatedLogEntry replicatedLogEntry) {
737 appendAndPersist(replicatedLogEntry, null);
741 public int dataSize() {
745 public void appendAndPersist(
746 final ReplicatedLogEntry replicatedLogEntry,
747 final Procedure<ReplicatedLogEntry> callback) {
749 if(LOG.isDebugEnabled()) {
750 LOG.debug("{}: Append log entry and persist {} ", persistenceId(), replicatedLogEntry);
753 // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
754 journal.add(replicatedLogEntry);
756 // When persisting events with persist it is guaranteed that the
757 // persistent actor will not receive further commands between the
758 // persist call and the execution(s) of the associated event
759 // handler. This also holds for multiple persist calls in context
760 // of a single command.
761 persistence().persist(replicatedLogEntry,
762 new Procedure<ReplicatedLogEntry>() {
764 public void apply(ReplicatedLogEntry evt) throws Exception {
765 int logEntrySize = replicatedLogEntry.size();
767 dataSize += logEntrySize;
768 long dataSizeForCheck = dataSize;
770 dataSizeSinceLastSnapshot += logEntrySize;
771 long journalSize = lastIndex()+1;
773 if(!hasFollowers()) {
774 // When we do not have followers we do not maintain an in-memory log
775 // due to this the journalSize will never become anything close to the
776 // snapshot batch count. In fact will mostly be 1.
777 // Similarly since the journal's dataSize depends on the entries in the
778 // journal the journal's dataSize will never reach a value close to the
780 // By maintaining the dataSize outside the journal we are tracking essentially
781 // what we have written to the disk however since we no longer are in
782 // need of doing a snapshot just for the sake of freeing up memory we adjust
783 // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often
784 // as if we were maintaining a real snapshot
785 dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER;
788 long dataThreshold = Runtime.getRuntime().totalMemory() *
789 getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100;
791 // when a snaphsot is being taken, captureSnapshot != null
792 if (!context.isSnapshotCaptureInitiated() &&
793 ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 ||
794 dataSizeForCheck > dataThreshold)) {
796 dataSizeSinceLastSnapshot = 0;
798 LOG.info("{}: Initiating Snapshot Capture..", persistenceId());
799 long lastAppliedIndex = -1;
800 long lastAppliedTerm = -1;
802 ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
803 if (!hasFollowers()) {
804 lastAppliedIndex = replicatedLogEntry.getIndex();
805 lastAppliedTerm = replicatedLogEntry.getTerm();
806 } else if (lastAppliedEntry != null) {
807 lastAppliedIndex = lastAppliedEntry.getIndex();
808 lastAppliedTerm = lastAppliedEntry.getTerm();
811 if(LOG.isDebugEnabled()) {
812 LOG.debug("{}: Snapshot Capture logSize: {}", persistenceId(), journal.size());
813 LOG.debug("{}: Snapshot Capture lastApplied:{} ",
814 persistenceId(), context.getLastApplied());
815 LOG.debug("{}: Snapshot Capture lastAppliedIndex:{}", persistenceId(),
817 LOG.debug("{}: Snapshot Capture lastAppliedTerm:{}", persistenceId(),
821 // send a CaptureSnapshot to self to make the expensive operation async.
822 getSelf().tell(new CaptureSnapshot(
823 lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm),
825 context.setSnapshotCaptureInitiated(true);
827 if(callback != null){
828 callback.apply(replicatedLogEntry);
837 static class DeleteEntries implements Serializable {
838 private static final long serialVersionUID = 1L;
839 private final int fromIndex;
841 public DeleteEntries(int fromIndex) {
842 this.fromIndex = fromIndex;
845 public int getFromIndex() {
851 private class ElectionTermImpl implements ElectionTerm {
853 * Identifier of the actor whose election term information this is
855 private long currentTerm = 0;
856 private String votedFor = null;
859 public long getCurrentTerm() {
864 public String getVotedFor() {
868 @Override public void update(long currentTerm, String votedFor) {
869 if(LOG.isDebugEnabled()) {
870 LOG.debug("{}: Set currentTerm={}, votedFor={}", persistenceId(), currentTerm, votedFor);
872 this.currentTerm = currentTerm;
873 this.votedFor = votedFor;
877 public void updateAndPersist(long currentTerm, String votedFor){
878 update(currentTerm, votedFor);
879 // FIXME : Maybe first persist then update the state
880 persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
882 @Override public void apply(UpdateElectionTerm param)
890 static class UpdateElectionTerm implements Serializable {
891 private static final long serialVersionUID = 1L;
892 private final long currentTerm;
893 private final String votedFor;
895 public UpdateElectionTerm(long currentTerm, String votedFor) {
896 this.currentTerm = currentTerm;
897 this.votedFor = votedFor;
900 public long getCurrentTerm() {
904 public String getVotedFor() {
909 protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider {
911 public NonPersistentRaftDataProvider(){
916 * The way snapshotting works is,
918 * <li> RaftActor calls createSnapshot on the Shard
919 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
920 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot.
921 * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot
922 * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done
923 * in SaveSnapshotSuccess.
928 public void saveSnapshot(Object o) {
929 // Make saving Snapshot successful
935 void setCurrentBehavior(AbstractRaftActorBehavior behavior) {
936 currentBehavior = behavior;
939 protected RaftActorBehavior getCurrentBehavior() {
940 return currentBehavior;