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 java.util.List;
14 import java.util.function.Consumer;
15 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
16 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
17 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
18 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
19 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
20 import org.slf4j.Logger;
23 * Manages the capturing of snapshots for a RaftActor.
26 * @author Thomas Pantelis
28 public class SnapshotManager implements SnapshotState {
30 private final SnapshotState IDLE = new Idle();
31 private final SnapshotState PERSISTING = new Persisting();
32 private final SnapshotState CREATING = new Creating();
34 private final Logger log;
35 private final RaftActorContext context;
36 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
37 new LastAppliedTermInformationReader();
38 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
39 new ReplicatedToAllTermInformationReader();
42 private SnapshotState currentState = IDLE;
43 private CaptureSnapshot captureSnapshot;
44 private long lastSequenceNumber = -1;
46 private Runnable createSnapshotProcedure;
48 private ApplySnapshot applySnapshot;
49 private Consumer<byte[]> applySnapshotProcedure;
52 * Constructs an instance.
54 * @param context the RaftActorContext
55 * @param logger the Logger
57 public SnapshotManager(RaftActorContext context, Logger logger) {
58 this.context = context;
62 public boolean isApplying() {
63 return applySnapshot != null;
67 public boolean isCapturing() {
68 return currentState.isCapturing();
72 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
73 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
77 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
78 return currentState.capture(lastLogEntry, replicatedToAllIndex);
82 public void apply(ApplySnapshot snapshot) {
83 currentState.apply(snapshot);
87 public void persist(final byte[] snapshotBytes, final long totalMemory) {
88 currentState.persist(snapshotBytes, totalMemory);
92 public void commit(final long sequenceNumber, long timeStamp) {
93 currentState.commit(sequenceNumber, timeStamp);
97 public void rollback() {
98 currentState.rollback();
102 public long trimLog(final long desiredTrimIndex) {
103 return currentState.trimLog(desiredTrimIndex);
106 public void setCreateSnapshotRunnable(Runnable createSnapshotProcedure) {
107 this.createSnapshotProcedure = createSnapshotProcedure;
110 public void setApplySnapshotConsumer(Consumer<byte[]> applySnapshotProcedure) {
111 this.applySnapshotProcedure = applySnapshotProcedure;
114 public long getLastSequenceNumber() {
115 return lastSequenceNumber;
119 public CaptureSnapshot getCaptureSnapshot() {
120 return captureSnapshot;
123 private boolean hasFollowers() {
124 return context.hasFollowers();
127 private String persistenceId() {
128 return context.getId();
132 * Constructs a CaptureSnapshot instance.
134 * @param lastLogEntry the last log entry for the snapshot.
135 * @param replicatedToAllIndex the index of the last entry replicated to all followers.
136 * @param installSnapshotInitiated true if snapshot is initiated to install on a follower.
137 * @return a new CaptureSnapshot instance.
139 public CaptureSnapshot newCaptureSnapshot(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
140 boolean installSnapshotInitiated) {
141 TermInformationReader lastAppliedTermInfoReader =
142 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
143 lastLogEntry, hasFollowers());
145 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
146 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
148 TermInformationReader replicatedToAllTermInfoReader =
149 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
151 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
152 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
154 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
156 long lastLogEntryIndex = lastAppliedIndex;
157 long lastLogEntryTerm = lastAppliedTerm;
158 if (lastLogEntry != null) {
159 lastLogEntryIndex = lastLogEntry.getIndex();
160 lastLogEntryTerm = lastLogEntry.getTerm();
162 log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
163 persistenceId(), lastAppliedIndex, lastAppliedTerm);
166 return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
167 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, installSnapshotInitiated);
170 private class AbstractSnapshotState implements SnapshotState {
173 public boolean isCapturing() {
178 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
179 log.debug("capture should not be called in state {}", this);
184 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
185 String targetFollower) {
186 log.debug("captureToInstall should not be called in state {}", this);
191 public void apply(ApplySnapshot snapshot) {
192 log.debug("apply should not be called in state {}", this);
196 public void persist(final byte[] snapshotBytes, final long totalMemory) {
197 log.debug("persist should not be called in state {}", this);
201 public void commit(final long sequenceNumber, long timeStamp) {
202 log.debug("commit should not be called in state {}", this);
206 public void rollback() {
207 log.debug("rollback should not be called in state {}", this);
211 public long trimLog(final long desiredTrimIndex) {
212 log.debug("trimLog should not be called in state {}", this);
216 protected long doTrimLog(final long desiredTrimIndex) {
217 // we would want to keep the lastApplied as its used while capturing snapshots
218 long lastApplied = context.getLastApplied();
219 long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
221 if (log.isTraceEnabled()) {
222 log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
223 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
226 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
227 log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
228 context.getTermInformation().getCurrentTerm());
230 //use the term of the temp-min, since we check for isPresent, entry will not be null
231 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
232 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
233 context.getReplicatedLog().snapshotCommit();
237 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
238 if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
239 // It's possible a follower was lagging and an install snapshot advanced its match index past
240 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
241 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
242 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
243 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
244 currentBehavior.setReplicatedToAllIndex(tempMin);
250 private class Idle extends AbstractSnapshotState {
253 public boolean isCapturing() {
257 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
258 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, targetFollower != null);
260 if (captureSnapshot.isInstallSnapshotInitiated()) {
261 log.info("{}: Initiating snapshot capture {} to install on {}",
262 persistenceId(), captureSnapshot, targetFollower);
264 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
267 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
269 log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
271 SnapshotManager.this.currentState = CREATING;
274 createSnapshotProcedure.run();
275 } catch (Exception e) {
276 SnapshotManager.this.currentState = IDLE;
277 log.error("Error creating snapshot", e);
285 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
286 return capture(lastLogEntry, replicatedToAllIndex, null);
290 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
291 String targetFollower) {
292 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
296 public void apply(ApplySnapshot toApply) {
297 SnapshotManager.this.applySnapshot = toApply;
299 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
301 log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
303 context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
305 SnapshotManager.this.currentState = PERSISTING;
309 public String toString() {
314 public long trimLog(final long desiredTrimIndex) {
315 return doTrimLog(desiredTrimIndex);
319 private class Creating extends AbstractSnapshotState {
322 public void persist(final byte[] snapshotBytes, final long totalMemory) {
323 // create a snapshot object from the state provided and save it
324 // when snapshot is saved async, SaveSnapshotSuccess is raised.
326 Snapshot snapshot = Snapshot.create(snapshotBytes,
327 captureSnapshot.getUnAppliedEntries(),
328 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
329 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
330 context.getTermInformation().getCurrentTerm(),
331 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
333 context.getPersistenceProvider().saveSnapshot(snapshot);
335 log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
337 long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
338 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
340 boolean logSizeExceededSnapshotBatchCount =
341 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
343 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
344 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
345 if (log.isDebugEnabled()) {
346 if (dataSizeThresholdExceeded) {
347 log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
348 context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
349 captureSnapshot.getLastAppliedIndex());
351 log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
352 context.getId(), context.getReplicatedLog().size(),
353 context.getConfigParams().getSnapshotBatchCount(),
354 captureSnapshot.getLastAppliedIndex());
358 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
359 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
360 // This could/should only happen if one of the followers is down as normally we keep
361 // removing from the log as entries are replicated to all.
362 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
363 captureSnapshot.getLastAppliedTerm());
365 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
366 // install snapshot to a follower.
367 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
368 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
371 } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
372 // clear the log based on replicatedToAllIndex
373 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
374 captureSnapshot.getReplicatedToAllTerm());
376 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
378 // The replicatedToAllIndex was not found in the log
379 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
380 // In this scenario we may need to save the snapshot to the akka persistence
381 // snapshot for recovery but we do not need to do the replicated log trimming.
382 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
383 context.getReplicatedLog().getSnapshotTerm());
386 log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
387 context.getId(), context.getReplicatedLog().getSnapshotIndex(),
388 context.getReplicatedLog().getSnapshotTerm());
390 if (context.getId().equals(currentBehavior.getLeaderId())
391 && captureSnapshot.isInstallSnapshotInitiated()) {
392 // this would be call straight to the leader and won't initiate in serialization
393 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
396 captureSnapshot = null;
397 SnapshotManager.this.currentState = PERSISTING;
401 public String toString() {
407 private class Persisting extends AbstractSnapshotState {
410 public void commit(final long sequenceNumber, long timeStamp) {
411 log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
413 if (applySnapshot != null) {
415 Snapshot snapshot = applySnapshot.getSnapshot();
417 //clears the followers log, sets the snapshot index to ensure adjusted-index works
418 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
419 context.setLastApplied(snapshot.getLastAppliedIndex());
420 context.setCommitIndex(snapshot.getLastAppliedIndex());
421 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
423 if (snapshot.getServerConfiguration() != null) {
424 context.updatePeerIds(snapshot.getServerConfiguration());
427 if (snapshot.getState().length > 0 ) {
428 applySnapshotProcedure.accept(snapshot.getState());
431 applySnapshot.getCallback().onSuccess();
432 } catch (Exception e) {
433 log.error("{}: Error applying snapshot", context.getId(), e);
436 context.getReplicatedLog().snapshotCommit();
439 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
440 timeStamp - 1, 0L, 0L));
442 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
448 public void rollback() {
449 // Nothing to rollback if we're applying a snapshot from the leader.
450 if (applySnapshot == null) {
451 context.getReplicatedLog().snapshotRollback();
453 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
454 + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
455 context.getReplicatedLog().getSnapshotIndex(),
456 context.getReplicatedLog().getSnapshotTerm(),
457 context.getReplicatedLog().size());
459 applySnapshot.getCallback().onFailure();
465 private void snapshotComplete() {
466 lastSequenceNumber = -1;
467 applySnapshot = null;
468 SnapshotManager.this.currentState = IDLE;
470 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
474 public String toString() {
480 private interface TermInformationReader {
486 static class LastAppliedTermInformationReader implements TermInformationReader {
490 LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex, ReplicatedLogEntry lastLogEntry,
491 boolean hasFollowers) {
492 ReplicatedLogEntry entry = log.get(originalIndex);
496 if (lastLogEntry != null) {
497 // since we have persisted the last-log-entry to persistent journal before the capture,
498 // we would want to snapshot from this entry.
499 index = lastLogEntry.getIndex();
500 term = lastLogEntry.getTerm();
502 } else if (entry != null) {
503 index = entry.getIndex();
504 term = entry.getTerm();
505 } else if (log.getSnapshotIndex() > -1) {
506 index = log.getSnapshotIndex();
507 term = log.getSnapshotTerm();
513 public long getIndex() {
518 public long getTerm() {
523 private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
527 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex) {
528 ReplicatedLogEntry entry = log.get(originalIndex);
533 index = entry.getIndex();
534 term = entry.getTerm();
541 public long getIndex() {
546 public long getTerm() {