Bug 3570: Persist snapshot on follower ApplySnapshot
[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 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;
20
21 public class SnapshotManager implements SnapshotState {
22
23     private final SnapshotState IDLE = new Idle();
24     private final SnapshotState PERSISTING = new Persisting();
25     private final SnapshotState CREATING = new Creating();
26
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();
33
34
35     private SnapshotState currentState = IDLE;
36     private CaptureSnapshot captureSnapshot;
37     private long lastSequenceNumber = -1;
38
39     private Procedure<Void> createSnapshotProcedure;
40
41     private Snapshot applySnapshot;
42     private Procedure<byte[]> applySnapshotProcedure;
43
44     public SnapshotManager(RaftActorContext context, Logger logger) {
45         this.context = context;
46         this.LOG = logger;
47     }
48
49     @Override
50     public boolean isCapturing() {
51         return currentState.isCapturing();
52     }
53
54     @Override
55     public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
56         return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
57     }
58
59     @Override
60     public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
61         return currentState.capture(lastLogEntry, replicatedToAllIndex);
62     }
63
64     @Override
65     public void apply(Snapshot snapshot) {
66         currentState.apply(snapshot);
67     }
68
69     @Override
70     public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
71         currentState.persist(snapshotBytes, currentBehavior, totalMemory);
72     }
73
74     @Override
75     public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
76         currentState.commit(sequenceNumber, currentBehavior);
77     }
78
79     @Override
80     public void rollback() {
81         currentState.rollback();
82     }
83
84     @Override
85     public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
86         return currentState.trimLog(desiredTrimIndex, currentBehavior);
87     }
88
89     public void setCreateSnapshotCallable(Procedure<Void> createSnapshotProcedure) {
90         this.createSnapshotProcedure = createSnapshotProcedure;
91     }
92
93     public void setApplySnapshotProcedure(Procedure<byte[]> applySnapshotProcedure) {
94         this.applySnapshotProcedure = applySnapshotProcedure;
95     }
96
97     public long getLastSequenceNumber() {
98         return lastSequenceNumber;
99     }
100
101     @VisibleForTesting
102     public CaptureSnapshot getCaptureSnapshot() {
103         return captureSnapshot;
104     }
105
106     private boolean hasFollowers(){
107         return context.getPeerAddresses().keySet().size() > 0;
108     }
109
110     private String persistenceId(){
111         return context.getId();
112     }
113
114     private class AbstractSnapshotState implements SnapshotState {
115
116         @Override
117         public boolean isCapturing() {
118             return false;
119         }
120
121         @Override
122         public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
123             LOG.debug("capture should not be called in state {}", this);
124             return false;
125         }
126
127         @Override
128         public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
129             LOG.debug("captureToInstall should not be called in state {}", this);
130             return false;
131         }
132
133         @Override
134         public void apply(Snapshot snapshot) {
135             LOG.debug("apply should not be called in state {}", this);
136         }
137
138         @Override
139         public void persist(byte[] snapshotBytes, RaftActorBehavior currentBehavior, long totalMemory) {
140             LOG.debug("persist should not be called in state {}", this);
141         }
142
143         @Override
144         public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
145             LOG.debug("commit should not be called in state {}", this);
146         }
147
148         @Override
149         public void rollback() {
150             LOG.debug("rollback should not be called in state {}", this);
151         }
152
153         @Override
154         public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
155             LOG.debug("trimLog should not be called in state {}", this);
156             return -1;
157         }
158
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));
163
164             if(LOG.isTraceEnabled()) {
165                 LOG.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
166                         persistenceId(), desiredTrimIndex, lastApplied, tempMin);
167             }
168
169             if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
170                 LOG.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
171                         context.getTermInformation().getCurrentTerm());
172
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();
177                 return tempMin;
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);
185             }
186             return -1;
187         }
188     }
189
190     private class Idle extends AbstractSnapshotState {
191
192         private boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
193             TermInformationReader lastAppliedTermInfoReader =
194                     lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
195                             lastLogEntry, hasFollowers());
196
197             long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
198             long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
199
200             TermInformationReader replicatedToAllTermInfoReader =
201                     replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
202
203             long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
204             long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
205
206             // send a CaptureSnapshot to self to make the expensive operation async.
207
208             List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
209
210             captureSnapshot = new CaptureSnapshot(lastLogEntry.getIndex(),
211                     lastLogEntry.getTerm(), lastAppliedIndex, lastAppliedTerm,
212                     newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, targetFollower != null);
213
214             if(captureSnapshot.isInstallSnapshotInitiated()) {
215                 LOG.info("{}: Initiating snapshot capture {} to install on {}",
216                         persistenceId(), captureSnapshot, targetFollower);
217             } else {
218                 LOG.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
219             }
220
221             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
222
223             LOG.debug("lastSequenceNumber prior to capture: {}", lastSequenceNumber);
224
225             SnapshotManager.this.currentState = CREATING;
226
227             try {
228                 createSnapshotProcedure.apply(null);
229             } catch (Exception e) {
230                 SnapshotManager.this.currentState = IDLE;
231                 LOG.error("Error creating snapshot", e);
232                 return false;
233             }
234
235             return true;
236         }
237
238         @Override
239         public boolean capture(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex) {
240             return capture(lastLogEntry, replicatedToAllIndex, null);
241         }
242
243         @Override
244         public boolean captureToInstall(ReplicatedLogEntry lastLogEntry, long replicatedToAllIndex, String targetFollower) {
245             return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
246         }
247
248         @Override
249         public void apply(Snapshot snapshot) {
250             applySnapshot = snapshot;
251
252             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
253
254             LOG.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
255
256             context.getPersistenceProvider().saveSnapshot(snapshot);
257
258             SnapshotManager.this.currentState = PERSISTING;
259         }
260
261         @Override
262         public String toString() {
263             return "Idle";
264         }
265
266         @Override
267         public long trimLog(long desiredTrimIndex, RaftActorBehavior currentBehavior) {
268             return doTrimLog(desiredTrimIndex, currentBehavior);
269         }
270     }
271
272     private class Creating extends AbstractSnapshotState {
273
274         @Override
275         public boolean isCapturing() {
276             return true;
277         }
278
279         @Override
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.
283
284             Snapshot sn = Snapshot.create(snapshotBytes,
285                     captureSnapshot.getUnAppliedEntries(),
286                     captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
287                     captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm());
288
289             context.getPersistenceProvider().saveSnapshot(sn);
290
291             LOG.info("{}: Persisting of snapshot done:{}", persistenceId(), sn.getLogMessage());
292
293             long dataThreshold = totalMemory *
294                     context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
295             if (context.getReplicatedLog().dataSize() > dataThreshold) {
296
297                 if(LOG.isDebugEnabled()) {
298                     LOG.debug("{}: dataSize {} exceeds dataThreshold {} - doing snapshotPreCommit with index {}",
299                             persistenceId(), context.getReplicatedLog().dataSize(), dataThreshold,
300                             captureSnapshot.getLastAppliedIndex());
301                 }
302
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());
308
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());
313                 }
314
315             } else if(captureSnapshot.getReplicatedToAllIndex() != -1){
316                 // clear the log based on replicatedToAllIndex
317                 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
318                         captureSnapshot.getReplicatedToAllTerm());
319
320                 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
321             } else {
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());
328             }
329
330             LOG.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex:{} " +
331                             "and term:{}", persistenceId(), captureSnapshot.getLastAppliedIndex(),
332                     captureSnapshot.getLastAppliedTerm());
333
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)));
339             }
340
341             captureSnapshot = null;
342             SnapshotManager.this.currentState = PERSISTING;
343         }
344
345         @Override
346         public String toString() {
347             return "Creating";
348         }
349
350     }
351
352     private class Persisting extends AbstractSnapshotState {
353
354         @Override
355         public void commit(long sequenceNumber, RaftActorBehavior currentBehavior) {
356             LOG.debug("Snapshot success sequence number:", sequenceNumber);
357
358             if(applySnapshot != null) {
359                 try {
360                     applySnapshotProcedure.apply(applySnapshot.getState());
361
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);
368                 }
369             } else {
370                 context.getReplicatedLog().snapshotCommit();
371             }
372
373             context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(
374                     sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
375
376             context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
377
378             lastSequenceNumber = -1;
379             applySnapshot = null;
380             SnapshotManager.this.currentState = IDLE;
381         }
382
383         @Override
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();
388
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());
394             }
395
396             lastSequenceNumber = -1;
397             applySnapshot = null;
398             SnapshotManager.this.currentState = IDLE;
399         }
400
401         @Override
402         public String toString() {
403             return "Persisting";
404         }
405
406     }
407
408     private static interface TermInformationReader {
409         long getIndex();
410         long getTerm();
411     }
412
413     static class LastAppliedTermInformationReader implements TermInformationReader{
414         private long index;
415         private long term;
416
417         public LastAppliedTermInformationReader init(ReplicatedLog log, long originalIndex,
418                                          ReplicatedLogEntry lastLogEntry, boolean hasFollowers){
419             ReplicatedLogEntry entry = log.get(originalIndex);
420             this.index = -1L;
421             this.term = -1L;
422             if (!hasFollowers) {
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();
428                 }
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();
435             }
436             return this;
437         }
438
439         @Override
440         public long getIndex(){
441             return this.index;
442         }
443
444         @Override
445         public long getTerm(){
446             return this.term;
447         }
448     }
449
450     private static class ReplicatedToAllTermInformationReader implements TermInformationReader{
451         private long index;
452         private long term;
453
454         ReplicatedToAllTermInformationReader init(ReplicatedLog log, long originalIndex){
455             ReplicatedLogEntry entry = log.get(originalIndex);
456             this.index = -1L;
457             this.term = -1L;
458
459             if (entry != null) {
460                 index = entry.getIndex();
461                 term = entry.getTerm();
462             }
463
464             return this;
465         }
466
467         @Override
468         public long getIndex(){
469             return this.index;
470         }
471
472         @Override
473         public long getTerm(){
474             return this.term;
475         }
476     }
477 }