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.base.messages.SnapshotComplete;
19 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
20 import org.slf4j.Logger;
22 public class SnapshotManager implements SnapshotState {
24 private final SnapshotState IDLE = new Idle();
25 private final SnapshotState PERSISTING = new Persisting();
26 private final SnapshotState CREATING = new Creating();
28 private final Logger LOG;
29 private final RaftActorContext context;
30 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
31 new LastAppliedTermInformationReader();
32 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
33 new ReplicatedToAllTermInformationReader();
36 private SnapshotState currentState = IDLE;
37 private CaptureSnapshot captureSnapshot;
38 private long lastSequenceNumber = -1;
40 private Procedure<Void> createSnapshotProcedure;
42 private ApplySnapshot applySnapshot;
43 private Procedure<byte[]> applySnapshotProcedure;
45 public SnapshotManager(RaftActorContext context, Logger logger) {
46 this.context = context;
50 public boolean isApplying() {
51 return applySnapshot != null;
55 public boolean isCapturing() {
56 return currentState.isCapturing();
60 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
61 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
65 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
66 return currentState.capture(lastLogEntry, replicatedToAllIndex);
70 public void apply(ApplySnapshot snapshot) {
71 currentState.apply(snapshot);
75 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
76 currentState.persist(snapshotBytes, currentBehavior, totalMemory);
80 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
81 currentState.commit(sequenceNumber, currentBehavior);
85 public void rollback() {
86 currentState.rollback();
90 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
91 return currentState.trimLog(desiredTrimIndex, currentBehavior);
94 public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
95 this.createSnapshotProcedure = createSnapshotProcedure;
98 public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
99 this.applySnapshotProcedure = applySnapshotProcedure;
102 public long getLastSequenceNumber() {
103 return lastSequenceNumber;
107 public CaptureSnapshot getCaptureSnapshot() {
108 return captureSnapshot;
111 private boolean hasFollowers(){
112 return context.hasFollowers();
115 private String persistenceId(){
116 return context.getId();
119 private class AbstractSnapshotState implements SnapshotState {
122 public boolean isCapturing() {
127 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
128 LOG.debug("capture should not be called in state {}", this);
133 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
134 LOG.debug("captureToInstall should not be called in state {}", this);
139 public void apply(ApplySnapshot snapshot) {
140 LOG.debug("apply should not be called in state {}", this);
144 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
145 LOG.debug("persist should not be called in state {}", this);
149 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
150 LOG.debug("commit should not be called in state {}", this);
154 public void rollback() {
155 LOG.debug("rollback should not be called in state {}", this);
159 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
160 LOG.debug("trimLog should not be called in state {}", this);
164 protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){
165 // we would want to keep the lastApplied as its used while capturing snapshots
166 long lastApplied = context.getLastApplied();
167 long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
169 if(LOG.isTraceEnabled()) {
170 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
171 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
174 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
175 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
176 context.getTermInformation().getCurrentTerm());
178 //use the term of the temp-min, since we check for isPresent, entry will not be null
179 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
180 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
181 context.getReplicatedLog().snapshotCommit();
183 } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
184 // It's possible a follower was lagging and an install snapshot advanced its match index past
185 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
186 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
187 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
188 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
189 currentBehavior.setReplicatedToAllIndex(tempMin);
195 private class Idle extends AbstractSnapshotState {
198 public boolean isCapturing() {
202 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
203 TermInformationReader lastAppliedTermInfoReader =
204 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
205 lastLogEntry, hasFollowers());
207 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
208 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
210 TermInformationReader replicatedToAllTermInfoReader =
211 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
213 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
214 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
216 // send a CaptureSnapshot to self to make the expensive operation async.
218 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
220 long lastLogEntryIndex = lastAppliedIndex;
221 long lastLogEntryTerm = lastAppliedTerm;
222 if(lastLogEntry != null) {
223 lastLogEntryIndex = lastLogEntry.getIndex();
224 lastLogEntryTerm = lastLogEntry.getTerm();
226 LOG.warn("Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
227 lastAppliedIndex, lastAppliedTerm);
230 captureSnapshot = new CaptureSnapshot(lastLogEntryIndex,
231 lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
232 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
234 if(captureSnapshot.isInstallSnapshotInitiated()) {
235 LOG.info("{}: Initiating snapshot capture {} to install on {}",
236 persistenceId(), captureSnapshot, targetFollower);
238 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
241 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
243 LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
245 SnapshotManager.this.currentState = CREATING;
248 createSnapshotProcedure.apply(null);
249 } catch (Exception e) {
250 SnapshotManager.this.currentState = IDLE;
251 LOG.error("Error creating snapshot", e);
259 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
260 return capture(lastLogEntry, replicatedToAllIndex, null);
264 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
265 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
269 public void apply(ApplySnapshot applySnapshot) {
270 SnapshotManager.this.applySnapshot = applySnapshot;
272 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
274 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
276 context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
278 SnapshotManager.this.currentState = PERSISTING;
282 public String toString() {
287 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
288 return doTrimLog(desiredTrimIndex, currentBehavior);
292 private class Creating extends AbstractSnapshotState {
295 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
296 // create a snapshot object from the state provided and save it
297 // when snapshot is saved async, SaveSnapshotSuccess is raised.
299 Snapshot snapshot = Snapshot.create(snapshotBytes,
300 captureSnapshot.getUnAppliedEntries(),
301 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
302 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
303 context.getTermInformation().getCurrentTerm(),
304 context.getTermInformation().getVotedFor());
306 context.getPersistenceProvider().saveSnapshot(snapshot);
308 LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
310 long dataThreshold = totalMemory *
311 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
312 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
314 boolean logSizeExceededSnapshotBatchCount =
315 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
317 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
318 if(LOG.isDebugEnabled()) {
319 if(dataSizeThresholdExceeded) {
320 LOG.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
321 context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
322 captureSnapshot.getLastAppliedIndex());
324 LOG.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
325 context.getId(), context.getReplicatedLog().size(),
326 context.getConfigParams().getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
330 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
331 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
332 // This could/should only happen if one of the followers is down as normally we keep
333 // removing from the log as entries are replicated to all.
334 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
335 captureSnapshot.getLastAppliedTerm());
337 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
338 // install snapshot to a follower.
339 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
340 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
343 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
344 // clear the log based on replicatedToAllIndex
345 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
346 captureSnapshot.getReplicatedToAllTerm());
348 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
350 // The replicatedToAllIndex was not found in the log
351 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
352 // In this scenario we may need to save the snapshot to the akka persistence
353 // snapshot for recovery but we do not need to do the replicated log trimming.
354 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
355 context.getReplicatedLog().getSnapshotTerm());
358 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
359 "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
360 context.getReplicatedLog().getSnapshotTerm());
362 if (context.getId().equals(currentBehavior.getLeaderId())
363 && captureSnapshot.isInstallSnapshotInitiated()) {
364 // this would be call straight to the leader and won't initiate in serialization
365 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
368 captureSnapshot = null;
369 SnapshotManager.this.currentState = PERSISTING;
373 public String toString() {
379 private class Persisting extends AbstractSnapshotState {
382 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
383 LOG.debug("Snapshot success sequence number: {}", sequenceNumber);
385 if(applySnapshot != null) {
387 Snapshot snapshot = applySnapshot.getSnapshot();
388 applySnapshotProcedure.apply(snapshot.getState());
390 //clears the followers log, sets the snapshot index to ensure adjusted-index works
391 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior));
392 context.setLastApplied(snapshot.getLastAppliedIndex());
393 context.setCommitIndex(snapshot.getLastAppliedIndex());
395 applySnapshot.getCallback().onSuccess();
396 } catch (Exception e) {
397 LOG.error("Error applying snapshot", e);
400 context.getReplicatedLog().snapshotCommit();
403 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
404 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
406 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
412 public void rollback() {
413 // Nothing to rollback if we're applying a snapshot from the leader.
414 if(applySnapshot == null) {
415 context.getReplicatedLog().snapshotRollback();
417 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
418 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
419 context.getReplicatedLog().getSnapshotIndex(),
420 context.getReplicatedLog().getSnapshotTerm(),
421 context.getReplicatedLog().size());
423 applySnapshot.getCallback().onFailure();
429 private void snapshotComplete() {
430 lastSequenceNumber = -1;
431 applySnapshot = null;
432 SnapshotManager.this.currentState = IDLE;
434 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
438 public String toString() {
444 private static interface TermInformationReader {
449 static class LastAppliedTermInformationReader implements TermInformationReader{
453 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
454 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
455 ReplicatedLogEntry entry = log.get(originalIndex);
459 if(lastLogEntry != null) {
460 // since we have persisted the last-log-entry to persistent journal before the capture,
461 // we would want to snapshot from this entry.
462 index = lastLogEntry.getIndex();
463 term = lastLogEntry.getTerm();
465 } else if (entry != null) {
466 index = entry.getIndex();
467 term = entry.getTerm();
468 } else if(log.getSnapshotIndex() > -1){
469 index = log.getSnapshotIndex();
470 term = log.getSnapshotTerm();
476 public long getIndex(){
481 public long getTerm(){
486 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
490 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
491 ReplicatedLogEntry entry = log.get(originalIndex);
496 index = entry.getIndex();
497 term = entry.getTerm();
504 public long getIndex(){
509 public long getTerm(){