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
8 package org.opendaylight.controller.cluster.raft;
10 import akka.persistence.SnapshotSelectionCriteria;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.io.ByteSource;
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.util.List;
16 import java.util.Optional;
17 import java.util.function.Consumer;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.controller.cluster.io.FileBackedOutputStream;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
22 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
24 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
25 import org.opendaylight.controller.cluster.raft.persisted.EmptyState;
26 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
27 import org.slf4j.Logger;
30 * Manages the capturing of snapshots for a RaftActor.
33 * @author Thomas Pantelis
35 public class SnapshotManager implements SnapshotState {
37 @SuppressWarnings("checkstyle:MemberName")
38 private final SnapshotState IDLE = new Idle();
40 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
41 private final SnapshotState PERSISTING = new Persisting();
43 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
44 private final SnapshotState CREATING = new Creating();
46 private final Logger log;
47 private final RaftActorContext context;
48 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
49 new LastAppliedTermInformationReader();
50 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
51 new ReplicatedToAllTermInformationReader();
54 private SnapshotState currentState = IDLE;
55 private CaptureSnapshot captureSnapshot;
56 private long lastSequenceNumber = -1;
58 private Consumer<Optional<OutputStream>> createSnapshotProcedure;
60 private ApplySnapshot applySnapshot;
61 private RaftActorSnapshotCohort snapshotCohort = NoopRaftActorSnapshotCohort.INSTANCE;
64 * Constructs an instance.
66 * @param context the RaftActorContext
67 * @param logger the Logger
69 public SnapshotManager(final RaftActorContext context, final Logger logger) {
70 this.context = context;
74 public boolean isApplying() {
75 return applySnapshot != null;
79 public boolean isCapturing() {
80 return currentState.isCapturing();
84 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
85 final String targetFollower) {
86 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
90 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
91 return currentState.capture(lastLogEntry, replicatedToAllIndex);
95 public void apply(final ApplySnapshot snapshot) {
96 currentState.apply(snapshot);
100 public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
101 final long totalMemory) {
102 currentState.persist(state, installSnapshotStream, totalMemory);
106 public void commit(final long sequenceNumber, final long timeStamp) {
107 currentState.commit(sequenceNumber, timeStamp);
111 public void rollback() {
112 currentState.rollback();
116 public long trimLog(final long desiredTrimIndex) {
117 return currentState.trimLog(desiredTrimIndex);
120 @SuppressWarnings("checkstyle:hiddenField")
121 void setCreateSnapshotConsumer(final Consumer<Optional<OutputStream>> createSnapshotProcedure) {
122 this.createSnapshotProcedure = createSnapshotProcedure;
125 void setSnapshotCohort(final RaftActorSnapshotCohort snapshotCohort) {
126 this.snapshotCohort = snapshotCohort;
129 public Snapshot.@NonNull State convertSnapshot(final ByteSource snapshotBytes) throws IOException {
130 return snapshotCohort.deserializeSnapshot(snapshotBytes);
133 public long getLastSequenceNumber() {
134 return lastSequenceNumber;
138 public CaptureSnapshot getCaptureSnapshot() {
139 return captureSnapshot;
142 private boolean hasFollowers() {
143 return context.hasFollowers();
146 private String persistenceId() {
147 return context.getId();
151 * Constructs a CaptureSnapshot instance.
153 * @param lastLogEntry the last log entry for the snapshot.
154 * @param replicatedToAllIndex the index of the last entry replicated to all followers.
155 * @return a new CaptureSnapshot instance.
157 public CaptureSnapshot newCaptureSnapshot(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
158 TermInformationReader lastAppliedTermInfoReader =
159 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
160 lastLogEntry, hasFollowers());
162 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
163 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
165 TermInformationReader replicatedToAllTermInfoReader =
166 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
168 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
169 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
171 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
173 long lastLogEntryIndex = lastAppliedIndex;
174 long lastLogEntryTerm = lastAppliedTerm;
175 if (lastLogEntry != null) {
176 lastLogEntryIndex = lastLogEntry.getIndex();
177 lastLogEntryTerm = lastLogEntry.getTerm();
179 log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and "
180 + "lastAppliedTerm {} instead.", persistenceId(), lastAppliedIndex, lastAppliedTerm);
183 return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
184 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries);
187 private class AbstractSnapshotState implements SnapshotState {
190 public boolean isCapturing() {
195 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
196 log.debug("capture should not be called in state {}", this);
201 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
202 final String targetFollower) {
203 log.debug("captureToInstall should not be called in state {}", this);
208 public void apply(final ApplySnapshot snapshot) {
209 log.debug("apply should not be called in state {}", this);
213 public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
214 final long totalMemory) {
215 log.debug("persist should not be called in state {}", this);
219 public void commit(final long sequenceNumber, final long timeStamp) {
220 log.debug("commit should not be called in state {}", this);
224 public void rollback() {
225 log.debug("rollback should not be called in state {}", this);
229 public long trimLog(final long desiredTrimIndex) {
230 log.debug("trimLog should not be called in state {}", this);
234 protected long doTrimLog(final long desiredTrimIndex) {
235 // we would want to keep the lastApplied as its used while capturing snapshots
236 long lastApplied = context.getLastApplied();
237 long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
239 if (log.isTraceEnabled()) {
240 log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
241 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
244 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
245 log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
246 context.getTermInformation().getCurrentTerm());
248 //use the term of the temp-min, since we check for isPresent, entry will not be null
249 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
250 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
251 context.getReplicatedLog().snapshotCommit();
255 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
256 if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
257 // It's possible a follower was lagging and an install snapshot advanced its match index past
258 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
259 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
260 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
261 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
262 currentBehavior.setReplicatedToAllIndex(tempMin);
268 private class Idle extends AbstractSnapshotState {
271 public boolean isCapturing() {
275 @SuppressWarnings("checkstyle:IllegalCatch")
276 private boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
277 final String targetFollower) {
278 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex);
280 OutputStream installSnapshotStream = null;
281 if (targetFollower != null) {
282 installSnapshotStream = context.getFileBackedOutputStreamFactory().newInstance();
283 log.info("{}: Initiating snapshot capture {} to install on {}",
284 persistenceId(), captureSnapshot, targetFollower);
286 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
289 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
291 log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
293 SnapshotManager.this.currentState = CREATING;
296 createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
297 } catch (Exception e) {
298 SnapshotManager.this.currentState = IDLE;
299 log.error("Error creating snapshot", e);
307 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
308 return capture(lastLogEntry, replicatedToAllIndex, null);
312 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
313 final String targetFollower) {
314 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
318 public void apply(final ApplySnapshot toApply) {
319 SnapshotManager.this.applySnapshot = toApply;
321 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
323 log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
325 context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
327 SnapshotManager.this.currentState = PERSISTING;
331 public String toString() {
336 public long trimLog(final long desiredTrimIndex) {
337 return doTrimLog(desiredTrimIndex);
341 private class Creating extends AbstractSnapshotState {
344 public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
345 final long totalMemory) {
346 // create a snapshot object from the state provided and save it
347 // when snapshot is saved async, SaveSnapshotSuccess is raised.
349 Snapshot snapshot = Snapshot.create(snapshotState,
350 captureSnapshot.getUnAppliedEntries(),
351 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
352 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
353 context.getTermInformation().getCurrentTerm(),
354 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
356 context.getPersistenceProvider().saveSnapshot(snapshot);
358 log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
360 long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
361 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
363 boolean logSizeExceededSnapshotBatchCount =
364 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
366 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
367 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
368 if (log.isDebugEnabled()) {
369 if (dataSizeThresholdExceeded) {
370 log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
371 + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
372 dataThreshold, captureSnapshot.getLastAppliedIndex());
374 log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
375 + "index {}", context.getId(), context.getReplicatedLog().size(),
376 context.getConfigParams().getSnapshotBatchCount(),
377 captureSnapshot.getLastAppliedIndex());
381 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
382 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
383 // This could/should only happen if one of the followers is down as normally we keep
384 // removing from the log as entries are replicated to all.
385 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
386 captureSnapshot.getLastAppliedTerm());
388 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
389 // install snapshot to a follower.
390 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
391 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
394 } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
395 // clear the log based on replicatedToAllIndex
396 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
397 captureSnapshot.getReplicatedToAllTerm());
399 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
401 // The replicatedToAllIndex was not found in the log
402 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
403 // In this scenario we may need to save the snapshot to the akka persistence
404 // snapshot for recovery but we do not need to do the replicated log trimming.
405 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
406 context.getReplicatedLog().getSnapshotTerm());
409 log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
410 context.getId(), context.getReplicatedLog().getSnapshotIndex(),
411 context.getReplicatedLog().getSnapshotTerm());
413 if (installSnapshotStream.isPresent()) {
414 if (context.getId().equals(currentBehavior.getLeaderId())) {
416 ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
417 currentBehavior.handleMessage(context.getActor(),
418 new SendInstallSnapshot(snapshot, snapshotBytes));
419 } catch (IOException e) {
420 log.error("{}: Snapshot install failed due to an unrecoverable streaming error",
424 ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
428 captureSnapshot = null;
429 SnapshotManager.this.currentState = PERSISTING;
433 public String toString() {
439 private class Persisting extends AbstractSnapshotState {
442 @SuppressWarnings("checkstyle:IllegalCatch")
443 public void commit(final long sequenceNumber, final long timeStamp) {
444 log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
446 if (applySnapshot != null) {
448 Snapshot snapshot = applySnapshot.getSnapshot();
450 //clears the followers log, sets the snapshot index to ensure adjusted-index works
451 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
452 context.setLastApplied(snapshot.getLastAppliedIndex());
453 context.setCommitIndex(snapshot.getLastAppliedIndex());
454 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
456 if (snapshot.getServerConfiguration() != null) {
457 context.updatePeerIds(snapshot.getServerConfiguration());
460 if (!(snapshot.getState() instanceof EmptyState)) {
461 snapshotCohort.applySnapshot(snapshot.getState());
464 applySnapshot.getCallback().onSuccess();
465 } catch (Exception e) {
466 log.error("{}: Error applying snapshot", context.getId(), e);
469 context.getReplicatedLog().snapshotCommit();
472 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
473 timeStamp - 1, 0L, 0L));
475 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
481 public void rollback() {
482 // Nothing to rollback if we're applying a snapshot from the leader.
483 if (applySnapshot == null) {
484 context.getReplicatedLog().snapshotRollback();
486 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
487 + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
488 context.getReplicatedLog().getSnapshotIndex(),
489 context.getReplicatedLog().getSnapshotTerm(),
490 context.getReplicatedLog().size());
492 applySnapshot.getCallback().onFailure();
498 private void snapshotComplete() {
499 lastSequenceNumber = -1;
500 applySnapshot = null;
501 SnapshotManager.this.currentState = IDLE;
503 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
507 public String toString() {
513 private interface TermInformationReader {
519 static class LastAppliedTermInformationReader implements TermInformationReader {
523 LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
524 final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
525 ReplicatedLogEntry entry = log.get(originalIndex);
529 if (lastLogEntry != null) {
530 // since we have persisted the last-log-entry to persistent journal before the capture,
531 // we would want to snapshot from this entry.
532 index = lastLogEntry.getIndex();
533 term = lastLogEntry.getTerm();
535 } else if (entry != null) {
536 index = entry.getIndex();
537 term = entry.getTerm();
538 } else if (log.getSnapshotIndex() > -1) {
539 index = log.getSnapshotIndex();
540 term = log.getSnapshotTerm();
546 public long getIndex() {
551 public long getTerm() {
556 private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
560 ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
561 ReplicatedLogEntry entry = log.get(originalIndex);
566 index = entry.getIndex();
567 term = entry.getTerm();
574 public long getIndex() {
579 public long getTerm() {