4dbe9ee9a0f9553e279aa4af7b4abb8682c697a3
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / SnapshotManager.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.raft;
10
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;
21
22 public class SnapshotManager implements SnapshotState {
23
24     private final SnapshotState IDLE = new Idle();
25     private final SnapshotState PERSISTING = new Persisting();
26     private final SnapshotState CREATING = new Creating();
27
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();
34
35
36     private SnapshotState currentState = IDLE;
37     private CaptureSnapshot captureSnapshot;
38     private long lastSequenceNumber = -1;
39
40     private Procedure<Void> createSnapshotProcedure;
41
42     private ApplySnapshot applySnapshot;
43     private Procedure<byte[]> applySnapshotProcedure;
44
45     public SnapshotManager(RaftActorContext context, Logger logger) {
46         this.context = context;
47         this.LOG = logger;
48     }
49
50     public boolean isApplying() {
51         return applySnapshot != null;
52     }
53
54     @Override
55     public boolean isCapturing() {
56         return currentState.isCapturing();
57     }
58
59     @Override
60     public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
61         return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
62     }
63
64     @Override
65     public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
66         return currentState.capture(lastLogEntry, replicatedToAllIndex);
67     }
68
69     @Override
70     public void apply(ApplySnapshot snapshot) {
71         currentState.apply(snapshot);
72     }
73
74     @Override
75     public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
76         currentState.persist(snapshotBytes, currentBehavior, totalMemory);
77     }
78
79     @Override
80     public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
81         currentState.commit(sequenceNumber, currentBehavior);
82     }
83
84     @Override
85     public void rollback() {
86         currentState.rollback();
87     }
88
89     @Override
90     public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
91         return currentState.trimLog(desiredTrimIndex, currentBehavior);
92     }
93
94     public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
95         this.createSnapshotProcedure = createSnapshotProcedure;
96     }
97
98     public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
99         this.applySnapshotProcedure = applySnapshotProcedure;
100     }
101
102     public long getLastSequenceNumber() {
103         return lastSequenceNumber;
104     }
105
106     @VisibleForTesting
107     public CaptureSnapshot getCaptureSnapshot() {
108         return captureSnapshot;
109     }
110
111     private boolean hasFollowers(){
112         return context.hasFollowers();
113     }
114
115     private String persistenceId(){
116         return context.getId();
117     }
118
119     private class AbstractSnapshotState implements SnapshotState {
120
121         @Override
122         public boolean isCapturing() {
123             return true;
124         }
125
126         @Override
127         public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
128             LOG.debug("capture should not be called in state {}", this);
129             return false;
130         }
131
132         @Override
133         public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
134             LOG.debug("captureToInstall should not be called in state {}", this);
135             return false;
136         }
137
138         @Override
139         public void apply(ApplySnapshot snapshot) {
140             LOG.debug("apply should not be called in state {}", this);
141         }
142
143         @Override
144         public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
145             LOG.debug("persist should not be called in state {}", this);
146         }
147
148         @Override
149         public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
150             LOG.debug("commit should not be called in state {}", this);
151         }
152
153         @Override
154         public void rollback() {
155             LOG.debug("rollback should not be called in state {}", this);
156         }
157
158         @Override
159         public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
160             LOG.debug("trimLog should not be called in state {}", this);
161             return -1;
162         }
163
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));
168
169             if(LOG.isTraceEnabled()) {
170                 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
171                         persistenceId(), desiredTrimIndex, lastApplied, tempMin);
172             }
173
174             if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
175                 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
176                         context.getTermInformation().getCurrentTerm());
177
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();
182                 return tempMin;
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);
190             }
191             return -1;
192         }
193     }
194
195     private class Idle extends AbstractSnapshotState {
196
197         @Override
198         public boolean isCapturing() {
199             return false;
200         }
201
202         private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
203             TermInformationReader lastAppliedTermInfoReader =
204                     lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
205                             lastLogEntry, hasFollowers());
206
207             long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
208             long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
209
210             TermInformationReader replicatedToAllTermInfoReader =
211                     replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
212
213             long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
214             long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
215
216             // send a CaptureSnapshot to self to make the expensive operation async.
217
218             List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
219
220             long lastLogEntryIndex = lastAppliedIndex;
221             long lastLogEntryTerm = lastAppliedTerm;
222             if(lastLogEntry != null) {
223                 lastLogEntryIndex = lastLogEntry.getIndex();
224                 lastLogEntryTerm = lastLogEntry.getTerm();
225             } else {
226                 LOG.warn("Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and lastAppliedTerm {} instead.",
227                     lastAppliedIndex, lastAppliedTerm);
228             }
229
230             captureSnapshot = new CaptureSnapshot(lastLogEntryIndex,
231                 lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
232                     newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
233
234             if(captureSnapshot.isInstallSnapshotInitiated()) {
235                 LOG.info("{}: Initiating snapshot capture {} to install on {}",
236                         persistenceId(), captureSnapshot, targetFollower);
237             } else {
238                 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
239             }
240
241             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
242
243             LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
244
245             SnapshotManager.this.currentState = CREATING;
246
247             try {
248                 createSnapshotProcedure.apply(null);
249             } catch (Exception e) {
250                 SnapshotManager.this.currentState = IDLE;
251                 LOG.error("Error creating snapshot", e);
252                 return false;
253             }
254
255             return true;
256         }
257
258         @Override
259         public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
260             return capture(lastLogEntry, replicatedToAllIndex, null);
261         }
262
263         @Override
264         public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
265             return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
266         }
267
268         @Override
269         public void apply(ApplySnapshot applySnapshot) {
270             SnapshotManager.this.applySnapshot = applySnapshot;
271
272             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
273
274             LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
275
276             context.getPersistenceProvider().saveSnapshot(applySnapshot.getSnapshot());
277
278             SnapshotManager.this.currentState = PERSISTING;
279         }
280
281         @Override
282         public String toString() {
283             return "Idle";
284         }
285
286         @Override
287         public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
288             return doTrimLog(desiredTrimIndex, currentBehavior);
289         }
290     }
291
292     private class Creating extends AbstractSnapshotState {
293
294         @Override
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.
298
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());
305
306             context.getPersistenceProvider().saveSnapshot(snapshot);
307
308             LOG.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
309
310             long dataThreshold = totalMemory *
311                     context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
312             boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
313
314             boolean logSizeExceededSnapshotBatchCount =
315                     context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
316
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());
323                     } else {
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());
327                     }
328                 }
329
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());
336
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());
341                 }
342
343             } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
344                 // clear the log based on replicatedToAllIndex
345                 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
346                         captureSnapshot.getReplicatedToAllTerm());
347
348                 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
349             } else {
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());
356             }
357
358             LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} " +
359                     "and term: {}", context.getId(), context.getReplicatedLog().getSnapshotIndex(),
360                     context.getReplicatedLog().getSnapshotTerm());
361
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));
366             }
367
368             captureSnapshot = null;
369             SnapshotManager.this.currentState = PERSISTING;
370         }
371
372         @Override
373         public String toString() {
374             return "Creating";
375         }
376
377     }
378
379     private class Persisting extends AbstractSnapshotState {
380
381         @Override
382         public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
383             LOG.debug("Snapshot success sequence number: {}", sequenceNumber);
384
385             if(applySnapshot != null) {
386                 try {
387                     Snapshot snapshot = applySnapshot.getSnapshot();
388                     applySnapshotProcedure.apply(snapshot.getState());
389
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());
394
395                     applySnapshot.getCallback().onSuccess();
396                 } catch (Exception e) {
397                     LOG.error("Error applying snapshot", e);
398                 }
399             } else {
400                 context.getReplicatedLog().snapshotCommit();
401             }
402
403             context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
404                     sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
405
406             context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
407
408             snapshotComplete();
409         }
410
411         @Override
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();
416
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());
422             } else {
423                 applySnapshot.getCallback().onFailure();
424             }
425
426             snapshotComplete();
427         }
428
429         private void snapshotComplete() {
430             lastSequenceNumber = -1;
431             applySnapshot = null;
432             SnapshotManager.this.currentState = IDLE;
433
434             context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
435         }
436
437         @Override
438         public String toString() {
439             return "Persisting";
440         }
441
442     }
443
444     private static interface TermInformationReader {
445         long getIndex();
446         long getTerm();
447     }
448
449     static class LastAppliedTermInformationReader implements TermInformationReader{
450         private long index;
451         private long term;
452
453         public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
454                                          ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
455             ReplicatedLogEntry entry = log.get(originalIndex);
456             this.index = -1L;
457             this.term = -1L;
458             if (!hasFollowers) {
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();
464                 }
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();
471             }
472             return this;
473         }
474
475         @Override
476         public long getIndex(){
477             return this.index;
478         }
479
480         @Override
481         public long getTerm(){
482             return this.term;
483         }
484     }
485
486     private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
487         private long index;
488         private long term;
489
490         ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
491             ReplicatedLogEntry entry = log.get(originalIndex);
492             this.index = -1L;
493             this.term = -1L;
494
495             if (entry != null) {
496                 index = entry.getIndex();
497                 term = entry.getTerm();
498             }
499
500             return this;
501         }
502
503         @Override
504         public long getIndex(){
505             return this.index;
506         }
507
508         @Override
509         public long getTerm(){
510             return this.term;
511         }
512     }
513 }