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 @SuppressWarnings("checkstyle:MemberName")
31 private final SnapshotState IDLE = new Idle();
33 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
34 private final SnapshotState PERSISTING = new Persisting();
36 @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
37 private final SnapshotState CREATING = new Creating();
39 private final Logger log;
40 private final RaftActorContext context;
41 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
42 new LastAppliedTermInformationReader();
43 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
44 new ReplicatedToAllTermInformationReader();
47 private SnapshotState currentState = IDLE;
48 private CaptureSnapshot captureSnapshot;
49 private long lastSequenceNumber = -1;
51 private Runnable createSnapshotProcedure;
53 private ApplySnapshot applySnapshot;
54 private Consumer<byte[]> applySnapshotProcedure;
57 * Constructs an instance.
59 * @param context the RaftActorContext
60 * @param logger the Logger
62 public SnapshotManager(RaftActorContext context, Logger logger) {
63 this.context = context;
67 public boolean isApplying() {
68 return applySnapshot != null;
72 public boolean isCapturing() {
73 return currentState.isCapturing();
77 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
78 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
82 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
83 return currentState.capture(lastLogEntry, replicatedToAllIndex);
87 public void apply(ApplySnapshot snapshot) {
88 currentState.apply(snapshot);
92 public void persist(final byte[] snapshotBytes, final long totalMemory) {
93 currentState.persist(snapshotBytes, totalMemory);
97 public void commit(final long sequenceNumber, long timeStamp) {
98 currentState.commit(sequenceNumber, timeStamp);
102 public void rollback() {
103 currentState.rollback();
107 public long trimLog(final long desiredTrimIndex) {
108 return currentState.trimLog(desiredTrimIndex);
111 public void setCreateSnapshotRunnable(Runnable createSnapshotProcedure) {
112 this.createSnapshotProcedure = createSnapshotProcedure;
115 public void setApplySnapshotConsumer(Consumer<byte[]> applySnapshotProcedure) {
116 this.applySnapshotProcedure = applySnapshotProcedure;
119 public long getLastSequenceNumber() {
120 return lastSequenceNumber;
124 public CaptureSnapshot getCaptureSnapshot() {
125 return captureSnapshot;
128 private boolean hasFollowers() {
129 return context.hasFollowers();
132 private String persistenceId() {
133 return context.getId();
137 * Constructs a CaptureSnapshot instance.
139 * @param lastLogEntry the last log entry for the snapshot.
140 * @param replicatedToAllIndex the index of the last entry replicated to all followers.
141 * @param installSnapshotInitiated true if snapshot is initiated to install on a follower.
142 * @return a new CaptureSnapshot instance.
144 public CaptureSnapshot newCaptureSnapshot(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
145 boolean installSnapshotInitiated) {
146 TermInformationReader lastAppliedTermInfoReader =
147 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
148 lastLogEntry, hasFollowers());
150 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
151 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
153 TermInformationReader replicatedToAllTermInfoReader =
154 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
156 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
157 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
159 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
161 long lastLogEntryIndex = lastAppliedIndex;
162 long lastLogEntryTerm = lastAppliedTerm;
163 if (lastLogEntry != null) {
164 lastLogEntryIndex = lastLogEntry.getIndex();
165 lastLogEntryTerm = lastLogEntry.getTerm();
167 log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and "
168 + "lastAppliedTerm {} instead.", persistenceId(), lastAppliedIndex, lastAppliedTerm);
171 return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
172 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, installSnapshotInitiated);
175 private class AbstractSnapshotState implements SnapshotState {
178 public boolean isCapturing() {
183 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
184 log.debug("capture should not be called in state {}", this);
189 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
190 String targetFollower) {
191 log.debug("captureToInstall should not be called in state {}", this);
196 public void apply(ApplySnapshot snapshot) {
197 log.debug("apply should not be called in state {}", this);
201 public void persist(final byte[] snapshotBytes, final long totalMemory) {
202 log.debug("persist should not be called in state {}", this);
206 public void commit(final long sequenceNumber, long timeStamp) {
207 log.debug("commit should not be called in state {}", this);
211 public void rollback() {
212 log.debug("rollback should not be called in state {}", this);
216 public long trimLog(final long desiredTrimIndex) {
217 log.debug("trimLog should not be called in state {}", this);
221 protected long doTrimLog(final long desiredTrimIndex) {
222 // we would want to keep the lastApplied as its used while capturing snapshots
223 long lastApplied = context.getLastApplied();
224 long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
226 if (log.isTraceEnabled()) {
227 log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
228 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
231 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
232 log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
233 context.getTermInformation().getCurrentTerm());
235 //use the term of the temp-min, since we check for isPresent, entry will not be null
236 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
237 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
238 context.getReplicatedLog().snapshotCommit();
242 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
243 if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
244 // It's possible a follower was lagging and an install snapshot advanced its match index past
245 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
246 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
247 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
248 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
249 currentBehavior.setReplicatedToAllIndex(tempMin);
255 private class Idle extends AbstractSnapshotState {
258 public boolean isCapturing() {
262 @SuppressWarnings("checkstyle:IllegalCatch")
263 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
264 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, targetFollower != null);
266 if (captureSnapshot.isInstallSnapshotInitiated()) {
267 log.info("{}: Initiating snapshot capture {} to install on {}",
268 persistenceId(), captureSnapshot, targetFollower);
270 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
273 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
275 log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
277 SnapshotManager.this.currentState = CREATING;
280 createSnapshotProcedure.run();
281 } catch (Exception e) {
282 SnapshotManager.this.currentState = IDLE;
283 log.error("Error creating snapshot", e);
291 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
292 return capture(lastLogEntry, replicatedToAllIndex, null);
296 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
297 String targetFollower) {
298 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
302 public void apply(ApplySnapshot toApply) {
303 SnapshotManager.this.applySnapshot = toApply;
305 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
307 log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
309 context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
311 SnapshotManager.this.currentState = PERSISTING;
315 public String toString() {
320 public long trimLog(final long desiredTrimIndex) {
321 return doTrimLog(desiredTrimIndex);
325 private class Creating extends AbstractSnapshotState {
328 public void persist(final byte[] snapshotBytes, final long totalMemory) {
329 // create a snapshot object from the state provided and save it
330 // when snapshot is saved async, SaveSnapshotSuccess is raised.
332 Snapshot snapshot = Snapshot.create(snapshotBytes,
333 captureSnapshot.getUnAppliedEntries(),
334 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
335 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
336 context.getTermInformation().getCurrentTerm(),
337 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
339 context.getPersistenceProvider().saveSnapshot(snapshot);
341 log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
343 long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
344 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
346 boolean logSizeExceededSnapshotBatchCount =
347 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
349 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
350 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
351 if (log.isDebugEnabled()) {
352 if (dataSizeThresholdExceeded) {
353 log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
354 + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
355 dataThreshold, captureSnapshot.getLastAppliedIndex());
357 log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
358 + "index {}", context.getId(), context.getReplicatedLog().size(),
359 context.getConfigParams().getSnapshotBatchCount(),
360 captureSnapshot.getLastAppliedIndex());
364 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
365 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
366 // This could/should only happen if one of the followers is down as normally we keep
367 // removing from the log as entries are replicated to all.
368 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
369 captureSnapshot.getLastAppliedTerm());
371 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
372 // install snapshot to a follower.
373 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
374 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
377 } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
378 // clear the log based on replicatedToAllIndex
379 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
380 captureSnapshot.getReplicatedToAllTerm());
382 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
384 // The replicatedToAllIndex was not found in the log
385 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
386 // In this scenario we may need to save the snapshot to the akka persistence
387 // snapshot for recovery but we do not need to do the replicated log trimming.
388 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
389 context.getReplicatedLog().getSnapshotTerm());
392 log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
393 context.getId(), context.getReplicatedLog().getSnapshotIndex(),
394 context.getReplicatedLog().getSnapshotTerm());
396 if (context.getId().equals(currentBehavior.getLeaderId())
397 && captureSnapshot.isInstallSnapshotInitiated()) {
398 // this would be call straight to the leader and won't initiate in serialization
399 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
402 captureSnapshot = null;
403 SnapshotManager.this.currentState = PERSISTING;
407 public String toString() {
413 private class Persisting extends AbstractSnapshotState {
416 @SuppressWarnings("checkstyle:IllegalCatch")
417 public void commit(final long sequenceNumber, long timeStamp) {
418 log.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
420 if (applySnapshot != null) {
422 Snapshot snapshot = applySnapshot.getSnapshot();
424 //clears the followers log, sets the snapshot index to ensure adjusted-index works
425 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
426 context.setLastApplied(snapshot.getLastAppliedIndex());
427 context.setCommitIndex(snapshot.getLastAppliedIndex());
428 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
430 if (snapshot.getServerConfiguration() != null) {
431 context.updatePeerIds(snapshot.getServerConfiguration());
434 if (snapshot.getState().length > 0 ) {
435 applySnapshotProcedure.accept(snapshot.getState());
438 applySnapshot.getCallback().onSuccess();
439 } catch (Exception e) {
440 log.error("{}: Error applying snapshot", context.getId(), e);
443 context.getReplicatedLog().snapshotCommit();
446 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(sequenceNumber,
447 timeStamp - 1, 0L, 0L));
449 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
455 public void rollback() {
456 // Nothing to rollback if we're applying a snapshot from the leader.
457 if (applySnapshot == null) {
458 context.getReplicatedLog().snapshotRollback();
460 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
461 + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
462 context.getReplicatedLog().getSnapshotIndex(),
463 context.getReplicatedLog().getSnapshotTerm(),
464 context.getReplicatedLog().size());
466 applySnapshot.getCallback().onFailure();
472 private void snapshotComplete() {
473 lastSequenceNumber = -1;
474 applySnapshot = null;
475 SnapshotManager.this.currentState = IDLE;
477 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
481 public String toString() {
487 private interface TermInformationReader {
493 static class LastAppliedTermInformationReader implements TermInformationReader {
497 LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex, ReplicatedLogEntry lastLogEntry,
498 boolean hasFollowers) {
499 ReplicatedLogEntry entry = log.get(originalIndex);
503 if (lastLogEntry != null) {
504 // since we have persisted the last-log-entry to persistent journal before the capture,
505 // we would want to snapshot from this entry.
506 index = lastLogEntry.getIndex();
507 term = lastLogEntry.getTerm();
509 } else if (entry != null) {
510 index = entry.getIndex();
511 term = entry.getTerm();
512 } else if (log.getSnapshotIndex() > -1) {
513 index = log.getSnapshotIndex();
514 term = log.getSnapshotTerm();
520 public long getIndex() {
525 public long getTerm() {
530 private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
534 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex) {
535 ReplicatedLogEntry entry = log.get(originalIndex);
540 index = entry.getIndex();
541 term = entry.getTerm();
548 public long getIndex() {
553 public long getTerm() {