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(RaftActorContext context, 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(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
86 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
90 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
91 return currentState.capture(lastLogEntry, replicatedToAllIndex);
95 public void apply(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, 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 void setCreateSnapshotConsumer(Consumer<Optional<OutputStream>> createSnapshotProcedure) {
121 this.createSnapshotProcedure = createSnapshotProcedure;
124 void setSnapshotCohort(final RaftActorSnapshotCohort snapshotCohort) {
125 this.snapshotCohort = snapshotCohort;
129 public Snapshot.State convertSnapshot(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(ReplicatedLogEntry lastLogEntry, 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(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
196 log.debug("capture should not be called in state {}", this);
201 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
202 String targetFollower) {
203 log.debug("captureToInstall should not be called in state {}", this);
208 public void apply(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, 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(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
277 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex);
279 OutputStream installSnapshotStream = null;
280 if (targetFollower != null) {
281 installSnapshotStream = context.getFileBackedOutputStreamFactory().newInstance();
282 log.info("{}: Initiating snapshot capture {} to install on {}",
283 persistenceId(), captureSnapshot, targetFollower);
285 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
288 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
290 log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
292 SnapshotManager.this.currentState = CREATING;
295 createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
296 } catch (Exception e) {
297 SnapshotManager.this.currentState = IDLE;
298 log.error("Error creating snapshot", e);
306 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
307 return capture(lastLogEntry, replicatedToAllIndex, null);
311 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
312 String targetFollower) {
313 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
317 public void apply(ApplySnapshot toApply) {
318 SnapshotManager.this.applySnapshot = toApply;
320 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
322 log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
324 context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
326 SnapshotManager.this.currentState = PERSISTING;
330 public String toString() {
335 public long trimLog(final long desiredTrimIndex) {
336 return doTrimLog(desiredTrimIndex);
340 private class Creating extends AbstractSnapshotState {
343 public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
344 final long totalMemory) {
345 // create a snapshot object from the state provided and save it
346 // when snapshot is saved async, SaveSnapshotSuccess is raised.
348 Snapshot snapshot = Snapshot.create(snapshotState,
349 captureSnapshot.getUnAppliedEntries(),
350 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
351 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
352 context.getTermInformation().getCurrentTerm(),
353 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
355 context.getPersistenceProvider().saveSnapshot(snapshot);
357 log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
359 long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
360 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
362 boolean logSizeExceededSnapshotBatchCount =
363 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
365 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
366 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
367 if (log.isDebugEnabled()) {
368 if (dataSizeThresholdExceeded) {
369 log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
370 + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
371 dataThreshold, captureSnapshot.getLastAppliedIndex());
373 log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
374 + "index {}", context.getId(), context.getReplicatedLog().size(),
375 context.getConfigParams().getSnapshotBatchCount(),
376 captureSnapshot.getLastAppliedIndex());
380 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
381 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
382 // This could/should only happen if one of the followers is down as normally we keep
383 // removing from the log as entries are replicated to all.
384 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
385 captureSnapshot.getLastAppliedTerm());
387 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
388 // install snapshot to a follower.
389 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
390 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
393 } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
394 // clear the log based on replicatedToAllIndex
395 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
396 captureSnapshot.getReplicatedToAllTerm());
398 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
400 // The replicatedToAllIndex was not found in the log
401 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
402 // In this scenario we may need to save the snapshot to the akka persistence
403 // snapshot for recovery but we do not need to do the replicated log trimming.
404 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
405 context.getReplicatedLog().getSnapshotTerm());
408 log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
409 context.getId(), context.getReplicatedLog().getSnapshotIndex(),
410 context.getReplicatedLog().getSnapshotTerm());
412 if (installSnapshotStream.isPresent()) {
413 if (context.getId().equals(currentBehavior.getLeaderId())) {
415 ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
416 currentBehavior.handleMessage(context.getActor(),
417 new SendInstallSnapshot(snapshot, snapshotBytes));
418 } catch (IOException e) {
419 log.error("{}: Snapshot install failed due to an unrecoverable streaming error",
423 ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
427 captureSnapshot = null;
428 SnapshotManager.this.currentState = PERSISTING;
432 public String toString() {
438 private class Persisting extends AbstractSnapshotState {
441 @SuppressWarnings("checkstyle:IllegalCatch")
442 public void commit(final long sequenceNumber, long timeStamp) {
443 log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
445 if (applySnapshot != null) {
447 Snapshot snapshot = applySnapshot.getSnapshot();
449 //clears the followers log, sets the snapshot index to ensure adjusted-index works
450 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
451 context.setLastApplied(snapshot.getLastAppliedIndex());
452 context.setCommitIndex(snapshot.getLastAppliedIndex());
453 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
455 if (snapshot.getServerConfiguration() != null) {
456 context.updatePeerIds(snapshot.getServerConfiguration());
459 if (!(snapshot.getState() instanceof EmptyState)) {
460 snapshotCohort.applySnapshot(snapshot.getState());
463 applySnapshot.getCallback().onSuccess();
464 } catch (Exception e) {
465 log.error("{}: Error applying snapshot", context.getId(), e);
468 context.getReplicatedLog().snapshotCommit();
471 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
472 timeStamp - 1, 0L, 0L));
474 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
480 public void rollback() {
481 // Nothing to rollback if we're applying a snapshot from the leader.
482 if (applySnapshot == null) {
483 context.getReplicatedLog().snapshotRollback();
485 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
486 + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
487 context.getReplicatedLog().getSnapshotIndex(),
488 context.getReplicatedLog().getSnapshotTerm(),
489 context.getReplicatedLog().size());
491 applySnapshot.getCallback().onFailure();
497 private void snapshotComplete() {
498 lastSequenceNumber = -1;
499 applySnapshot = null;
500 SnapshotManager.this.currentState = IDLE;
502 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
506 public String toString() {
512 private interface TermInformationReader {
518 static class LastAppliedTermInformationReader implements TermInformationReader {
522 LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex, ReplicatedLogEntry lastLogEntry,
523 boolean hasFollowers) {
524 ReplicatedLogEntry entry = log.get(originalIndex);
528 if (lastLogEntry != null) {
529 // since we have persisted the last-log-entry to persistent journal before the capture,
530 // we would want to snapshot from this entry.
531 index = lastLogEntry.getIndex();
532 term = lastLogEntry.getTerm();
534 } else if (entry != null) {
535 index = entry.getIndex();
536 term = entry.getTerm();
537 } else if (log.getSnapshotIndex() > -1) {
538 index = log.getSnapshotIndex();
539 term = log.getSnapshotTerm();
545 public long getIndex() {
550 public long getTerm() {
555 private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
559 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex) {
560 ReplicatedLogEntry entry = log.get(originalIndex);
565 index = entry.getIndex();
566 term = entry.getTerm();
573 public long getIndex() {
578 public long getTerm() {