X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=blobdiff_plain;f=opendaylight%2Fmd-sal%2Fsal-akka-raft%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fcontroller%2Fcluster%2Fraft%2FSnapshotManager.java;h=791a791027ab2a2c2e7dc8786d167514c754dae6;hp=10574e3a02cf881c689a88e6f81de0f021ffe70b;hb=7cb260aeb0738104e3bee8a086de9e2e5f77b7e0;hpb=288a70d15252b3c5fafd202fe7935563f05da9c8 diff --git a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/SnapshotManager.java b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/SnapshotManager.java index 10574e3a02..791a791027 100644 --- a/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/SnapshotManager.java +++ b/opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/SnapshotManager.java @@ -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.japi.Procedure; 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 Procedure createSnapshotProcedure; + private Consumer> createSnapshotProcedure = null; private ApplySnapshot applySnapshot; - private Procedure 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,28 +81,35 @@ 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(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) { - currentState.persist(snapshotBytes, currentBehavior, totalMemory); + public void persist(final Snapshot.State state, final Optional installSnapshotStream, + final long totalMemory) { + currentState.persist(state, installSnapshotStream, totalMemory); } @Override - public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) { - currentState.commit(sequenceNumber, currentBehavior); + public void commit(final long sequenceNumber, final long timeStamp) { + currentState.commit(sequenceNumber, timeStamp); } @Override @@ -87,16 +118,21 @@ public class SnapshotManager implements SnapshotState { } @Override - public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) { - return currentState.trimLog(desiredTrimIndex, currentBehavior); + public long trimLog(final long desiredTrimIndex) { + return currentState.trimLog(desiredTrimIndex); } - public void setCreateSnapshotCallable(Procedure createSnapshotProcedure) { + @SuppressWarnings("checkstyle:hiddenField") + void setCreateSnapshotConsumer(final Consumer> createSnapshotProcedure) { this.createSnapshotProcedure = createSnapshotProcedure; } - public void setApplySnapshotProcedure(Procedure 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 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.", - 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(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) { - LOG.debug("captureToInstall should not be called in state {}", this); + 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 void apply(ApplySnapshot snapshot) { - LOG.debug("apply 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 persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) { - LOG.debug("persist 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 commit(long sequenceNumber, RaftActorBehavior currentBehavior) { - LOG.debug("commit should not be called in state {}", this); + public void persist(final Snapshot.State state, final Optional installSnapshotStream, + final long totalMemory) { + log.debug("persist should not be called in state {}", this); + } + + @Override + 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(long desiredTrimIndex, RaftActorBehavior currentBehavior) { - LOG.debug("trimLog should not be called in state {}", this); + public long trimLog(final long desiredTrimIndex) { + log.debug("trimLog should not be called in state {}", this); return -1; } - protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){ + 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 @@ -211,7 +267,10 @@ public class SnapshotManager implements SnapshotState { context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm()); context.getReplicatedLog().snapshotCommit(); return tempMin; - } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) { + } + + final RaftActorBehavior currentBehavior = context.getCurrentBehavior(); + 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 @@ -230,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: {}", lastSequenceNumber); + log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber); SnapshotManager.this.currentState = CREATING; try { - createSnapshotProcedure.apply(null); + 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; } @@ -258,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; } @@ -286,46 +355,53 @@ public class SnapshotManager implements SnapshotState { } @Override - public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) { - return doTrimLog(desiredTrimIndex, currentBehavior); + public long trimLog(final long desiredTrimIndex) { + return doTrimLog(desiredTrimIndex); } } private class Creating extends AbstractSnapshotState { @Override - public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) { + public void persist(final Snapshot.State snapshotState, final Optional 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(), context.getTermInformation().getCurrentTerm(), - context.getTermInformation().getVotedFor(), context.getPeerServerInfo()); + context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true)); context.getPersistenceProvider().saveSnapshot(snapshot); - LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot); - - long dataThreshold = totalMemory * - context.getConfigParams().getSnapshotDataThresholdPercentage() / 100; - boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold; - - boolean logSizeExceededSnapshotBatchCount = - context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount(); - - 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()); + log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot); + + final ConfigParams config = context.getConfigParams(); + final long absoluteThreshold = config.getSnapshotDataThreshold(); + final long dataThreshold = absoluteThreshold != 0 ? absoluteThreshold * ConfigParams.MEGABYTE + : totalMemory * config.getSnapshotDataThresholdPercentage() / 100; + + final boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold; + final boolean logSizeExceededSnapshotBatchCount = + context.getReplicatedLog().size() >= config.getSnapshotBatchCount(); + + final RaftActorBehavior currentBehavior = context.getCurrentBehavior(); + 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()); } } @@ -338,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()); @@ -357,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; @@ -381,33 +466,38 @@ public class SnapshotManager implements SnapshotState { private class Persisting extends AbstractSnapshotState { @Override - public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) { - LOG.debug("Snapshot success sequence number: {}", 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(); //clears the followers log, sets the snapshot index to ensure adjusted-index works - context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior)); + context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context)); context.setLastApplied(snapshot.getLastAppliedIndex()); context.setCommitIndex(snapshot.getLastAppliedIndex()); context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor()); - if(snapshot.getState().length > 0 ) { - applySnapshotProcedure.apply(snapshot.getState()); + if (snapshot.getServerConfiguration() != null) { + context.updatePeerIds(snapshot.getServerConfiguration()); + } + + if (!(snapshot.getState() instanceof EmptyState)) { + snapshotCohort.applySnapshot(snapshot.getState()); } applySnapshot.getCallback().onSuccess(); } catch (Exception e) { - LOG.error("Error applying snapshot", e); + log.error("{}: Error applying snapshot", context.getId(), e); } } else { context.getReplicatedLog().snapshotCommit(); } - context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria( - sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000)); + context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(), + timeStamp - 1, 0L, 0L)); context.getPersistenceProvider().deleteMessages(lastSequenceNumber); @@ -417,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()); @@ -447,22 +537,23 @@ public class SnapshotManager implements SnapshotState { } - private static interface TermInformationReader { + 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(); @@ -471,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(); } @@ -479,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; @@ -507,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; } }