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(final byte[] snapshotBytes, final long totalMemory) {
76 currentState.persist(snapshotBytes, totalMemory);
80 public void commit(final long sequenceNumber) {
81 currentState.commit(sequenceNumber);
85 public void rollback() {
86 currentState.rollback();
90 public long trimLog(final long desiredTrimIndex) {
91 return currentState.trimLog(desiredTrimIndex);
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 public CaptureSnapshot newCaptureSnapshot(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex,
120 boolean installSnapshotInitiated) {
121 TermInformationReader lastAppliedTermInfoReader =
122 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
123 lastLogEntry, hasFollowers());
125 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
126 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
128 TermInformationReader replicatedToAllTermInfoReader =
129 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
131 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
132 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
134 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
136 long lastLogEntryIndex = lastAppliedIndex;
137 long lastLogEntryTerm = lastAppliedTerm;
138 if(lastLogEntry != null) {
139 lastLogEntryIndex = lastLogEntry.getIndex();
140 lastLogEntryTerm = lastLogEntry.getTerm();
142 LOG.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
143 persistenceId(), lastAppliedIndex, lastAppliedTerm);
146 return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
147 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, installSnapshotInitiated);
150 private class AbstractSnapshotState implements SnapshotState {
153 public boolean isCapturing() {
158 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
159 LOG.debug("capture should not be called in state {}", this);
164 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
165 LOG.debug("captureToInstall should not be called in state {}", this);
170 public void apply(ApplySnapshot snapshot) {
171 LOG.debug("apply should not be called in state {}", this);
175 public void persist(final byte[] snapshotBytes, final long totalMemory) {
176 LOG.debug("persist should not be called in state {}", this);
180 public void commit(final long sequenceNumber) {
181 LOG.debug("commit should not be called in state {}", this);
185 public void rollback() {
186 LOG.debug("rollback should not be called in state {}", this);
190 public long trimLog(final long desiredTrimIndex) {
191 LOG.debug("trimLog should not be called in state {}", this);
195 protected long doTrimLog(final long desiredTrimIndex) {
196 // we would want to keep the lastApplied as its used while capturing snapshots
197 long lastApplied = context.getLastApplied();
198 long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
200 if(LOG.isTraceEnabled()) {
201 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
202 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
205 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
206 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
207 context.getTermInformation().getCurrentTerm());
209 //use the term of the temp-min, since we check for isPresent, entry will not be null
210 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
211 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
212 context.getReplicatedLog().snapshotCommit();
216 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
217 if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
218 // It's possible a follower was lagging and an install snapshot advanced its match index past
219 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
220 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
221 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
222 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
223 currentBehavior.setReplicatedToAllIndex(tempMin);
229 private class Idle extends AbstractSnapshotState {
232 public boolean isCapturing() {
236 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
237 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, targetFollower != null);
239 if(captureSnapshot.isInstallSnapshotInitiated()) {
240 LOG.info("{}: Initiating snapshot capture {} to install on {}",
241 persistenceId(), captureSnapshot, targetFollower);
243 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
246 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
248 LOG.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
250 SnapshotManager.this.currentState = CREATING;
253 createSnapshotProcedure.apply(null);
254 } catch (Exception e) {
255 SnapshotManager.this.currentState = IDLE;
256 LOG.error("Error creating snapshot", e);
264 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
265 return capture(lastLogEntry, replicatedToAllIndex, null);
269 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
270 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
274 public void apply(ApplySnapshot applySnapshot) {
275 SnapshotManager.this.applySnapshot = applySnapshot;
277 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
279 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
281 context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
283 SnapshotManager.this.currentState = PERSISTING;
287 public String toString() {
292 public long trimLog(final long desiredTrimIndex) {
293 return doTrimLog(desiredTrimIndex);
297 private class Creating extends AbstractSnapshotState {
300 public void persist(final byte[] snapshotBytes, final long totalMemory) {
301 // create a snapshot object from the state provided and save it
302 // when snapshot is saved async, SaveSnapshotSuccess is raised.
304 Snapshot snapshot = Snapshot.create(snapshotBytes,
305 captureSnapshot.getUnAppliedEntries(),
306 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
307 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
308 context.getTermInformation().getCurrentTerm(),
309 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
311 context.getPersistenceProvider().saveSnapshot(snapshot);
313 LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
315 long dataThreshold = totalMemory *
316 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
317 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
319 boolean logSizeExceededSnapshotBatchCount =
320 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
322 final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
323 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
324 if(LOG.isDebugEnabled()) {
325 if(dataSizeThresholdExceeded) {
326 LOG.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
327 context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
328 captureSnapshot.getLastAppliedIndex());
330 LOG.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
331 context.getId(), context.getReplicatedLog().size(),
332 context.getConfigParams().getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
336 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
337 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
338 // This could/should only happen if one of the followers is down as normally we keep
339 // removing from the log as entries are replicated to all.
340 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
341 captureSnapshot.getLastAppliedTerm());
343 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
344 // install snapshot to a follower.
345 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
346 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
349 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
350 // clear the log based on replicatedToAllIndex
351 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
352 captureSnapshot.getReplicatedToAllTerm());
354 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
356 // The replicatedToAllIndex was not found in the log
357 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
358 // In this scenario we may need to save the snapshot to the akka persistence
359 // snapshot for recovery but we do not need to do the replicated log trimming.
360 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
361 context.getReplicatedLog().getSnapshotTerm());
364 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
365 "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
366 context.getReplicatedLog().getSnapshotTerm());
368 if (context.getId().equals(currentBehavior.getLeaderId())
369 && captureSnapshot.isInstallSnapshotInitiated()) {
370 // this would be call straight to the leader and won't initiate in serialization
371 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
374 captureSnapshot = null;
375 SnapshotManager.this.currentState = PERSISTING;
379 public String toString() {
385 private class Persisting extends AbstractSnapshotState {
388 public void commit(final long sequenceNumber) {
389 LOG.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
391 if(applySnapshot != null) {
393 Snapshot snapshot = applySnapshot.getSnapshot();
395 //clears the followers log, sets the snapshot index to ensure adjusted-index works
396 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
397 context.setLastApplied(snapshot.getLastAppliedIndex());
398 context.setCommitIndex(snapshot.getLastAppliedIndex());
399 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
401 if(snapshot.getState().length > 0 ) {
402 applySnapshotProcedure.apply(snapshot.getState());
405 applySnapshot.getCallback().onSuccess();
406 } catch (Exception e) {
407 LOG.error("{}: Error applying snapshot", context.getId(), e);
410 context.getReplicatedLog().snapshotCommit();
413 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
414 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), Long.MAX_VALUE, 0L, 0L));
416 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
422 public void rollback() {
423 // Nothing to rollback if we're applying a snapshot from the leader.
424 if(applySnapshot == null) {
425 context.getReplicatedLog().snapshotRollback();
427 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
428 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
429 context.getReplicatedLog().getSnapshotIndex(),
430 context.getReplicatedLog().getSnapshotTerm(),
431 context.getReplicatedLog().size());
433 applySnapshot.getCallback().onFailure();
439 private void snapshotComplete() {
440 lastSequenceNumber = -1;
441 applySnapshot = null;
442 SnapshotManager.this.currentState = IDLE;
444 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
448 public String toString() {
454 private static interface TermInformationReader {
459 static class LastAppliedTermInformationReader implements TermInformationReader{
463 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
464 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
465 ReplicatedLogEntry entry = log.get(originalIndex);
469 if(lastLogEntry != null) {
470 // since we have persisted the last-log-entry to persistent journal before the capture,
471 // we would want to snapshot from this entry.
472 index = lastLogEntry.getIndex();
473 term = lastLogEntry.getTerm();
475 } else if (entry != null) {
476 index = entry.getIndex();
477 term = entry.getTerm();
478 } else if(log.getSnapshotIndex() > -1){
479 index = log.getSnapshotIndex();
480 term = log.getSnapshotTerm();
486 public long getIndex(){
491 public long getTerm(){
496 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
500 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
501 ReplicatedLogEntry entry = log.get(originalIndex);
506 index = entry.getIndex();
507 term = entry.getTerm();
514 public long getIndex(){
519 public long getTerm(){