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 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(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
176 LOG.debug("persist should not be called in state {}", this);
180 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
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(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
191 LOG.debug("trimLog should not be called in state {}", this);
195 protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){
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();
214 } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
215 // It's possible a follower was lagging and an install snapshot advanced its match index past
216 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
217 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
218 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
219 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
220 currentBehavior.setReplicatedToAllIndex(tempMin);
226 private class Idle extends AbstractSnapshotState {
229 public boolean isCapturing() {
233 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
234 captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex, targetFollower != null);
236 if(captureSnapshot.isInstallSnapshotInitiated()) {
237 LOG.info("{}: Initiating snapshot capture {} to install on {}",
238 persistenceId(), captureSnapshot, targetFollower);
240 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
243 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
245 LOG.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
247 SnapshotManager.this.currentState = CREATING;
250 createSnapshotProcedure.apply(null);
251 } catch (Exception e) {
252 SnapshotManager.this.currentState = IDLE;
253 LOG.error("Error creating snapshot", e);
261 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
262 return capture(lastLogEntry, replicatedToAllIndex, null);
266 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
267 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
271 public void apply(ApplySnapshot applySnapshot) {
272 SnapshotManager.this.applySnapshot = applySnapshot;
274 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
276 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
278 context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
280 SnapshotManager.this.currentState = PERSISTING;
284 public String toString() {
289 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
290 return doTrimLog(desiredTrimIndex, currentBehavior);
294 private class Creating extends AbstractSnapshotState {
297 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
298 // create a snapshot object from the state provided and save it
299 // when snapshot is saved async, SaveSnapshotSuccess is raised.
301 Snapshot snapshot = Snapshot.create(snapshotBytes,
302 captureSnapshot.getUnAppliedEntries(),
303 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
304 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
305 context.getTermInformation().getCurrentTerm(),
306 context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
308 context.getPersistenceProvider().saveSnapshot(snapshot);
310 LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
312 long dataThreshold = totalMemory *
313 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
314 boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
316 boolean logSizeExceededSnapshotBatchCount =
317 context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
319 if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
320 if(LOG.isDebugEnabled()) {
321 if(dataSizeThresholdExceeded) {
322 LOG.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit with index {}",
323 context.getId(), context.getReplicatedLog().dataSize(), dataThreshold,
324 captureSnapshot.getLastAppliedIndex());
326 LOG.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with index {}",
327 context.getId(), context.getReplicatedLog().size(),
328 context.getConfigParams().getSnapshotBatchCount(), captureSnapshot.getLastAppliedIndex());
332 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
333 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
334 // This could/should only happen if one of the followers is down as normally we keep
335 // removing from the log as entries are replicated to all.
336 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
337 captureSnapshot.getLastAppliedTerm());
339 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
340 // install snapshot to a follower.
341 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
342 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
345 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
346 // clear the log based on replicatedToAllIndex
347 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
348 captureSnapshot.getReplicatedToAllTerm());
350 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
352 // The replicatedToAllIndex was not found in the log
353 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
354 // In this scenario we may need to save the snapshot to the akka persistence
355 // snapshot for recovery but we do not need to do the replicated log trimming.
356 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
357 context.getReplicatedLog().getSnapshotTerm());
360 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
361 "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
362 context.getReplicatedLog().getSnapshotTerm());
364 if (context.getId().equals(currentBehavior.getLeaderId())
365 && captureSnapshot.isInstallSnapshotInitiated()) {
366 // this would be call straight to the leader and won't initiate in serialization
367 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
370 captureSnapshot = null;
371 SnapshotManager.this.currentState = PERSISTING;
375 public String toString() {
381 private class Persisting extends AbstractSnapshotState {
384 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
385 LOG.debug("{}: Snapshot success - sequence number: {}", persistenceId(), sequenceNumber);
387 if(applySnapshot != null) {
389 Snapshot snapshot = applySnapshot.getSnapshot();
391 //clears the followers log, sets the snapshot index to ensure adjusted-index works
392 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior));
393 context.setLastApplied(snapshot.getLastAppliedIndex());
394 context.setCommitIndex(snapshot.getLastAppliedIndex());
395 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
397 if(snapshot.getState().length > 0 ) {
398 applySnapshotProcedure.apply(snapshot.getState());
401 applySnapshot.getCallback().onSuccess();
402 } catch (Exception e) {
403 LOG.error("{}: Error applying snapshot", context.getId(), e);
406 context.getReplicatedLog().snapshotCommit();
409 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
410 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), Long.MAX_VALUE));
412 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
418 public void rollback() {
419 // Nothing to rollback if we're applying a snapshot from the leader.
420 if(applySnapshot == null) {
421 context.getReplicatedLog().snapshotRollback();
423 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
424 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
425 context.getReplicatedLog().getSnapshotIndex(),
426 context.getReplicatedLog().getSnapshotTerm(),
427 context.getReplicatedLog().size());
429 applySnapshot.getCallback().onFailure();
435 private void snapshotComplete() {
436 lastSequenceNumber = -1;
437 applySnapshot = null;
438 SnapshotManager.this.currentState = IDLE;
440 context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
444 public String toString() {
450 private static interface TermInformationReader {
455 static class LastAppliedTermInformationReader implements TermInformationReader{
459 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
460 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
461 ReplicatedLogEntry entry = log.get(originalIndex);
465 if(lastLogEntry != null) {
466 // since we have persisted the last-log-entry to persistent journal before the capture,
467 // we would want to snapshot from this entry.
468 index = lastLogEntry.getIndex();
469 term = lastLogEntry.getTerm();
471 } else if (entry != null) {
472 index = entry.getIndex();
473 term = entry.getTerm();
474 } else if(log.getSnapshotIndex() > -1){
475 index = log.getSnapshotIndex();
476 term = log.getSnapshotTerm();
482 public long getIndex(){
487 public long getTerm(){
492 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
496 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
497 ReplicatedLogEntry entry = log.get(originalIndex);
502 index = entry.getIndex();
503 term = entry.getTerm();
510 public long getIndex(){
515 public long getTerm(){