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 java.util.concurrent.TimeUnit;
26 import org.opendaylight.controller.cluster.DataPersistenceProvider;
27 import org.opendaylight.controller.cluster.common.actor.AbstractUntypedPersistentActor;
28 import org.opendaylight.controller.cluster.notifications.RoleChanged;
29 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
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.SendInstallSnapshot;
37 import org.opendaylight.controller.cluster.raft.behaviors.AbstractRaftActorBehavior;
38 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
39 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
40 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
41 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
42 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
47 * RaftActor encapsulates a state machine that needs to be kept synchronized
48 * in a cluster. It implements the RAFT algorithm as described in the paper
49 * <a href='https://ramcloud.stanford.edu/wiki/download/attachments/11370504/raft.pdf'>
50 * In Search of an Understandable Consensus Algorithm</a>
52 * RaftActor has 3 states and each state has a certain behavior associated
53 * with it. A Raft actor can behave as,
56 * <li> A Follower (or) </li>
57 * <li> A Candidate </li>
61 * A RaftActor MUST be a Leader in order to accept requests from clients to
62 * change the state of it's encapsulated state machine. Once a RaftActor becomes
63 * a Leader it is also responsible for ensuring that all followers ultimately
64 * have the same log and therefore the same state machine as itself.
67 * The current behavior of a RaftActor determines how election for leadership
68 * is initiated and how peer RaftActors react to request for votes.
71 * Each RaftActor also needs to know the current election term. It uses this
72 * information for a couple of things. One is to simply figure out who it
73 * voted for in the last election. Another is to figure out if the message
74 * it received to update it's state is stale.
77 * The RaftActor uses akka-persistence to store it's replicated log.
78 * Furthermore through it's behaviors a Raft Actor determines
81 * <li> when a log entry should be persisted </li>
82 * <li> when a log entry should be applied to the state machine (and) </li>
83 * <li> when a snapshot should be saved </li>
86 public abstract class RaftActor extends AbstractUntypedPersistentActor {
88 private static final long APPLY_STATE_DELAY_THRESHOLD_IN_NANOS = TimeUnit.MILLISECONDS.toNanos(50L); // 50 millis
90 protected final Logger LOG = LoggerFactory.getLogger(getClass());
93 * The current state determines the current behavior of a RaftActor
94 * A Raft Actor always starts off in the Follower State
96 private RaftActorBehavior currentBehavior;
99 * This context should NOT be passed directly to any other actor it is
100 * only to be consumed by the RaftActorBehaviors
102 private final RaftActorContextImpl context;
105 * The in-memory journal
107 private ReplicatedLogImpl replicatedLog = new ReplicatedLogImpl();
109 private CaptureSnapshot captureSnapshot = null;
111 private Stopwatch recoveryTimer;
113 private int currentRecoveryBatchCount;
115 public RaftActor(String id, Map<String, String> peerAddresses) {
116 this(id, peerAddresses, Optional.<ConfigParams>absent());
119 public RaftActor(String id, Map<String, String> peerAddresses,
120 Optional<ConfigParams> configParams) {
122 context = new RaftActorContextImpl(this.getSelf(),
123 this.getContext(), id, new ElectionTermImpl(),
124 -1, -1, replicatedLog, peerAddresses,
125 (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
129 private void initRecoveryTimer() {
130 if(recoveryTimer == null) {
131 recoveryTimer = Stopwatch.createStarted();
136 public void preStart() throws Exception {
137 LOG.info("Starting recovery for {} with journal batch size {}", persistenceId(),
138 context.getConfigParams().getJournalRecoveryLogBatchSize());
144 public void postStop() {
145 if(currentBehavior != null) {
147 currentBehavior.close();
148 } catch (Exception e) {
149 LOG.debug("{}: Error closing behavior {}", persistenceId(), currentBehavior.state());
157 public void handleRecover(Object message) {
158 if(persistence().isRecoveryApplicable()) {
159 if (message instanceof SnapshotOffer) {
160 onRecoveredSnapshot((SnapshotOffer) message);
161 } else if (message instanceof ReplicatedLogEntry) {
162 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
163 } else if (message instanceof ApplyLogEntries) {
164 // Handle this message for backwards compatibility with pre-Lithium versions.
165 onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex());
166 } else if (message instanceof ApplyJournalEntries) {
167 onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
168 } else if (message instanceof DeleteEntries) {
169 replicatedLog.removeFrom(((DeleteEntries) message).getFromIndex());
170 } else if (message instanceof UpdateElectionTerm) {
171 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
172 ((UpdateElectionTerm) message).getVotedFor());
173 } else if (message instanceof RecoveryCompleted) {
174 onRecoveryCompletedMessage();
177 if (message instanceof RecoveryCompleted) {
178 // Delete all the messages from the akka journal so that we do not end up with consistency issues
179 // Note I am not using the dataPersistenceProvider and directly using the akka api here
180 deleteMessages(lastSequenceNr());
182 // Delete all the akka snapshots as they will not be needed
183 deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), scala.Long.MaxValue()));
185 onRecoveryComplete();
187 initializeBehavior();
192 private void onRecoveredSnapshot(SnapshotOffer offer) {
193 if(LOG.isDebugEnabled()) {
194 LOG.debug("{}: SnapshotOffer called..", persistenceId());
199 Snapshot snapshot = (Snapshot) offer.snapshot();
201 // Create a replicated log with the snapshot information
202 // The replicated log can be used later on to retrieve this snapshot
203 // when we need to install it on a peer
204 replicatedLog = new ReplicatedLogImpl(snapshot);
206 context.setReplicatedLog(replicatedLog);
207 context.setLastApplied(snapshot.getLastAppliedIndex());
208 context.setCommitIndex(snapshot.getLastAppliedIndex());
210 Stopwatch timer = Stopwatch.createStarted();
212 // Apply the snapshot to the actors state
213 applyRecoverySnapshot(snapshot.getState());
216 LOG.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size=" +
217 replicatedLog.size(), persistenceId(), timer.toString(),
218 replicatedLog.getSnapshotIndex(), replicatedLog.getSnapshotTerm());
221 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
222 if(LOG.isDebugEnabled()) {
223 LOG.debug("{}: Received ReplicatedLogEntry for recovery: {}", persistenceId(), logEntry.getIndex());
226 replicatedLog.append(logEntry);
229 private void onRecoveredApplyLogEntries(long toIndex) {
230 if(LOG.isDebugEnabled()) {
231 LOG.debug("{}: Received ApplyLogEntries for recovery, applying to state: {} to {}",
232 persistenceId(), context.getLastApplied() + 1, toIndex);
235 for (long i = context.getLastApplied() + 1; i <= toIndex; i++) {
236 batchRecoveredLogEntry(replicatedLog.get(i));
239 context.setLastApplied(toIndex);
240 context.setCommitIndex(toIndex);
243 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
246 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
247 if(currentRecoveryBatchCount == 0) {
248 startLogRecoveryBatch(batchSize);
251 appendRecoveredLogEntry(logEntry.getData());
253 if(++currentRecoveryBatchCount >= batchSize) {
254 endCurrentLogRecoveryBatch();
258 private void endCurrentLogRecoveryBatch() {
259 applyCurrentLogRecoveryBatch();
260 currentRecoveryBatchCount = 0;
263 private void onRecoveryCompletedMessage() {
264 if(currentRecoveryBatchCount > 0) {
265 endCurrentLogRecoveryBatch();
268 onRecoveryComplete();
270 String recoveryTime = "";
271 if(recoveryTimer != null) {
272 recoveryTimer.stop();
273 recoveryTime = " in " + recoveryTimer.toString();
274 recoveryTimer = null;
278 "Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
279 "Persistence Id = " + persistenceId() +
280 " Last index in log={}, snapshotIndex={}, snapshotTerm={}, " +
282 replicatedLog.lastIndex(), replicatedLog.getSnapshotIndex(),
283 replicatedLog.getSnapshotTerm(), replicatedLog.size());
285 initializeBehavior();
288 protected void initializeBehavior(){
289 changeCurrentBehavior(new Follower(context));
292 protected void changeCurrentBehavior(RaftActorBehavior newBehavior){
293 RaftActorBehavior oldBehavior = currentBehavior;
294 currentBehavior = newBehavior;
295 handleBehaviorChange(oldBehavior, currentBehavior);
298 @Override public void handleCommand(Object message) {
299 if (message instanceof ApplyState){
300 ApplyState applyState = (ApplyState) message;
302 long elapsedTime = (System.nanoTime() - applyState.getStartTime());
303 if(elapsedTime >= APPLY_STATE_DELAY_THRESHOLD_IN_NANOS){
304 LOG.warn("ApplyState took more time than expected. Elapsed Time = {} ms ApplyState = {}",
305 TimeUnit.NANOSECONDS.toMillis(elapsedTime), applyState);
308 if(LOG.isDebugEnabled()) {
309 LOG.debug("{}: Applying state for log index {} data {}",
310 persistenceId(), applyState.getReplicatedLogEntry().getIndex(),
311 applyState.getReplicatedLogEntry().getData());
314 applyState(applyState.getClientActor(), applyState.getIdentifier(),
315 applyState.getReplicatedLogEntry().getData());
317 } else if (message instanceof ApplyJournalEntries){
318 ApplyJournalEntries applyEntries = (ApplyJournalEntries) message;
319 if(LOG.isDebugEnabled()) {
320 LOG.debug("{}: Persisting ApplyLogEntries with index={}", persistenceId(), applyEntries.getToIndex());
322 persistence().persist(applyEntries, new Procedure<ApplyJournalEntries>() {
324 public void apply(ApplyJournalEntries param) throws Exception {
328 } else if(message instanceof ApplySnapshot ) {
329 Snapshot snapshot = ((ApplySnapshot) message).getSnapshot();
331 if(LOG.isDebugEnabled()) {
332 LOG.debug("{}: ApplySnapshot called on Follower Actor " +
333 "snapshotIndex:{}, snapshotTerm:{}", persistenceId(), snapshot.getLastAppliedIndex(),
334 snapshot.getLastAppliedTerm()
338 applySnapshot(snapshot.getState());
340 //clears the followers log, sets the snapshot index to ensure adjusted-index works
341 replicatedLog = new ReplicatedLogImpl(snapshot);
342 context.setReplicatedLog(replicatedLog);
343 context.setLastApplied(snapshot.getLastAppliedIndex());
345 } else if (message instanceof FindLeader) {
347 new FindLeaderReply(getLeaderAddress()),
351 } else if (message instanceof SaveSnapshotSuccess) {
352 SaveSnapshotSuccess success = (SaveSnapshotSuccess) message;
353 LOG.info("{}: SaveSnapshotSuccess received for snapshot", persistenceId());
355 long sequenceNumber = success.metadata().sequenceNr();
357 commitSnapshot(sequenceNumber);
359 } else if (message instanceof SaveSnapshotFailure) {
360 SaveSnapshotFailure saveSnapshotFailure = (SaveSnapshotFailure) message;
362 LOG.error("{}: SaveSnapshotFailure received for snapshot Cause:",
363 persistenceId(), saveSnapshotFailure.cause());
365 context.getReplicatedLog().snapshotRollback();
367 LOG.info("{}: Replicated Log rollbacked. Snapshot will be attempted in the next cycle." +
368 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
369 context.getReplicatedLog().getSnapshotIndex(),
370 context.getReplicatedLog().getSnapshotTerm(),
371 context.getReplicatedLog().size());
373 } else if (message instanceof CaptureSnapshot) {
374 LOG.info("{}: CaptureSnapshot received by actor", persistenceId());
376 if(captureSnapshot == null) {
377 captureSnapshot = (CaptureSnapshot)message;
381 } else if (message instanceof CaptureSnapshotReply){
382 handleCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot());
385 RaftActorBehavior oldBehavior = currentBehavior;
386 currentBehavior = currentBehavior.handleMessage(getSender(), message);
388 handleBehaviorChange(oldBehavior, currentBehavior);
392 private void handleBehaviorChange(RaftActorBehavior oldBehavior, RaftActorBehavior currentBehavior) {
393 if (oldBehavior != currentBehavior){
397 String oldBehaviorLeaderId = oldBehavior == null? null : oldBehavior.getLeaderId();
398 String oldBehaviorState = oldBehavior == null? null : oldBehavior.state().name();
400 // it can happen that the state has not changed but the leader has changed.
401 onLeaderChanged(oldBehaviorLeaderId, currentBehavior.getLeaderId());
403 if (getRoleChangeNotifier().isPresent() &&
404 (oldBehavior == null || (oldBehavior.state() != currentBehavior.state()))) {
405 getRoleChangeNotifier().get().tell(
406 new RoleChanged(getId(), oldBehaviorState , currentBehavior.state().name()),
412 * When a derived RaftActor needs to persist something it must call
419 protected void persistData(final ActorRef clientActor, final String identifier,
420 final Payload data) {
422 ReplicatedLogEntry replicatedLogEntry = new ReplicatedLogImplEntry(
423 context.getReplicatedLog().lastIndex() + 1,
424 context.getTermInformation().getCurrentTerm(), data);
426 if(LOG.isDebugEnabled()) {
427 LOG.debug("{}: Persist data {}", persistenceId(), replicatedLogEntry);
430 final RaftActorContext raftContext = getRaftActorContext();
433 .appendAndPersist(replicatedLogEntry, new Procedure<ReplicatedLogEntry>() {
435 public void apply(ReplicatedLogEntry replicatedLogEntry) throws Exception {
437 // Increment the Commit Index and the Last Applied values
438 raftContext.setCommitIndex(replicatedLogEntry.getIndex());
439 raftContext.setLastApplied(replicatedLogEntry.getIndex());
441 // Apply the state immediately
442 applyState(clientActor, identifier, data);
444 // Send a ApplyJournalEntries message so that we write the fact that we applied
445 // the state to durable storage
446 self().tell(new ApplyJournalEntries(replicatedLogEntry.getIndex()), self());
448 // Check if the "real" snapshot capture has been initiated. If no then do the fake snapshot
449 if(!context.isSnapshotCaptureInitiated()){
450 raftContext.getReplicatedLog().snapshotPreCommit(raftContext.getLastApplied(),
451 raftContext.getTermInformation().getCurrentTerm());
452 raftContext.getReplicatedLog().snapshotCommit();
454 LOG.debug("{}: Skipping fake snapshotting for {} because real snapshotting is in progress",
455 persistenceId(), getId());
457 } else if (clientActor != null) {
458 // Send message for replication
459 currentBehavior.handleMessage(getSelf(),
460 new Replicate(clientActor, identifier,
468 protected String getId() {
469 return context.getId();
473 * Derived actors can call the isLeader method to check if the current
474 * RaftActor is the Leader or not
476 * @return true it this RaftActor is a Leader false otherwise
478 protected boolean isLeader() {
479 return context.getId().equals(currentBehavior.getLeaderId());
483 * Derived actor can call getLeader if they need a reference to the Leader.
484 * This would be useful for example in forwarding a request to an actor
485 * which is the leader
487 * @return A reference to the leader if known, null otherwise
489 protected ActorSelection getLeader(){
490 String leaderAddress = getLeaderAddress();
492 if(leaderAddress == null){
496 return context.actorSelection(leaderAddress);
501 * @return the current leader's id
503 protected String getLeaderId(){
504 return currentBehavior.getLeaderId();
507 protected RaftState getRaftState() {
508 return currentBehavior.state();
511 protected ReplicatedLogEntry getLastLogEntry() {
512 return replicatedLog.last();
515 protected Long getCurrentTerm(){
516 return context.getTermInformation().getCurrentTerm();
519 protected Long getCommitIndex(){
520 return context.getCommitIndex();
523 protected Long getLastApplied(){
524 return context.getLastApplied();
527 protected RaftActorContext getRaftActorContext() {
531 protected void updateConfigParams(ConfigParams configParams) {
532 context.setConfigParams(configParams);
536 * setPeerAddress sets the address of a known peer at a later time.
538 * This is to account for situations where a we know that a peer
539 * exists but we do not know an address up-front. This may also be used in
540 * situations where a known peer starts off in a different location and we
541 * need to change it's address
543 * Note that if the peerId does not match the list of peers passed to
544 * this actor during construction an IllegalStateException will be thrown.
549 protected void setPeerAddress(String peerId, String peerAddress){
550 context.setPeerAddress(peerId, peerAddress);
553 protected void commitSnapshot(long sequenceNumber) {
554 context.getReplicatedLog().snapshotCommit();
556 // TODO: Not sure if we want to be this aggressive with trimming stuff
557 trimPersistentData(sequenceNumber);
561 * The applyState method will be called by the RaftActor when some data
562 * needs to be applied to the actor's state
564 * @param clientActor A reference to the client who sent this message. This
565 * is the same reference that was passed to persistData
566 * by the derived actor. clientActor may be null when
567 * the RaftActor is behaving as a follower or during
569 * @param identifier The identifier of the persisted data. This is also
570 * the same identifier that was passed to persistData by
571 * the derived actor. identifier may be null when
572 * the RaftActor is behaving as a follower or during
574 * @param data A piece of data that was persisted by the persistData call.
575 * This should NEVER be null.
577 protected abstract void applyState(ActorRef clientActor, String identifier,
581 * This method is called during recovery at the start of a batch of state entries. Derived
582 * classes should perform any initialization needed to start a batch.
584 protected abstract void startLogRecoveryBatch(int maxBatchSize);
587 * This method is called during recovery to append state data to the current batch. This method
588 * is called 1 or more times after {@link #startLogRecoveryBatch}.
590 * @param data the state data
592 protected abstract void appendRecoveredLogEntry(Payload data);
595 * This method is called during recovery to reconstruct the state of the actor.
597 * @param snapshotBytes A snapshot of the state of the actor
599 protected abstract void applyRecoverySnapshot(byte[] snapshotBytes);
602 * This method is called during recovery at the end of a batch to apply the current batched
603 * log entries. This method is called after {@link #appendRecoveredLogEntry}.
605 protected abstract void applyCurrentLogRecoveryBatch();
608 * This method is called when recovery is complete.
610 protected abstract void onRecoveryComplete();
613 * This method will be called by the RaftActor when a snapshot needs to be
614 * created. The derived actor should respond with its current state.
616 * During recovery the state that is returned by the derived actor will
617 * be passed back to it by calling the applySnapshot method
619 * @return The current state of the actor
621 protected abstract void createSnapshot();
624 * This method can be called at any other point during normal
625 * operations when the derived actor is out of sync with it's peers
626 * and the only way to bring it in sync is by applying a snapshot
628 * @param snapshotBytes A snapshot of the state of the actor
630 protected abstract void applySnapshot(byte[] snapshotBytes);
633 * This method will be called by the RaftActor when the state of the
634 * RaftActor changes. The derived actor can then use methods like
635 * isLeader or getLeader to do something useful
637 protected abstract void onStateChanged();
639 protected abstract DataPersistenceProvider persistence();
642 * Notifier Actor for this RaftActor to notify when a role change happens
643 * @return ActorRef - ActorRef of the notifier or Optional.absent if none.
645 protected abstract Optional<ActorRef> getRoleChangeNotifier();
647 protected void onLeaderChanged(String oldLeader, String newLeader){};
649 private void trimPersistentData(long sequenceNumber) {
650 // Trim akka snapshots
651 // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
652 // For now guessing that it is ANDed.
653 persistence().deleteSnapshots(new SnapshotSelectionCriteria(
654 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
657 persistence().deleteMessages(sequenceNumber);
660 private String getLeaderAddress(){
662 return getSelf().path().toString();
664 String leaderId = currentBehavior.getLeaderId();
665 if (leaderId == null) {
668 String peerAddress = context.getPeerAddress(leaderId);
669 if(LOG.isDebugEnabled()) {
670 LOG.debug("{}: getLeaderAddress leaderId = {} peerAddress = {}",
671 persistenceId(), leaderId, peerAddress);
677 private void handleCaptureSnapshotReply(byte[] snapshotBytes) {
678 LOG.info("{}: CaptureSnapshotReply received by actor: snapshot size {}", persistenceId(), snapshotBytes.length);
680 // create a snapshot object from the state provided and save it
681 // when snapshot is saved async, SaveSnapshotSuccess is raised.
683 Snapshot sn = Snapshot.create(snapshotBytes,
684 context.getReplicatedLog().getFrom(captureSnapshot.getLastAppliedIndex() + 1),
685 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
686 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
688 persistence().saveSnapshot(sn);
690 LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage());
692 long dataThreshold = Runtime.getRuntime().totalMemory() *
693 getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100;
694 if (context.getReplicatedLog().dataSize() > dataThreshold) {
695 // if memory is less, clear the log based on lastApplied.
696 // this could/should only happen if one of the followers is down
697 // as normally we keep removing from the log when its replicated to all.
698 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
699 captureSnapshot.getLastAppliedTerm());
701 getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
702 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
703 // clear the log based on replicatedToAllIndex
704 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
705 captureSnapshot.getReplicatedToAllTerm());
707 getCurrentBehavior().setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
709 // The replicatedToAllIndex was not found in the log
710 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
711 // In this scenario we may need to save the snapshot to the akka persistence
712 // snapshot for recovery but we do not need to do the replicated log trimming.
713 context.getReplicatedLog().snapshotPreCommit(replicatedLog.getSnapshotIndex(),
714 replicatedLog.getSnapshotTerm());
718 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
719 "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
720 captureSnapshot.getLastAppliedTerm());
722 if (isLeader() && captureSnapshot.isInstallSnapshotInitiated()) {
723 // this would be call straight to the leader and won't initiate in serialization
724 currentBehavior.handleMessage(getSelf(), new SendInstallSnapshot(
725 ByteString.copyFrom(snapshotBytes)));
728 captureSnapshot = null;
729 context.setSnapshotCaptureInitiated(false);
732 protected boolean hasFollowers(){
733 return getRaftActorContext().getPeerAddresses().keySet().size() > 0;
736 private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
738 private static final int DATA_SIZE_DIVIDER = 5;
739 private long dataSizeSinceLastSnapshot = 0;
741 public ReplicatedLogImpl(Snapshot snapshot) {
742 super(snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
743 snapshot.getUnAppliedEntries());
746 public ReplicatedLogImpl() {
750 @Override public void removeFromAndPersist(long logEntryIndex) {
751 int adjustedIndex = adjustedIndex(logEntryIndex);
753 if (adjustedIndex < 0) {
757 // FIXME: Maybe this should be done after the command is saved
758 journal.subList(adjustedIndex , journal.size()).clear();
760 persistence().persist(new DeleteEntries(adjustedIndex), new Procedure<DeleteEntries>() {
763 public void apply(DeleteEntries param)
765 //FIXME : Doing nothing for now
767 for (ReplicatedLogEntry entry : journal) {
768 dataSize += entry.size();
774 @Override public void appendAndPersist(
775 final ReplicatedLogEntry replicatedLogEntry) {
776 appendAndPersist(replicatedLogEntry, null);
779 public void appendAndPersist(
780 final ReplicatedLogEntry replicatedLogEntry,
781 final Procedure<ReplicatedLogEntry> callback) {
783 if(LOG.isDebugEnabled()) {
784 LOG.debug("{}: Append log entry and persist {} ", persistenceId(), replicatedLogEntry);
787 // FIXME : By adding the replicated log entry to the in-memory journal we are not truly ensuring durability of the logs
788 journal.add(replicatedLogEntry);
790 // When persisting events with persist it is guaranteed that the
791 // persistent actor will not receive further commands between the
792 // persist call and the execution(s) of the associated event
793 // handler. This also holds for multiple persist calls in context
794 // of a single command.
795 persistence().persist(replicatedLogEntry,
796 new Procedure<ReplicatedLogEntry>() {
798 public void apply(ReplicatedLogEntry evt) throws Exception {
799 int logEntrySize = replicatedLogEntry.size();
801 dataSize += logEntrySize;
802 long dataSizeForCheck = dataSize;
804 dataSizeSinceLastSnapshot += logEntrySize;
805 long journalSize = lastIndex() + 1;
807 if(!hasFollowers()) {
808 // When we do not have followers we do not maintain an in-memory log
809 // due to this the journalSize will never become anything close to the
810 // snapshot batch count. In fact will mostly be 1.
811 // Similarly since the journal's dataSize depends on the entries in the
812 // journal the journal's dataSize will never reach a value close to the
814 // By maintaining the dataSize outside the journal we are tracking essentially
815 // what we have written to the disk however since we no longer are in
816 // need of doing a snapshot just for the sake of freeing up memory we adjust
817 // the real size of data by the DATA_SIZE_DIVIDER so that we do not snapshot as often
818 // as if we were maintaining a real snapshot
819 dataSizeForCheck = dataSizeSinceLastSnapshot / DATA_SIZE_DIVIDER;
822 long dataThreshold = Runtime.getRuntime().totalMemory() *
823 getRaftActorContext().getConfigParams().getSnapshotDataThresholdPercentage() / 100;
825 // when a snaphsot is being taken, captureSnapshot != null
826 if (!context.isSnapshotCaptureInitiated() &&
827 ( journalSize % context.getConfigParams().getSnapshotBatchCount() == 0 ||
828 dataSizeForCheck > dataThreshold)) {
830 dataSizeSinceLastSnapshot = 0;
832 LOG.info("{}: Initiating Snapshot Capture, journalSize = {}, dataSizeForCheck = {}," +
833 " dataThreshold = {}", persistenceId(), journalSize, dataSizeForCheck, dataThreshold);
835 long lastAppliedIndex = -1;
836 long lastAppliedTerm = -1;
838 ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
839 if (!hasFollowers()) {
840 lastAppliedIndex = replicatedLogEntry.getIndex();
841 lastAppliedTerm = replicatedLogEntry.getTerm();
842 } else if (lastAppliedEntry != null) {
843 lastAppliedIndex = lastAppliedEntry.getIndex();
844 lastAppliedTerm = lastAppliedEntry.getTerm();
847 if(LOG.isDebugEnabled()) {
848 LOG.debug("{}: Snapshot Capture logSize: {}", persistenceId(), journal.size());
849 LOG.debug("{}: Snapshot Capture lastApplied:{} ",
850 persistenceId(), context.getLastApplied());
851 LOG.debug("{}: Snapshot Capture lastAppliedIndex:{}", persistenceId(),
853 LOG.debug("{}: Snapshot Capture lastAppliedTerm:{}", persistenceId(),
857 // send a CaptureSnapshot to self to make the expensive operation async.
858 long replicatedToAllIndex = getCurrentBehavior().getReplicatedToAllIndex();
859 ReplicatedLogEntry replicatedToAllEntry = context.getReplicatedLog().get(replicatedToAllIndex);
860 getSelf().tell(new CaptureSnapshot(lastIndex(), lastTerm(), lastAppliedIndex, lastAppliedTerm,
861 (replicatedToAllEntry != null ? replicatedToAllEntry.getIndex() : -1),
862 (replicatedToAllEntry != null ? replicatedToAllEntry.getTerm() : -1)),
864 context.setSnapshotCaptureInitiated(true);
866 if (callback != null){
867 callback.apply(replicatedLogEntry);
876 static class DeleteEntries implements Serializable {
877 private static final long serialVersionUID = 1L;
878 private final int fromIndex;
880 public DeleteEntries(int fromIndex) {
881 this.fromIndex = fromIndex;
884 public int getFromIndex() {
890 private class ElectionTermImpl implements ElectionTerm {
892 * Identifier of the actor whose election term information this is
894 private long currentTerm = 0;
895 private String votedFor = null;
898 public long getCurrentTerm() {
903 public String getVotedFor() {
907 @Override public void update(long currentTerm, String votedFor) {
908 if(LOG.isDebugEnabled()) {
909 LOG.debug("{}: Set currentTerm={}, votedFor={}", persistenceId(), currentTerm, votedFor);
911 this.currentTerm = currentTerm;
912 this.votedFor = votedFor;
916 public void updateAndPersist(long currentTerm, String votedFor){
917 update(currentTerm, votedFor);
918 // FIXME : Maybe first persist then update the state
919 persistence().persist(new UpdateElectionTerm(this.currentTerm, this.votedFor), new Procedure<UpdateElectionTerm>(){
921 @Override public void apply(UpdateElectionTerm param)
929 static class UpdateElectionTerm implements Serializable {
930 private static final long serialVersionUID = 1L;
931 private final long currentTerm;
932 private final String votedFor;
934 public UpdateElectionTerm(long currentTerm, String votedFor) {
935 this.currentTerm = currentTerm;
936 this.votedFor = votedFor;
939 public long getCurrentTerm() {
943 public String getVotedFor() {
948 protected class NonPersistentRaftDataProvider extends NonPersistentDataProvider {
950 public NonPersistentRaftDataProvider(){
955 * The way snapshotting works is,
957 * <li> RaftActor calls createSnapshot on the Shard
958 * <li> Shard sends a CaptureSnapshotReply and RaftActor then calls saveSnapshot
959 * <li> When saveSnapshot is invoked on the akka-persistence API it uses the SnapshotStore to save the snapshot.
960 * The SnapshotStore sends SaveSnapshotSuccess or SaveSnapshotFailure. When the RaftActor gets SaveSnapshot
961 * success it commits the snapshot to the in-memory journal. This commitSnapshot is mimicking what is done
962 * in SaveSnapshotSuccess.
967 public void saveSnapshot(Object o) {
968 // Make saving Snapshot successful
974 void setCurrentBehavior(AbstractRaftActorBehavior behavior) {
975 currentBehavior = behavior;
978 protected RaftActorBehavior getCurrentBehavior() {
979 return currentBehavior;