Add direct in-memory journal threshold
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / SnapshotManager.java
index 3fc43c7fd1457c126b4cf4cf40285844401341e9..791a791027ab2a2c2e7dc8786d167514c754dae6 100644 (file)
@@ -5,27 +5,45 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.controller.cluster.raft;
 
 import akka.persistence.SnapshotSelectionCriteria;
 import com.google.common.annotations.VisibleForTesting;
+import com.google.common.io.ByteSource;
+import java.io.IOException;
+import java.io.OutputStream;
 import java.util.List;
+import java.util.Optional;
 import java.util.function.Consumer;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.controller.cluster.io.FileBackedOutputStream;
 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
+import org.opendaylight.controller.cluster.raft.persisted.EmptyState;
+import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
 import org.slf4j.Logger;
 
+/**
+ * Manages the capturing of snapshots for a RaftActor.
+ *
+ * @author Moiz Raja
+ * @author Thomas Pantelis
+ */
 public class SnapshotManager implements SnapshotState {
 
+    @SuppressWarnings("checkstyle:MemberName")
     private final SnapshotState IDLE = new Idle();
+
+    @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
     private final SnapshotState PERSISTING = new Persisting();
+
+    @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
     private final SnapshotState CREATING = new Creating();
 
-    private final Logger LOG;
+    private final Logger log;
     private final RaftActorContext context;
     private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
             new LastAppliedTermInformationReader();
@@ -37,14 +55,20 @@ public class SnapshotManager implements SnapshotState {
     private CaptureSnapshot captureSnapshot;
     private long lastSequenceNumber = -1;
 
-    private Runnable createSnapshotProcedure;
+    private Consumer<Optional<OutputStream>> createSnapshotProcedure = null;
 
     private ApplySnapshot applySnapshot;
-    private Consumer<byte[]> applySnapshotProcedure;
-
-    public SnapshotManager(RaftActorContext context, Logger logger) {
+    private RaftActorSnapshotCohort snapshotCohort = NoopRaftActorSnapshotCohort.INSTANCE;
+
+    /**
+     * Constructs an instance.
+     *
+     * @param context the RaftActorContext
+     * @param logger the Logger
+     */
+    public SnapshotManager(final RaftActorContext context, final Logger logger) {
         this.context = context;
-        this.LOG = logger;
+        this.log = logger;
     }
 
     public boolean isApplying() {
@@ -57,27 +81,34 @@ public class SnapshotManager implements SnapshotState {
     }
 
     @Override
-    public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
+    public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+            final String targetFollower) {
         return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
     }
 
     @Override
-    public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
+    public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
         return currentState.capture(lastLogEntry, replicatedToAllIndex);
     }
 
     @Override
-    public void apply(ApplySnapshot snapshot) {
+    public boolean captureWithForcedTrim(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
+        return currentState.captureWithForcedTrim(lastLogEntry, replicatedToAllIndex);
+    }
+
+    @Override
+    public void apply(final ApplySnapshot snapshot) {
         currentState.apply(snapshot);
     }
 
     @Override
-    public void persist(final byte[] snapshotBytes, final long totalMemory) {
-        currentState.persist(snapshotBytes, totalMemory);
+    public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
+            final long totalMemory) {
+        currentState.persist(state, installSnapshotStream, totalMemory);
     }
 
     @Override
-    public void commit(final long sequenceNumber, long timeStamp) {
+    public void commit(final long sequenceNumber, final long timeStamp) {
         currentState.commit(sequenceNumber, timeStamp);
     }
 
@@ -91,12 +122,17 @@ public class SnapshotManager implements SnapshotState {
         return currentState.trimLog(desiredTrimIndex);
     }
 
-    public void setCreateSnapshotRunnable(Runnable createSnapshotProcedure) {
+    @SuppressWarnings("checkstyle:hiddenField")
+    void setCreateSnapshotConsumer(final Consumer<Optional<OutputStream>> createSnapshotProcedure) {
         this.createSnapshotProcedure = createSnapshotProcedure;
     }
 
-    public void setApplySnapshotConsumer(Consumer<byte[]> applySnapshotProcedure) {
-        this.applySnapshotProcedure = applySnapshotProcedure;
+    void setSnapshotCohort(final RaftActorSnapshotCohort snapshotCohort) {
+        this.snapshotCohort = snapshotCohort;
+    }
+
+    public Snapshot.@NonNull State convertSnapshot(final ByteSource snapshotBytes) throws IOException {
+        return snapshotCohort.deserializeSnapshot(snapshotBytes);
     }
 
     public long getLastSequenceNumber() {
@@ -108,16 +144,23 @@ public class SnapshotManager implements SnapshotState {
         return captureSnapshot;
     }
 
-    private boolean hasFollowers(){
+    private boolean hasFollowers() {
         return context.hasFollowers();
     }
 
-    private String persistenceId(){
+    private String persistenceId() {
         return context.getId();
     }
 
-    public CaptureSnapshot newCaptureSnapshot(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
-            boolean installSnapshotInitiated) {
+    /**
+     * Constructs a CaptureSnapshot instance.
+     *
+     * @param lastLogEntry the last log entry for the snapshot.
+     * @param replicatedToAllIndex the index of the last entry replicated to all followers.
+     * @return a new CaptureSnapshot instance.
+     */
+    public CaptureSnapshot newCaptureSnapshot(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+                                              final boolean mandatoryTrim) {
         TermInformationReader lastAppliedTermInfoReader =
                 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
                         lastLogEntry, hasFollowers());
@@ -133,18 +176,23 @@ public class SnapshotManager implements SnapshotState {
 
         List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
 
-        long lastLogEntryIndex = lastAppliedIndex;
-        long lastLogEntryTerm = lastAppliedTerm;
-        if(lastLogEntry != null) {
+        final long lastLogEntryIndex;
+        final long lastLogEntryTerm;
+        if (lastLogEntry == null) {
+            // When we don't have journal present, for example two captureSnapshots executed right after another with no
+            // new journal we still want to preserve the index and term in the snapshot.
+            lastAppliedIndex = lastLogEntryIndex = context.getReplicatedLog().getSnapshotIndex();
+            lastAppliedTerm = lastLogEntryTerm = context.getReplicatedLog().getSnapshotTerm();
+
+            log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using snapshot values lastAppliedIndex {} and "
+                    + "lastAppliedTerm {} instead.", persistenceId(), lastAppliedIndex, lastAppliedTerm);
+        } else {
             lastLogEntryIndex = lastLogEntry.getIndex();
             lastLogEntryTerm = lastLogEntry.getTerm();
-        } else {
-            LOG.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
-                    persistenceId(), lastAppliedIndex, lastAppliedTerm);
         }
 
         return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
-                newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, installSnapshotInitiated);
+                newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, mandatoryTrim);
     }
 
     private class AbstractSnapshotState implements SnapshotState {
@@ -155,55 +203,63 @@ public class SnapshotManager implements SnapshotState {
         }
 
         @Override
-        public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
-            LOG.debug("capture should not be called in state {}", this);
+        public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
+            log.debug("capture should not be called in state {}", this);
+            return false;
+        }
+
+        @Override
+        public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+                final String targetFollower) {
+            log.debug("captureToInstall should not be called in state {}", this);
             return false;
         }
 
         @Override
-        public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
-            LOG.debug("captureToInstall should not be called in state {}", this);
+        public boolean captureWithForcedTrim(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
+            log.debug("captureWithForcedTrim should not be called in state {}", this);
             return false;
         }
 
         @Override
-        public void apply(ApplySnapshot snapshot) {
-            LOG.debug("apply should not be called in state {}", this);
+        public void apply(final ApplySnapshot snapshot) {
+            log.debug("apply should not be called in state {}", this);
         }
 
         @Override
-        public void persist(final byte[] snapshotBytes, final long totalMemory) {
-            LOG.debug("persist should not be called in state {}", this);
+        public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
+                final long totalMemory) {
+            log.debug("persist should not be called in state {}", this);
         }
 
         @Override
-        public void commit(final long sequenceNumber, long timeStamp) {
-            LOG.debug("commit should not be called in state {}", this);
+        public void commit(final long sequenceNumber, final long timeStamp) {
+            log.debug("commit should not be called in state {}", this);
         }
 
         @Override
         public void rollback() {
-            LOG.debug("rollback should not be called in state {}", this);
+            log.debug("rollback should not be called in state {}", this);
         }
 
         @Override
         public long trimLog(final long desiredTrimIndex) {
-            LOG.debug("trimLog should not be called in state {}", this);
+            log.debug("trimLog should not be called in state {}", this);
             return -1;
         }
 
         protected long doTrimLog(final long desiredTrimIndex) {
             //  we would want to keep the lastApplied as its used while capturing snapshots
             long lastApplied = context.getLastApplied();
-            long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
+            long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
 
-            if(LOG.isTraceEnabled()) {
-                LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
+            if (log.isTraceEnabled()) {
+                log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
                         persistenceId(), desiredTrimIndex, lastApplied, tempMin);
             }
 
             if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
-                LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
+                log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
                         context.getTermInformation().getCurrentTerm());
 
                 //use the term of the temp-min, since we check for isPresent, entry will not be null
@@ -214,7 +270,7 @@ public class SnapshotManager implements SnapshotState {
             }
 
             final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
-            if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
+            if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
                 // It's possible a follower was lagging and an install snapshot advanced its match index past
                 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
                 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
@@ -233,27 +289,31 @@ public class SnapshotManager implements SnapshotState {
             return false;
         }
 
-        private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
-            captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, targetFollower != null);
+        @SuppressWarnings("checkstyle:IllegalCatch")
+        private boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+                final String targetFollower, final boolean mandatoryTrim) {
+            captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, mandatoryTrim);
 
-            if(captureSnapshot.isInstallSnapshotInitiated()) {
-                LOG.info("{}: Initiating snapshot capture {} to install on {}",
+            OutputStream installSnapshotStream = null;
+            if (targetFollower != null) {
+                installSnapshotStream = context.getFileBackedOutputStreamFactory().newInstance();
+                log.info("{}: Initiating snapshot capture {} to install on {}",
                         persistenceId(), captureSnapshot, targetFollower);
             } else {
-                LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
+                log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
             }
 
             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
 
-            LOG.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
+            log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
 
             SnapshotManager.this.currentState = CREATING;
 
             try {
-                createSnapshotProcedure.run();
+                createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
             } catch (Exception e) {
                 SnapshotManager.this.currentState = IDLE;
-                LOG.error("Error creating snapshot", e);
+                log.error("Error creating snapshot", e);
                 return false;
             }
 
@@ -261,24 +321,30 @@ public class SnapshotManager implements SnapshotState {
         }
 
         @Override
-        public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
-            return capture(lastLogEntry, replicatedToAllIndex, null);
+        public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
+            return capture(lastLogEntry, replicatedToAllIndex, null, false);
         }
 
         @Override
-        public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
-            return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
+        public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
+                final String targetFollower) {
+            return capture(lastLogEntry, replicatedToAllIndex, targetFollower, false);
         }
 
         @Override
-        public void apply(ApplySnapshot applySnapshot) {
-            SnapshotManager.this.applySnapshot = applySnapshot;
+        public boolean captureWithForcedTrim(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
+            return capture(lastLogEntry, replicatedToAllIndex, null, true);
+        }
+
+        @Override
+        public void apply(final ApplySnapshot toApply) {
+            SnapshotManager.this.applySnapshot = toApply;
 
             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
 
-            LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
+            log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
 
-            context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
+            context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
 
             SnapshotManager.this.currentState = PERSISTING;
         }
@@ -297,11 +363,12 @@ public class SnapshotManager implements SnapshotState {
     private class Creating extends AbstractSnapshotState {
 
         @Override
-        public void persist(final byte[] snapshotBytes, final long totalMemory) {
+        public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
+                final long totalMemory) {
             // create a snapshot object from the state provided and save it
             // when snapshot is saved async, SaveSnapshotSuccess is raised.
 
-            Snapshot snapshot = Snapshot.create(snapshotBytes,
+            Snapshot snapshot = Snapshot.create(snapshotState,
                     captureSnapshot.getUnAppliedEntries(),
                     captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
                     captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
@@ -310,26 +377,31 @@ public class SnapshotManager implements SnapshotState {
 
             context.getPersistenceProvider().saveSnapshot(snapshot);
 
-            LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
+            log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
 
-            long dataThreshold = totalMemory *
-                    context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
-            boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
+            final ConfigParams config = context.getConfigParams();
+            final long absoluteThreshold = config.getSnapshotDataThreshold();
+            final long dataThreshold = absoluteThreshold != 0 ? absoluteThreshold * ConfigParams.MEGABYTE
+                    : totalMemory * config.getSnapshotDataThresholdPercentage() / 100;
 
-            boolean logSizeExceededSnapshotBatchCount =
-                    context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
+            final boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
+            final boolean logSizeExceededSnapshotBatchCount =
+                    context.getReplicatedLog().size() >= config.getSnapshotBatchCount();
 
             final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
-            if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
-                if(LOG.isDebugEnabled()) {
-                    if(dataSizeThresholdExceeded) {
-                        LOG.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
-                                context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
-                                captureSnapshot.getLastAppliedIndex());
+            if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount || captureSnapshot.isMandatoryTrim()) {
+                if (log.isDebugEnabled()) {
+                    if (dataSizeThresholdExceeded) {
+                        log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
+                                + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
+                                dataThreshold, captureSnapshot.getLastAppliedIndex());
+                    } else if (logSizeExceededSnapshotBatchCount) {
+                        log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
+                                + "index {}", context.getId(), context.getReplicatedLog().size(),
+                                config.getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
                     } else {
-                        LOG.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
-                                context.getId(), context.getReplicatedLog().size(),
-                                context.getConfigParams().getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
+                        log.debug("{}: user triggered or root overwrite snapshot encountered, trimming log up to "
+                                + "last applied index {}", context.getId(), captureSnapshot.getLastAppliedIndex());
                     }
                 }
 
@@ -342,11 +414,11 @@ public class SnapshotManager implements SnapshotState {
 
                 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
                 // install snapshot to a follower.
-                if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
+                if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
                     currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
                 }
 
-            } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
+            } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
                 // clear the log based on replicatedToAllIndex
                 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
                         captureSnapshot.getReplicatedToAllTerm());
@@ -361,14 +433,23 @@ public class SnapshotManager implements SnapshotState {
                         context.getReplicatedLog().getSnapshotTerm());
             }
 
-            LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
-                    "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
+            log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
+                    context.getId(), context.getReplicatedLog().getSnapshotIndex(),
                     context.getReplicatedLog().getSnapshotTerm());
 
-            if (context.getId().equals(currentBehavior.getLeaderId())
-                    && captureSnapshot.isInstallSnapshotInitiated()) {
-                // this would be call straight to the leader and won't initiate in serialization
-                currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
+            if (installSnapshotStream.isPresent()) {
+                if (context.getId().equals(currentBehavior.getLeaderId())) {
+                    try {
+                        ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
+                        currentBehavior.handleMessage(context.getActor(),
+                                new SendInstallSnapshot(snapshot, snapshotBytes));
+                    } catch (IOException e) {
+                        log.error("{}: Snapshot install failed due to an unrecoverable streaming error",
+                                context.getId(), e);
+                    }
+                } else {
+                    ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
+                }
             }
 
             captureSnapshot = null;
@@ -385,10 +466,11 @@ public class SnapshotManager implements SnapshotState {
     private class Persisting extends AbstractSnapshotState {
 
         @Override
-        public void commit(final long sequenceNumber, long timeStamp) {
-            LOG.debug("{}: Snapshot success -  sequence number: {}", persistenceId(), sequenceNumber);
+        @SuppressWarnings("checkstyle:IllegalCatch")
+        public void commit(final long sequenceNumber, final long timeStamp) {
+            log.debug("{}: Snapshot success -  sequence number: {}", persistenceId(), sequenceNumber);
 
-            if(applySnapshot != null) {
+            if (applySnapshot != null) {
                 try {
                     Snapshot snapshot = applySnapshot.getSnapshot();
 
@@ -398,23 +480,23 @@ public class SnapshotManager implements SnapshotState {
                     context.setCommitIndex(snapshot.getLastAppliedIndex());
                     context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
 
-                    if(snapshot.getServerConfiguration() != null) {
+                    if (snapshot.getServerConfiguration() != null) {
                         context.updatePeerIds(snapshot.getServerConfiguration());
                     }
 
-                    if(snapshot.getState().length > 0 ) {
-                        applySnapshotProcedure.accept(snapshot.getState());
+                    if (!(snapshot.getState() instanceof EmptyState)) {
+                        snapshotCohort.applySnapshot(snapshot.getState());
                     }
 
                     applySnapshot.getCallback().onSuccess();
                 } catch (Exception e) {
-                    LOG.error("{}: Error applying snapshot", context.getId(), e);
+                    log.error("{}: Error applying snapshot", context.getId(), e);
                 }
             } else {
                 context.getReplicatedLog().snapshotCommit();
             }
 
-            context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
+            context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
                     timeStamp - 1, 0L, 0L));
 
             context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
@@ -425,11 +507,11 @@ public class SnapshotManager implements SnapshotState {
         @Override
         public void rollback() {
             // Nothing to rollback if we're applying a snapshot from the leader.
-            if(applySnapshot == null) {
+            if (applySnapshot == null) {
                 context.getReplicatedLog().snapshotRollback();
 
-                LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
-                        "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
+                log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
+                        "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
                         context.getReplicatedLog().getSnapshotIndex(),
                         context.getReplicatedLog().getSnapshotTerm(),
                         context.getReplicatedLog().size());
@@ -457,20 +539,21 @@ public class SnapshotManager implements SnapshotState {
 
     private interface TermInformationReader {
         long getIndex();
+
         long getTerm();
     }
 
-    static class LastAppliedTermInformationReader implements TermInformationReader{
+    static class LastAppliedTermInformationReader implements TermInformationReader {
         private long index;
         private long term;
 
-        public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
-                                         ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
+        LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
+                final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
             ReplicatedLogEntry entry = log.get(originalIndex);
             this.index = -1L;
             this.term = -1L;
             if (!hasFollowers) {
-                if(lastLogEntry != null) {
+                if (lastLogEntry != null) {
                     // since we have persisted the last-log-entry to persistent journal before the capture,
                     // we would want to snapshot from this entry.
                     index = lastLogEntry.getIndex();
@@ -479,7 +562,7 @@ public class SnapshotManager implements SnapshotState {
             } else if (entry != null) {
                 index = entry.getIndex();
                 term = entry.getTerm();
-            } else if(log.getSnapshotIndex() > -1){
+            } else if (log.getSnapshotIndex() > -1) {
                 index = log.getSnapshotIndex();
                 term = log.getSnapshotTerm();
             }
@@ -487,21 +570,21 @@ public class SnapshotManager implements SnapshotState {
         }
 
         @Override
-        public long getIndex(){
+        public long getIndex() {
             return this.index;
         }
 
         @Override
-        public long getTerm(){
+        public long getTerm() {
             return this.term;
         }
     }
 
-    private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
+    private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
         private long index;
         private long term;
 
-        ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
+        ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
             ReplicatedLogEntry entry = log.get(originalIndex);
             this.index = -1L;
             this.term = -1L;
@@ -515,12 +598,12 @@ public class SnapshotManager implements SnapshotState {
         }
 
         @Override
-        public long getIndex(){
+        public long getIndex() {
             return this.index;
         }
 
         @Override
-        public long getTerm(){
+        public long getTerm() {
             return this.term;
         }
     }