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.CaptureSnapshot;
16 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
17 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
18 import org.slf4j.Logger;
20 public class SnapshotManager implements SnapshotState {
22 private final SnapshotState IDLE = new Idle();
23 private final SnapshotState PERSISTING = new Persisting();
24 private final SnapshotState CREATING = new Creating();
26 private final Logger LOG;
27 private final RaftActorContext context;
28 private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
29 new LastAppliedTermInformationReader();
30 private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
31 new ReplicatedToAllTermInformationReader();
34 private SnapshotState currentState = IDLE;
35 private CaptureSnapshot captureSnapshot;
36 private long lastSequenceNumber = -1;
38 private Procedure<Void> createSnapshotProcedure;
40 private Snapshot applySnapshot;
41 private Procedure<byte[]> applySnapshotProcedure;
43 public SnapshotManager(RaftActorContext context, Logger logger) {
44 this.context = context;
49 public boolean isCapturing() {
50 return currentState.isCapturing();
54 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
55 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
59 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
60 return currentState.capture(lastLogEntry, replicatedToAllIndex);
64 public void apply(Snapshot snapshot) {
65 currentState.apply(snapshot);
69 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
70 currentState.persist(snapshotBytes, currentBehavior, totalMemory);
74 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
75 currentState.commit(sequenceNumber, currentBehavior);
79 public void rollback() {
80 currentState.rollback();
84 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
85 return currentState.trimLog(desiredTrimIndex, currentBehavior);
88 public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
89 this.createSnapshotProcedure = createSnapshotProcedure;
92 public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
93 this.applySnapshotProcedure = applySnapshotProcedure;
96 public long getLastSequenceNumber() {
97 return lastSequenceNumber;
101 public CaptureSnapshot getCaptureSnapshot() {
102 return captureSnapshot;
105 private boolean hasFollowers(){
106 return context.getPeerAddresses().keySet().size() > 0;
109 private String persistenceId(){
110 return context.getId();
113 private class AbstractSnapshotState implements SnapshotState {
116 public boolean isCapturing() {
121 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
122 LOG.debug("capture should not be called in state {}", this);
127 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
128 LOG.debug("captureToInstall should not be called in state {}", this);
133 public void apply(Snapshot snapshot) {
134 LOG.debug("apply should not be called in state {}", this);
138 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
139 LOG.debug("persist should not be called in state {}", this);
143 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
144 LOG.debug("commit should not be called in state {}", this);
148 public void rollback() {
149 LOG.debug("rollback should not be called in state {}", this);
153 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
154 LOG.debug("trimLog should not be called in state {}", this);
158 protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){
159 // we would want to keep the lastApplied as its used while capturing snapshots
160 long lastApplied = context.getLastApplied();
161 long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
163 if(LOG.isTraceEnabled()) {
164 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
165 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
168 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
169 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
170 context.getTermInformation().getCurrentTerm());
172 //use the term of the temp-min, since we check for isPresent, entry will not be null
173 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
174 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
175 context.getReplicatedLog().snapshotCommit();
177 } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
178 // It's possible a follower was lagging and an install snapshot advanced its match index past
179 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
180 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
181 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
182 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
183 currentBehavior.setReplicatedToAllIndex(tempMin);
189 private class Idle extends AbstractSnapshotState {
191 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
192 TermInformationReader lastAppliedTermInfoReader =
193 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
194 lastLogEntry, hasFollowers());
196 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
197 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
199 TermInformationReader replicatedToAllTermInfoReader =
200 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
202 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
203 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
205 // send a CaptureSnapshot to self to make the expensive operation async.
207 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
209 captureSnapshot = new CaptureSnapshot(lastLogEntry.getIndex(),
210 lastLogEntry.getTerm(), lastAppliedIndex, lastAppliedTerm,
211 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
213 if(captureSnapshot.isInstallSnapshotInitiated()) {
214 LOG.info("{}: Initiating snapshot capture {} to install on {}",
215 persistenceId(), captureSnapshot, targetFollower);
217 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
220 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
222 LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
224 SnapshotManager.this.currentState = CREATING;
227 createSnapshotProcedure.apply(null);
228 } catch (Exception e) {
229 SnapshotManager.this.currentState = IDLE;
230 LOG.error("Error creating snapshot", e);
238 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
239 return capture(lastLogEntry, replicatedToAllIndex, null);
243 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
244 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
248 public void apply(Snapshot snapshot) {
249 applySnapshot = snapshot;
251 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
253 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
255 context.getPersistenceProvider().saveSnapshot(snapshot);
257 SnapshotManager.this.currentState = PERSISTING;
261 public String toString() {
266 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
267 return doTrimLog(desiredTrimIndex, currentBehavior);
271 private class Creating extends AbstractSnapshotState {
274 public boolean isCapturing() {
279 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
280 // create a snapshot object from the state provided and save it
281 // when snapshot is saved async, SaveSnapshotSuccess is raised.
283 Snapshot snapshot = Snapshot.create(snapshotBytes,
284 captureSnapshot.getUnAppliedEntries(),
285 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
286 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
288 context.getPersistenceProvider().saveSnapshot(snapshot);
290 LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), snapshot.getLogMessage());
292 long dataThreshold = totalMemory *
293 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
294 if (context.getReplicatedLog().dataSize() > dataThreshold) {
296 if(LOG.isDebugEnabled()) {
297 LOG.debug("{}: dataSize {} exceeds dataThreshold {} - doing snapshotPreCommit with index {}",
298 persistenceId(), context.getReplicatedLog().dataSize(), dataThreshold,
299 captureSnapshot.getLastAppliedIndex());
302 // if memory is less, clear the log based on lastApplied.
303 // this could/should only happen if one of the followers is down
304 // as normally we keep removing from the log when its replicated to all.
305 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
306 captureSnapshot.getLastAppliedTerm());
308 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
309 // install snapshot to a follower.
310 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
311 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
314 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
315 // clear the log based on replicatedToAllIndex
316 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
317 captureSnapshot.getReplicatedToAllTerm());
319 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
321 // The replicatedToAllIndex was not found in the log
322 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
323 // In this scenario we may need to save the snapshot to the akka persistence
324 // snapshot for recovery but we do not need to do the replicated log trimming.
325 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
326 context.getReplicatedLog().getSnapshotTerm());
329 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
330 "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
331 captureSnapshot.getLastAppliedTerm());
333 if (context.getId().equals(currentBehavior.getLeaderId())
334 && captureSnapshot.isInstallSnapshotInitiated()) {
335 // this would be call straight to the leader and won't initiate in serialization
336 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(snapshot));
339 captureSnapshot = null;
340 SnapshotManager.this.currentState = PERSISTING;
344 public String toString() {
350 private class Persisting extends AbstractSnapshotState {
353 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
354 LOG.debug("Snapshot success sequence number:", sequenceNumber);
356 if(applySnapshot != null) {
358 applySnapshotProcedure.apply(applySnapshot.getState());
360 //clears the followers log, sets the snapshot index to ensure adjusted-index works
361 context.setReplicatedLog(ReplicatedLogImpl.newInstance(applySnapshot, context, currentBehavior));
362 context.setLastApplied(applySnapshot.getLastAppliedIndex());
363 context.setCommitIndex(applySnapshot.getLastAppliedIndex());
364 } catch (Exception e) {
365 LOG.error("Error applying snapshot", e);
368 context.getReplicatedLog().snapshotCommit();
371 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
372 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
374 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
376 lastSequenceNumber = -1;
377 applySnapshot = null;
378 SnapshotManager.this.currentState = IDLE;
382 public void rollback() {
383 // Nothing to rollback if we're applying a snapshot from the leader.
384 if(applySnapshot == null) {
385 context.getReplicatedLog().snapshotRollback();
387 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
388 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
389 context.getReplicatedLog().getSnapshotIndex(),
390 context.getReplicatedLog().getSnapshotTerm(),
391 context.getReplicatedLog().size());
394 lastSequenceNumber = -1;
395 applySnapshot = null;
396 SnapshotManager.this.currentState = IDLE;
400 public String toString() {
406 private static interface TermInformationReader {
411 static class LastAppliedTermInformationReader implements TermInformationReader{
415 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
416 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
417 ReplicatedLogEntry entry = log.get(originalIndex);
421 if(lastLogEntry != null) {
422 // since we have persisted the last-log-entry to persistent journal before the capture,
423 // we would want to snapshot from this entry.
424 index = lastLogEntry.getIndex();
425 term = lastLogEntry.getTerm();
427 } else if (entry != null) {
428 index = entry.getIndex();
429 term = entry.getTerm();
430 } else if(log.getSnapshotIndex() > -1){
431 index = log.getSnapshotIndex();
432 term = log.getSnapshotTerm();
438 public long getIndex(){
443 public long getTerm(){
448 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
452 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
453 ReplicatedLogEntry entry = log.get(originalIndex);
458 index = entry.getIndex();
459 term = entry.getTerm();
466 public long getIndex(){
471 public long getTerm(){