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.japi.Procedure;
12 import akka.persistence.SnapshotSelectionCriteria;
13 import com.google.common.annotations.VisibleForTesting;
14 import java.util.List;
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.behaviors.RaftActorBehavior;
19 import org.slf4j.Logger;
21 public class SnapshotManager implements SnapshotState {
23 private final SnapshotState IDLE = new Idle();
24 private final SnapshotState PERSISTING = new Persisting();
25 private final SnapshotState CREATING = new Creating();
27 private final Logger LOG;
28 private final RaftActorContext context;
29 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
30 new LastAppliedTermInformationReader();
31 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
32 new ReplicatedToAllTermInformationReader();
35 private SnapshotState currentState = IDLE;
36 private CaptureSnapshot captureSnapshot;
37 private long lastSequenceNumber = -1;
39 private Procedure<Void> createSnapshotProcedure;
41 private ApplySnapshot applySnapshot;
42 private Procedure<byte[]> applySnapshotProcedure;
44 public SnapshotManager(RaftActorContext context, Logger logger) {
45 this.context = context;
49 public boolean isApplying() {
50 return applySnapshot != null;
54 public boolean isCapturing() {
55 return currentState.isCapturing();
59 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
60 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
64 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
65 return currentState.capture(lastLogEntry, replicatedToAllIndex);
69 public void apply(ApplySnapshot snapshot) {
70 currentState.apply(snapshot);
74 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
75 currentState.persist(snapshotBytes, currentBehavior, totalMemory);
79 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
80 currentState.commit(sequenceNumber, currentBehavior);
84 public void rollback() {
85 currentState.rollback();
89 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
90 return currentState.trimLog(desiredTrimIndex, currentBehavior);
93 public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
94 this.createSnapshotProcedure = createSnapshotProcedure;
97 public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
98 this.applySnapshotProcedure = applySnapshotProcedure;
101 public long getLastSequenceNumber() {
102 return lastSequenceNumber;
106 public CaptureSnapshot getCaptureSnapshot() {
107 return captureSnapshot;
110 private boolean hasFollowers(){
111 return context.hasFollowers();
114 private String persistenceId(){
115 return context.getId();
118 private class AbstractSnapshotState implements SnapshotState {
121 public boolean isCapturing() {
126 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
127 LOG.debug("capture should not be called in state {}", this);
132 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
133 LOG.debug("captureToInstall should not be called in state {}", this);
138 public void apply(ApplySnapshot snapshot) {
139 LOG.debug("apply should not be called in state {}", this);
143 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
144 LOG.debug("persist should not be called in state {}", this);
148 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
149 LOG.debug("commit should not be called in state {}", this);
153 public void rollback() {
154 LOG.debug("rollback should not be called in state {}", this);
158 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
159 LOG.debug("trimLog should not be called in state {}", this);
163 protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){
164 // we would want to keep the lastApplied as its used while capturing snapshots
165 long lastApplied = context.getLastApplied();
166 long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
168 if(LOG.isTraceEnabled()) {
169 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
170 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
173 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
174 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
175 context.getTermInformation().getCurrentTerm());
177 //use the term of the temp-min, since we check for isPresent, entry will not be null
178 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
179 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
180 context.getReplicatedLog().snapshotCommit();
182 } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
183 // It's possible a follower was lagging and an install snapshot advanced its match index past
184 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
185 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
186 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
187 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
188 currentBehavior.setReplicatedToAllIndex(tempMin);
194 private class Idle extends AbstractSnapshotState {
197 public boolean isCapturing() {
201 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
202 TermInformationReader lastAppliedTermInfoReader =
203 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
204 lastLogEntry, hasFollowers());
206 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
207 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
209 TermInformationReader replicatedToAllTermInfoReader =
210 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
212 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
213 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
215 // send a CaptureSnapshot to self to make the expensive operation async.
217 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
219 long lastLogEntryIndex = lastAppliedIndex;
220 long lastLogEntryTerm = lastAppliedTerm;
221 if(lastLogEntry != null) {
222 lastLogEntryIndex = lastLogEntry.getIndex();
223 lastLogEntryTerm = lastLogEntry.getTerm();
225 LOG.warn("Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
226 lastAppliedIndex, lastAppliedTerm);
229 captureSnapshot = new CaptureSnapshot(lastLogEntryIndex,
230 lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
231 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
233 if(captureSnapshot.isInstallSnapshotInitiated()) {
234 LOG.info("{}: Initiating snapshot capture {} to install on {}",
235 persistenceId(), captureSnapshot, targetFollower);
237 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
240 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
242 LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
244 SnapshotManager.this.currentState = CREATING;
247 createSnapshotProcedure.apply(null);
248 } catch (Exception e) {
249 SnapshotManager.this.currentState = IDLE;
250 LOG.error("Error creating snapshot", e);
258 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
259 return capture(lastLogEntry, replicatedToAllIndex, null);
263 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
264 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
268 public void apply(ApplySnapshot applySnapshot) {
269 SnapshotManager.this.applySnapshot = applySnapshot;
271 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
273 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
275 context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
277 SnapshotManager.this.currentState = PERSISTING;
281 public String toString() {
286 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
287 return doTrimLog(desiredTrimIndex, currentBehavior);
291 private class Creating extends AbstractSnapshotState {
294 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
295 // create a snapshot object from the state provided and save it
296 // when snapshot is saved async, SaveSnapshotSuccess is raised.
298 Snapshot snapshot = Snapshot.create(snapshotBytes,
299 captureSnapshot.getUnAppliedEntries(),
300 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
301 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
302 context.getTermInformation().getCurrentTerm(),
303 context.getTermInformation().getVotedFor());
305 context.getPersistenceProvider().saveSnapshot(snapshot);
307 LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
309 long dataThreshold = totalMemory *
310 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
311 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
313 boolean logSizeExceededSnapshotBatchCount =
314 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
316 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
317 if(LOG.isDebugEnabled()) {
318 if(dataSizeThresholdExceeded) {
319 LOG.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
320 context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
321 captureSnapshot.getLastAppliedIndex());
323 LOG.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
324 context.getId(), context.getReplicatedLog().size(),
325 context.getConfigParams().getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
329 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
330 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
331 // This could/should only happen if one of the followers is down as normally we keep
332 // removing from the log as entries are replicated to all.
333 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
334 captureSnapshot.getLastAppliedTerm());
336 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
337 // install snapshot to a follower.
338 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
339 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
342 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
343 // clear the log based on replicatedToAllIndex
344 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
345 captureSnapshot.getReplicatedToAllTerm());
347 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
349 // The replicatedToAllIndex was not found in the log
350 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
351 // In this scenario we may need to save the snapshot to the akka persistence
352 // snapshot for recovery but we do not need to do the replicated log trimming.
353 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
354 context.getReplicatedLog().getSnapshotTerm());
357 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
358 "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
359 context.getReplicatedLog().getSnapshotTerm());
361 if (context.getId().equals(currentBehavior.getLeaderId())
362 && captureSnapshot.isInstallSnapshotInitiated()) {
363 // this would be call straight to the leader and won't initiate in serialization
364 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
367 captureSnapshot = null;
368 SnapshotManager.this.currentState = PERSISTING;
372 public String toString() {
378 private class Persisting extends AbstractSnapshotState {
381 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
382 LOG.debug("Snapshot success sequence number: {}", sequenceNumber);
384 if(applySnapshot != null) {
386 Snapshot snapshot = applySnapshot.getSnapshot();
387 applySnapshotProcedure.apply(snapshot.getState());
389 //clears the followers log, sets the snapshot index to ensure adjusted-index works
390 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior));
391 context.setLastApplied(snapshot.getLastAppliedIndex());
392 context.setCommitIndex(snapshot.getLastAppliedIndex());
394 applySnapshot.getCallback().onSuccess();
395 } catch (Exception e) {
396 LOG.error("Error applying snapshot", e);
399 context.getReplicatedLog().snapshotCommit();
402 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
403 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
405 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
407 lastSequenceNumber = -1;
408 applySnapshot = null;
409 SnapshotManager.this.currentState = IDLE;
413 public void rollback() {
414 // Nothing to rollback if we're applying a snapshot from the leader.
415 if(applySnapshot == null) {
416 context.getReplicatedLog().snapshotRollback();
418 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
419 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
420 context.getReplicatedLog().getSnapshotIndex(),
421 context.getReplicatedLog().getSnapshotTerm(),
422 context.getReplicatedLog().size());
424 applySnapshot.getCallback().onFailure();
427 lastSequenceNumber = -1;
428 applySnapshot = null;
429 SnapshotManager.this.currentState = IDLE;
433 public String toString() {
439 private static interface TermInformationReader {
444 static class LastAppliedTermInformationReader implements TermInformationReader{
448 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
449 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
450 ReplicatedLogEntry entry = log.get(originalIndex);
454 if(lastLogEntry != null) {
455 // since we have persisted the last-log-entry to persistent journal before the capture,
456 // we would want to snapshot from this entry.
457 index = lastLogEntry.getIndex();
458 term = lastLogEntry.getTerm();
460 } else if (entry != null) {
461 index = entry.getIndex();
462 term = entry.getTerm();
463 } else if(log.getSnapshotIndex() > -1){
464 index = log.getSnapshotIndex();
465 term = log.getSnapshotTerm();
471 public long getIndex(){
476 public long getTerm(){
481 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
485 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
486 ReplicatedLogEntry entry = log.get(originalIndex);
491 index = entry.getIndex();
492 term = entry.getTerm();
499 public long getIndex(){
504 public long getTerm(){