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 com.google.protobuf.ByteString;
15 import java.util.List;
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 Snapshot applySnapshot;
42 private Procedure<byte[]> applySnapshotProcedure;
44 public SnapshotManager(RaftActorContext context, Logger logger) {
45 this.context = context;
50 public boolean isCapturing() {
51 return currentState.isCapturing();
55 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
56 return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
60 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
61 return currentState.capture(lastLogEntry, replicatedToAllIndex);
65 public void apply(Snapshot snapshot) {
66 currentState.apply(snapshot);
70 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
71 currentState.persist(snapshotBytes, currentBehavior, totalMemory);
75 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
76 currentState.commit(sequenceNumber, currentBehavior);
80 public void rollback() {
81 currentState.rollback();
85 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
86 return currentState.trimLog(desiredTrimIndex, currentBehavior);
89 public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
90 this.createSnapshotProcedure = createSnapshotProcedure;
93 public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
94 this.applySnapshotProcedure = applySnapshotProcedure;
97 public long getLastSequenceNumber() {
98 return lastSequenceNumber;
102 public CaptureSnapshot getCaptureSnapshot() {
103 return captureSnapshot;
106 private boolean hasFollowers(){
107 return context.getPeerAddresses().keySet().size() > 0;
110 private String persistenceId(){
111 return context.getId();
114 private class AbstractSnapshotState implements SnapshotState {
117 public boolean isCapturing() {
122 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
123 LOG.debug("capture should not be called in state {}", this);
128 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
129 LOG.debug("captureToInstall should not be called in state {}", this);
134 public void apply(Snapshot snapshot) {
135 LOG.debug("apply should not be called in state {}", this);
139 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
140 LOG.debug("persist should not be called in state {}", this);
144 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
145 LOG.debug("commit should not be called in state {}", this);
149 public void rollback() {
150 LOG.debug("rollback should not be called in state {}", this);
154 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
155 LOG.debug("trimLog should not be called in state {}", this);
159 protected long doTrimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior){
160 // we would want to keep the lastApplied as its used while capturing snapshots
161 long lastApplied = context.getLastApplied();
162 long tempMin = Math.min(desiredTrimIndex, (lastApplied > -1 ? lastApplied - 1 : -1));
164 if(LOG.isTraceEnabled()) {
165 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
166 persistenceId(), desiredTrimIndex, lastApplied, tempMin);
169 if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
170 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
171 context.getTermInformation().getCurrentTerm());
173 //use the term of the temp-min, since we check for isPresent, entry will not be null
174 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
175 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
176 context.getReplicatedLog().snapshotCommit();
178 } else if(tempMin > currentBehavior.getReplicatedToAllIndex()) {
179 // It's possible a follower was lagging and an install snapshot advanced its match index past
180 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
181 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
182 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
183 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
184 currentBehavior.setReplicatedToAllIndex(tempMin);
190 private class Idle extends AbstractSnapshotState {
192 private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
193 TermInformationReader lastAppliedTermInfoReader =
194 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
195 lastLogEntry, hasFollowers());
197 long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
198 long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
200 TermInformationReader replicatedToAllTermInfoReader =
201 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
203 long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
204 long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
206 // send a CaptureSnapshot to self to make the expensive operation async.
208 List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
210 captureSnapshot = new CaptureSnapshot(lastLogEntry.getIndex(),
211 lastLogEntry.getTerm(), lastAppliedIndex, lastAppliedTerm,
212 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
214 if(captureSnapshot.isInstallSnapshotInitiated()) {
215 LOG.info("{}: Initiating snapshot capture {} to install on {}",
216 persistenceId(), captureSnapshot, targetFollower);
218 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
221 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
223 LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
225 SnapshotManager.this.currentState = CREATING;
228 createSnapshotProcedure.apply(null);
229 } catch (Exception e) {
230 SnapshotManager.this.currentState = IDLE;
231 LOG.error("Error creating snapshot", e);
239 public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
240 return capture(lastLogEntry, replicatedToAllIndex, null);
244 public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
245 return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
249 public void apply(Snapshot snapshot) {
250 applySnapshot = snapshot;
252 lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
254 LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
256 context.getPersistenceProvider().saveSnapshot(snapshot);
258 SnapshotManager.this.currentState = PERSISTING;
262 public String toString() {
267 public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
268 return doTrimLog(desiredTrimIndex, currentBehavior);
272 private class Creating extends AbstractSnapshotState {
275 public boolean isCapturing() {
280 public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
281 // create a snapshot object from the state provided and save it
282 // when snapshot is saved async, SaveSnapshotSuccess is raised.
284 Snapshot sn = Snapshot.create(snapshotBytes,
285 captureSnapshot.getUnAppliedEntries(),
286 captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
287 captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
289 context.getPersistenceProvider().saveSnapshot(sn);
291 LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage());
293 long dataThreshold = totalMemory *
294 context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
295 if (context.getReplicatedLog().dataSize() > dataThreshold) {
297 if(LOG.isDebugEnabled()) {
298 LOG.debug("{}: dataSize {} exceeds dataThreshold {} - doing snapshotPreCommit with index {}",
299 persistenceId(), context.getReplicatedLog().dataSize(), dataThreshold,
300 captureSnapshot.getLastAppliedIndex());
303 // if memory is less, clear the log based on lastApplied.
304 // this could/should only happen if one of the followers is down
305 // as normally we keep removing from the log when its replicated to all.
306 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
307 captureSnapshot.getLastAppliedTerm());
309 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
310 // install snapshot to a follower.
311 if(captureSnapshot.getReplicatedToAllIndex() >= 0) {
312 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
315 } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
316 // clear the log based on replicatedToAllIndex
317 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
318 captureSnapshot.getReplicatedToAllTerm());
320 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
322 // The replicatedToAllIndex was not found in the log
323 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
324 // In this scenario we may need to save the snapshot to the akka persistence
325 // snapshot for recovery but we do not need to do the replicated log trimming.
326 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
327 context.getReplicatedLog().getSnapshotTerm());
330 LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
331 "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
332 captureSnapshot.getLastAppliedTerm());
334 if (context.getId().equals(currentBehavior.getLeaderId())
335 && captureSnapshot.isInstallSnapshotInitiated()) {
336 // this would be call straight to the leader and won't initiate in serialization
337 currentBehavior.handleMessage(context.getActor(), new SendInstallSnapshot(
338 ByteString.copyFrom(snapshotBytes)));
341 captureSnapshot = null;
342 SnapshotManager.this.currentState = PERSISTING;
346 public String toString() {
352 private class Persisting extends AbstractSnapshotState {
355 public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
356 LOG.debug("Snapshot success sequence number:", sequenceNumber);
358 if(applySnapshot != null) {
360 applySnapshotProcedure.apply(applySnapshot.getState());
362 //clears the followers log, sets the snapshot index to ensure adjusted-index works
363 context.setReplicatedLog(ReplicatedLogImpl.newInstance(applySnapshot, context, currentBehavior));
364 context.setLastApplied(applySnapshot.getLastAppliedIndex());
365 context.setCommitIndex(applySnapshot.getLastAppliedIndex());
366 } catch (Exception e) {
367 LOG.error("Error applying snapshot", e);
370 context.getReplicatedLog().snapshotCommit();
373 context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
374 sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
376 context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
378 lastSequenceNumber = -1;
379 applySnapshot = null;
380 SnapshotManager.this.currentState = IDLE;
384 public void rollback() {
385 // Nothing to rollback if we're applying a snapshot from the leader.
386 if(applySnapshot == null) {
387 context.getReplicatedLog().snapshotRollback();
389 LOG.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle." +
390 "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
391 context.getReplicatedLog().getSnapshotIndex(),
392 context.getReplicatedLog().getSnapshotTerm(),
393 context.getReplicatedLog().size());
396 lastSequenceNumber = -1;
397 applySnapshot = null;
398 SnapshotManager.this.currentState = IDLE;
402 public String toString() {
408 private static interface TermInformationReader {
413 static class LastAppliedTermInformationReader implements TermInformationReader{
417 public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
418 ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
419 ReplicatedLogEntry entry = log.get(originalIndex);
423 if(lastLogEntry != null) {
424 // since we have persisted the last-log-entry to persistent journal before the capture,
425 // we would want to snapshot from this entry.
426 index = lastLogEntry.getIndex();
427 term = lastLogEntry.getTerm();
429 } else if (entry != null) {
430 index = entry.getIndex();
431 term = entry.getTerm();
432 } else if(log.getSnapshotIndex() > -1){
433 index = log.getSnapshotIndex();
434 term = log.getSnapshotTerm();
440 public long getIndex(){
445 public long getTerm(){
450 private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
454 ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
455 ReplicatedLogEntry entry = log.get(originalIndex);
460 index = entry.getIndex();
461 term = entry.getTerm();
468 public long getIndex(){
473 public long getTerm(){