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.persistence.SnapshotSelectionCriteria;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.io.ByteSource;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import java.util.List;
17 import java.util.Optional;
18 import java.util.function.Consumer;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.controller.cluster.io.FileBackedOutputStream;
21 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
22 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
24 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
25 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
26 import org.opendaylight.controller.cluster.raft.persisted.EmptyState;
27 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
28 import org.slf4j.Logger;
31 * Manages the capturing of snapshots for a RaftActor.
34 * @author Thomas Pantelis
36 public class SnapshotManager implements SnapshotState {
38 @SuppressWarnings("checkstyle:MemberName")
39 private final SnapshotState IDLE = new Idle();
41 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
42 private final SnapshotState PERSISTING = new Persisting();
44 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
45 private final SnapshotState CREATING = new Creating();
47 private final Logger log;
48 private final RaftActorContext context;
49 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
50 new LastAppliedTermInformationReader();
51 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
52 new ReplicatedToAllTermInformationReader();
55 private SnapshotState currentState = IDLE;
56 private CaptureSnapshot captureSnapshot;
57 private long lastSequenceNumber = -1;
59 private Consumer<Optional<OutputStream>> createSnapshotProcedure;
61 private ApplySnapshot applySnapshot;
62 private RaftActorSnapshotCohort snapshotCohort = NoopRaftActorSnapshotCohort.INSTANCE;
65 * Constructs an instance.
67 * @param context the RaftActorContext
68 * @param logger the Logger
70 public SnapshotManager(final RaftActorContext context, final Logger logger) {
71 this.context = context;
75 public boolean isApplying() {
76 return applySnapshot != null;
80 public boolean isCapturing() {
81 return currentState.isCapturing();
85 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
86 final String targetFollower) {
87 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
91 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
92 return currentState.capture(lastLogEntry, replicatedToAllIndex);
96 public void apply(final ApplySnapshot snapshot) {
97 currentState.apply(snapshot);
101 public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
102 final long totalMemory) {
103 currentState.persist(state, installSnapshotStream, totalMemory);
107 public void commit(final long sequenceNumber, final long timeStamp) {
108 currentState.commit(sequenceNumber, timeStamp);
112 public void rollback() {
113 currentState.rollback();
117 public long trimLog(final long desiredTrimIndex) {
118 return currentState.trimLog(desiredTrimIndex);
121 @SuppressWarnings("checkstyle:hiddenField")
122 void setCreateSnapshotConsumer(final Consumer<Optional<OutputStream>> createSnapshotProcedure) {
123 this.createSnapshotProcedure = createSnapshotProcedure;
126 void setSnapshotCohort(final RaftActorSnapshotCohort snapshotCohort) {
127 this.snapshotCohort = snapshotCohort;
131 public Snapshot.State convertSnapshot(final ByteSource snapshotBytes) throws IOException {
132 return snapshotCohort.deserializeSnapshot(snapshotBytes);
135 public long getLastSequenceNumber() {
136 return lastSequenceNumber;
140 public CaptureSnapshot getCaptureSnapshot() {
141 return captureSnapshot;
144 private boolean hasFollowers() {
145 return context.hasFollowers();
148 private String persistenceId() {
149 return context.getId();
153 * Constructs a CaptureSnapshot instance.
155 * @param lastLogEntry the last log entry for the snapshot.
156 * @param replicatedToAllIndex the index of the last entry replicated to all followers.
157 * @return a new CaptureSnapshot instance.
159 public CaptureSnapshot newCaptureSnapshot(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
160 TermInformationReader lastAppliedTermInfoReader =
161 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
162 lastLogEntry, hasFollowers());
164 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
165 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
167 TermInformationReader replicatedToAllTermInfoReader =
168 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
170 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
171 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
173 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
175 long lastLogEntryIndex = lastAppliedIndex;
176 long lastLogEntryTerm = lastAppliedTerm;
177 if (lastLogEntry != null) {
178 lastLogEntryIndex = lastLogEntry.getIndex();
179 lastLogEntryTerm = lastLogEntry.getTerm();
181 log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and "
182 + "lastAppliedTerm {} instead.", persistenceId(), lastAppliedIndex, lastAppliedTerm);
185 return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
186 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries);
189 private class AbstractSnapshotState implements SnapshotState {
192 public boolean isCapturing() {
197 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
198 log.debug("capture should not be called in state {}", this);
203 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
204 final String targetFollower) {
205 log.debug("captureToInstall should not be called in state {}", this);
210 public void apply(final ApplySnapshot snapshot) {
211 log.debug("apply should not be called in state {}", this);
215 public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
216 final long totalMemory) {
217 log.debug("persist should not be called in state {}", this);
221 public void commit(final long sequenceNumber, final long timeStamp) {
222 log.debug("commit should not be called in state {}", this);
226 public void rollback() {
227 log.debug("rollback should not be called in state {}", this);
231 public long trimLog(final long desiredTrimIndex) {
232 log.debug("trimLog should not be called in state {}", this);
236 protected long doTrimLog(final long desiredTrimIndex) {
237 // we would want to keep the lastApplied as its used while capturing snapshots
238 long lastApplied = context.getLastApplied();
239 long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
241 if (log.isTraceEnabled()) {
242 log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
243 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
246 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
247 log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
248 context.getTermInformation().getCurrentTerm());
250 //use the term of the temp-min, since we check for isPresent, entry will not be null
251 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
252 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
253 context.getReplicatedLog().snapshotCommit();
257 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
258 if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
259 // It's possible a follower was lagging and an install snapshot advanced its match index past
260 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
261 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
262 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
263 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
264 currentBehavior.setReplicatedToAllIndex(tempMin);
270 private class Idle extends AbstractSnapshotState {
273 public boolean isCapturing() {
277 @SuppressWarnings("checkstyle:IllegalCatch")
278 private boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
279 final String targetFollower) {
280 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex);
282 OutputStream installSnapshotStream = null;
283 if (targetFollower != null) {
284 installSnapshotStream = context.getFileBackedOutputStreamFactory().newInstance();
285 log.info("{}: Initiating snapshot capture {} to install on {}",
286 persistenceId(), captureSnapshot, targetFollower);
288 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
291 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
293 log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
295 SnapshotManager.this.currentState = CREATING;
298 createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
299 } catch (Exception e) {
300 SnapshotManager.this.currentState = IDLE;
301 log.error("Error creating snapshot", e);
309 public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
310 return capture(lastLogEntry, replicatedToAllIndex, null);
314 public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
315 final String targetFollower) {
316 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
320 public void apply(final ApplySnapshot toApply) {
321 SnapshotManager.this.applySnapshot = toApply;
323 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
325 log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
327 context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
329 SnapshotManager.this.currentState = PERSISTING;
333 public String toString() {
338 public long trimLog(final long desiredTrimIndex) {
339 return doTrimLog(desiredTrimIndex);
343 private class Creating extends AbstractSnapshotState {
346 public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
347 final long totalMemory) {
348 // create a snapshot object from the state provided and save it
349 // when snapshot is saved async, SaveSnapshotSuccess is raised.
351 Snapshot snapshot = Snapshot.create(snapshotState,
352 captureSnapshot.getUnAppliedEntries(),
353 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
354 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
355 context.getTermInformation().getCurrentTerm(),
356 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
358 context.getPersistenceProvider().saveSnapshot(snapshot);
360 log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
362 long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
363 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
365 boolean logSizeExceededSnapshotBatchCount =
366 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
368 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
369 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
370 if (log.isDebugEnabled()) {
371 if (dataSizeThresholdExceeded) {
372 log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
373 + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
374 dataThreshold, captureSnapshot.getLastAppliedIndex());
376 log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
377 + "index {}", context.getId(), context.getReplicatedLog().size(),
378 context.getConfigParams().getSnapshotBatchCount(),
379 captureSnapshot.getLastAppliedIndex());
383 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
384 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
385 // This could/should only happen if one of the followers is down as normally we keep
386 // removing from the log as entries are replicated to all.
387 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
388 captureSnapshot.getLastAppliedTerm());
390 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
391 // install snapshot to a follower.
392 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
393 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
396 } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
397 // clear the log based on replicatedToAllIndex
398 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
399 captureSnapshot.getReplicatedToAllTerm());
401 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
403 // The replicatedToAllIndex was not found in the log
404 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
405 // In this scenario we may need to save the snapshot to the akka persistence
406 // snapshot for recovery but we do not need to do the replicated log trimming.
407 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
408 context.getReplicatedLog().getSnapshotTerm());
411 log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
412 context.getId(), context.getReplicatedLog().getSnapshotIndex(),
413 context.getReplicatedLog().getSnapshotTerm());
415 if (installSnapshotStream.isPresent()) {
416 if (context.getId().equals(currentBehavior.getLeaderId())) {
418 ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
419 currentBehavior.handleMessage(context.getActor(),
420 new SendInstallSnapshot(snapshot, snapshotBytes));
421 } catch (IOException e) {
422 log.error("{}: Snapshot install failed due to an unrecoverable streaming error",
426 ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
430 captureSnapshot = null;
431 SnapshotManager.this.currentState = PERSISTING;
435 public String toString() {
441 private class Persisting extends AbstractSnapshotState {
444 @SuppressWarnings("checkstyle:IllegalCatch")
445 public void commit(final long sequenceNumber, final long timeStamp) {
446 log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
448 if (applySnapshot != null) {
450 Snapshot snapshot = applySnapshot.getSnapshot();
452 //clears the followers log, sets the snapshot index to ensure adjusted-index works
453 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
454 context.setLastApplied(snapshot.getLastAppliedIndex());
455 context.setCommitIndex(snapshot.getLastAppliedIndex());
456 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
458 if (snapshot.getServerConfiguration() != null) {
459 context.updatePeerIds(snapshot.getServerConfiguration());
462 if (!(snapshot.getState() instanceof EmptyState)) {
463 snapshotCohort.applySnapshot(snapshot.getState());
466 applySnapshot.getCallback().onSuccess();
467 } catch (Exception e) {
468 log.error("{}: Error applying snapshot", context.getId(), e);
471 context.getReplicatedLog().snapshotCommit();
474 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
475 timeStamp - 1, 0L, 0L));
477 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
483 public void rollback() {
484 // Nothing to rollback if we're applying a snapshot from the leader.
485 if (applySnapshot == null) {
486 context.getReplicatedLog().snapshotRollback();
488 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
489 + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
490 context.getReplicatedLog().getSnapshotIndex(),
491 context.getReplicatedLog().getSnapshotTerm(),
492 context.getReplicatedLog().size());
494 applySnapshot.getCallback().onFailure();
500 private void snapshotComplete() {
501 lastSequenceNumber = -1;
502 applySnapshot = null;
503 SnapshotManager.this.currentState = IDLE;
505 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
509 public String toString() {
515 private interface TermInformationReader {
521 static class LastAppliedTermInformationReader implements TermInformationReader {
525 LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
526 final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
527 ReplicatedLogEntry entry = log.get(originalIndex);
531 if (lastLogEntry != null) {
532 // since we have persisted the last-log-entry to persistent journal before the capture,
533 // we would want to snapshot from this entry.
534 index = lastLogEntry.getIndex();
535 term = lastLogEntry.getTerm();
537 } else if (entry != null) {
538 index = entry.getIndex();
539 term = entry.getTerm();
540 } else if (log.getSnapshotIndex() > -1) {
541 index = log.getSnapshotIndex();
542 term = log.getSnapshotTerm();
548 public long getIndex() {
553 public long getTerm() {
558 private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
562 ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
563 ReplicatedLogEntry entry = log.get(originalIndex);
568 index = entry.getIndex();
569 term = entry.getTerm();
576 public long getIndex() {
581 public long getTerm() {