Fix modernization issues
[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 package org.opendaylight.controller.cluster.raft;
9
10 import akka.persistence.SnapshotSelectionCriteria;
11 import com.google.common.annotations.VisibleForTesting;
12 import com.google.common.io.ByteSource;
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.util.List;
16 import java.util.Optional;
17 import java.util.function.Consumer;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.controller.cluster.io.FileBackedOutputStream;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
22 import org.opendaylight.controller.cluster.raft.base.messages.SendInstallSnapshot;
23 import org.opendaylight.controller.cluster.raft.base.messages.SnapshotComplete;
24 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
25 import org.opendaylight.controller.cluster.raft.persisted.EmptyState;
26 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
27 import org.slf4j.Logger;
28
29 /**
30  * Manages the capturing of snapshots for a RaftActor.
31  *
32  * @author Moiz Raja
33  * @author Thomas Pantelis
34  */
35 public class SnapshotManager implements SnapshotState {
36
37     @SuppressWarnings("checkstyle:MemberName")
38     private final SnapshotState IDLE = new Idle();
39
40     @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
41     private final SnapshotState PERSISTING = new Persisting();
42
43     @SuppressWarnings({"checkstyle:MemberName", "checkstyle:AbbreviationAsWordInName"})
44     private final SnapshotState CREATING = new Creating();
45
46     private final Logger log;
47     private final RaftActorContext context;
48     private final LastAppliedTermInformationReader lastAppliedTermInformationReader =
49             new LastAppliedTermInformationReader();
50     private final ReplicatedToAllTermInformationReader replicatedToAllTermInformationReader =
51             new ReplicatedToAllTermInformationReader();
52
53
54     private SnapshotState currentState = IDLE;
55     private CaptureSnapshot captureSnapshot;
56     private long lastSequenceNumber = -1;
57
58     private Consumer<Optional<OutputStream>> createSnapshotProcedure = null;
59
60     private ApplySnapshot applySnapshot;
61     private RaftActorSnapshotCohort snapshotCohort = NoopRaftActorSnapshotCohort.INSTANCE;
62
63     /**
64      * Constructs an instance.
65      *
66      * @param context the RaftActorContext
67      * @param logger the Logger
68      */
69     public SnapshotManager(final RaftActorContext context, final Logger logger) {
70         this.context = context;
71         this.log = logger;
72     }
73
74     public boolean isApplying() {
75         return applySnapshot != null;
76     }
77
78     @Override
79     public boolean isCapturing() {
80         return currentState.isCapturing();
81     }
82
83     @Override
84     public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
85             final String targetFollower) {
86         return currentState.captureToInstall(lastLogEntry, replicatedToAllIndex, targetFollower);
87     }
88
89     @Override
90     public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
91         return currentState.capture(lastLogEntry, replicatedToAllIndex);
92     }
93
94     @Override
95     public void apply(final ApplySnapshot snapshot) {
96         currentState.apply(snapshot);
97     }
98
99     @Override
100     public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
101             final long totalMemory) {
102         currentState.persist(state, installSnapshotStream, totalMemory);
103     }
104
105     @Override
106     public void commit(final long sequenceNumber, final long timeStamp) {
107         currentState.commit(sequenceNumber, timeStamp);
108     }
109
110     @Override
111     public void rollback() {
112         currentState.rollback();
113     }
114
115     @Override
116     public long trimLog(final long desiredTrimIndex) {
117         return currentState.trimLog(desiredTrimIndex);
118     }
119
120     @SuppressWarnings("checkstyle:hiddenField")
121     void setCreateSnapshotConsumer(final Consumer<Optional<OutputStream>> createSnapshotProcedure) {
122         this.createSnapshotProcedure = createSnapshotProcedure;
123     }
124
125     void setSnapshotCohort(final RaftActorSnapshotCohort snapshotCohort) {
126         this.snapshotCohort = snapshotCohort;
127     }
128
129     public Snapshot.@NonNull State convertSnapshot(final ByteSource snapshotBytes) throws IOException {
130         return snapshotCohort.deserializeSnapshot(snapshotBytes);
131     }
132
133     public long getLastSequenceNumber() {
134         return lastSequenceNumber;
135     }
136
137     @VisibleForTesting
138     public CaptureSnapshot getCaptureSnapshot() {
139         return captureSnapshot;
140     }
141
142     private boolean hasFollowers() {
143         return context.hasFollowers();
144     }
145
146     private String persistenceId() {
147         return context.getId();
148     }
149
150     /**
151      * Constructs a CaptureSnapshot instance.
152      *
153      * @param lastLogEntry the last log entry for the snapshot.
154      * @param replicatedToAllIndex the index of the last entry replicated to all followers.
155      * @return a new CaptureSnapshot instance.
156      */
157     public CaptureSnapshot newCaptureSnapshot(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
158         TermInformationReader lastAppliedTermInfoReader =
159                 lastAppliedTermInformationReader.init(context.getReplicatedLog(), context.getLastApplied(),
160                         lastLogEntry, hasFollowers());
161
162         long lastAppliedIndex = lastAppliedTermInfoReader.getIndex();
163         long lastAppliedTerm = lastAppliedTermInfoReader.getTerm();
164
165         TermInformationReader replicatedToAllTermInfoReader =
166                 replicatedToAllTermInformationReader.init(context.getReplicatedLog(), replicatedToAllIndex);
167
168         long newReplicatedToAllIndex = replicatedToAllTermInfoReader.getIndex();
169         long newReplicatedToAllTerm = replicatedToAllTermInfoReader.getTerm();
170
171         List<ReplicatedLogEntry> unAppliedEntries = context.getReplicatedLog().getFrom(lastAppliedIndex + 1);
172
173         long lastLogEntryIndex = lastAppliedIndex;
174         long lastLogEntryTerm = lastAppliedTerm;
175         if (lastLogEntry != null) {
176             lastLogEntryIndex = lastLogEntry.getIndex();
177             lastLogEntryTerm = lastLogEntry.getTerm();
178         } else {
179             log.debug("{}: Capturing Snapshot : lastLogEntry is null. Using lastAppliedIndex {} and "
180                     + "lastAppliedTerm {} instead.", persistenceId(), lastAppliedIndex, lastAppliedTerm);
181         }
182
183         return new CaptureSnapshot(lastLogEntryIndex, lastLogEntryTerm, lastAppliedIndex, lastAppliedTerm,
184                 newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries);
185     }
186
187     private class AbstractSnapshotState implements SnapshotState {
188
189         @Override
190         public boolean isCapturing() {
191             return true;
192         }
193
194         @Override
195         public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
196             log.debug("capture should not be called in state {}", this);
197             return false;
198         }
199
200         @Override
201         public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
202                 final String targetFollower) {
203             log.debug("captureToInstall should not be called in state {}", this);
204             return false;
205         }
206
207         @Override
208         public void apply(final ApplySnapshot snapshot) {
209             log.debug("apply should not be called in state {}", this);
210         }
211
212         @Override
213         public void persist(final Snapshot.State state, final Optional<OutputStream> installSnapshotStream,
214                 final long totalMemory) {
215             log.debug("persist should not be called in state {}", this);
216         }
217
218         @Override
219         public void commit(final long sequenceNumber, final long timeStamp) {
220             log.debug("commit should not be called in state {}", this);
221         }
222
223         @Override
224         public void rollback() {
225             log.debug("rollback should not be called in state {}", this);
226         }
227
228         @Override
229         public long trimLog(final long desiredTrimIndex) {
230             log.debug("trimLog should not be called in state {}", this);
231             return -1;
232         }
233
234         protected long doTrimLog(final long desiredTrimIndex) {
235             //  we would want to keep the lastApplied as its used while capturing snapshots
236             long lastApplied = context.getLastApplied();
237             long tempMin = Math.min(desiredTrimIndex, lastApplied > -1 ? lastApplied - 1 : -1);
238
239             if (log.isTraceEnabled()) {
240                 log.trace("{}: performSnapshotWithoutCapture: desiredTrimIndex: {}, lastApplied: {}, tempMin: {}",
241                         persistenceId(), desiredTrimIndex, lastApplied, tempMin);
242             }
243
244             if (tempMin > -1 && context.getReplicatedLog().isPresent(tempMin)) {
245                 log.debug("{}: fakeSnapshot purging log to {} for term {}", persistenceId(), tempMin,
246                         context.getTermInformation().getCurrentTerm());
247
248                 //use the term of the temp-min, since we check for isPresent, entry will not be null
249                 ReplicatedLogEntry entry = context.getReplicatedLog().get(tempMin);
250                 context.getReplicatedLog().snapshotPreCommit(tempMin, entry.getTerm());
251                 context.getReplicatedLog().snapshotCommit();
252                 return tempMin;
253             }
254
255             final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
256             if (tempMin > currentBehavior.getReplicatedToAllIndex()) {
257                 // It's possible a follower was lagging and an install snapshot advanced its match index past
258                 // the current replicatedToAllIndex. Since the follower is now caught up we should advance the
259                 // replicatedToAllIndex (to tempMin). The fact that tempMin wasn't found in the log is likely
260                 // due to a previous snapshot triggered by the memory threshold exceeded, in that case we
261                 // trim the log to the last applied index even if previous entries weren't replicated to all followers.
262                 currentBehavior.setReplicatedToAllIndex(tempMin);
263             }
264             return -1;
265         }
266     }
267
268     private class Idle extends AbstractSnapshotState {
269
270         @Override
271         public boolean isCapturing() {
272             return false;
273         }
274
275         @SuppressWarnings("checkstyle:IllegalCatch")
276         private boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
277                 final String targetFollower) {
278             captureSnapshot = newCaptureSnapshot(lastLogEntry, replicatedToAllIndex);
279
280             OutputStream installSnapshotStream = null;
281             if (targetFollower != null) {
282                 installSnapshotStream = context.getFileBackedOutputStreamFactory().newInstance();
283                 log.info("{}: Initiating snapshot capture {} to install on {}",
284                         persistenceId(), captureSnapshot, targetFollower);
285             } else {
286                 log.info("{}: Initiating snapshot capture {}", persistenceId(), captureSnapshot);
287             }
288
289             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
290
291             log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
292
293             SnapshotManager.this.currentState = CREATING;
294
295             try {
296                 createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
297             } catch (Exception e) {
298                 SnapshotManager.this.currentState = IDLE;
299                 log.error("Error creating snapshot", e);
300                 return false;
301             }
302
303             return true;
304         }
305
306         @Override
307         public boolean capture(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex) {
308             return capture(lastLogEntry, replicatedToAllIndex, null);
309         }
310
311         @Override
312         public boolean captureToInstall(final ReplicatedLogEntry lastLogEntry, final long replicatedToAllIndex,
313                 final String targetFollower) {
314             return capture(lastLogEntry, replicatedToAllIndex, targetFollower);
315         }
316
317         @Override
318         public void apply(final ApplySnapshot toApply) {
319             SnapshotManager.this.applySnapshot = toApply;
320
321             lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
322
323             log.debug("lastSequenceNumber prior to persisting applied snapshot: {}", lastSequenceNumber);
324
325             context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
326
327             SnapshotManager.this.currentState = PERSISTING;
328         }
329
330         @Override
331         public String toString() {
332             return "Idle";
333         }
334
335         @Override
336         public long trimLog(final long desiredTrimIndex) {
337             return doTrimLog(desiredTrimIndex);
338         }
339     }
340
341     private class Creating extends AbstractSnapshotState {
342
343         @Override
344         public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
345                 final long totalMemory) {
346             // create a snapshot object from the state provided and save it
347             // when snapshot is saved async, SaveSnapshotSuccess is raised.
348
349             Snapshot snapshot = Snapshot.create(snapshotState,
350                     captureSnapshot.getUnAppliedEntries(),
351                     captureSnapshot.getLastIndex(), captureSnapshot.getLastTerm(),
352                     captureSnapshot.getLastAppliedIndex(), captureSnapshot.getLastAppliedTerm(),
353                     context.getTermInformation().getCurrentTerm(),
354                     context.getTermInformation().getVotedFor(), context.getPeerServerInfo(true));
355
356             context.getPersistenceProvider().saveSnapshot(snapshot);
357
358             log.info("{}: Persisting of snapshot done: {}", persistenceId(), snapshot);
359
360             long dataThreshold = totalMemory * context.getConfigParams().getSnapshotDataThresholdPercentage() / 100;
361             boolean dataSizeThresholdExceeded = context.getReplicatedLog().dataSize() > dataThreshold;
362
363             boolean logSizeExceededSnapshotBatchCount =
364                     context.getReplicatedLog().size() >= context.getConfigParams().getSnapshotBatchCount();
365
366             final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
367             if (dataSizeThresholdExceeded || logSizeExceededSnapshotBatchCount) {
368                 if (log.isDebugEnabled()) {
369                     if (dataSizeThresholdExceeded) {
370                         log.debug("{}: log data size {} exceeds the memory threshold {} - doing snapshotPreCommit "
371                                 + "with index {}", context.getId(), context.getReplicatedLog().dataSize(),
372                                 dataThreshold, captureSnapshot.getLastAppliedIndex());
373                     } else {
374                         log.debug("{}: log size {} exceeds the snapshot batch count {} - doing snapshotPreCommit with "
375                                 + "index {}", context.getId(), context.getReplicatedLog().size(),
376                                 context.getConfigParams().getSnapshotBatchCount(),
377                                 captureSnapshot.getLastAppliedIndex());
378                     }
379                 }
380
381                 // We either exceeded the memory threshold or the log size exceeded the snapshot batch
382                 // count so, to keep the log memory footprint in check, clear the log based on lastApplied.
383                 // This could/should only happen if one of the followers is down as normally we keep
384                 // removing from the log as entries are replicated to all.
385                 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getLastAppliedIndex(),
386                         captureSnapshot.getLastAppliedTerm());
387
388                 // Don't reset replicatedToAllIndex to -1 as this may prevent us from trimming the log after an
389                 // install snapshot to a follower.
390                 if (captureSnapshot.getReplicatedToAllIndex() >= 0) {
391                     currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
392                 }
393
394             } else if (captureSnapshot.getReplicatedToAllIndex() != -1) {
395                 // clear the log based on replicatedToAllIndex
396                 context.getReplicatedLog().snapshotPreCommit(captureSnapshot.getReplicatedToAllIndex(),
397                         captureSnapshot.getReplicatedToAllTerm());
398
399                 currentBehavior.setReplicatedToAllIndex(captureSnapshot.getReplicatedToAllIndex());
400             } else {
401                 // The replicatedToAllIndex was not found in the log
402                 // This means that replicatedToAllIndex never moved beyond -1 or that it is already in the snapshot.
403                 // In this scenario we may need to save the snapshot to the akka persistence
404                 // snapshot for recovery but we do not need to do the replicated log trimming.
405                 context.getReplicatedLog().snapshotPreCommit(context.getReplicatedLog().getSnapshotIndex(),
406                         context.getReplicatedLog().getSnapshotTerm());
407             }
408
409             log.info("{}: Removed in-memory snapshotted entries, adjusted snaphsotIndex: {} and term: {}",
410                     context.getId(), context.getReplicatedLog().getSnapshotIndex(),
411                     context.getReplicatedLog().getSnapshotTerm());
412
413             if (installSnapshotStream.isPresent()) {
414                 if (context.getId().equals(currentBehavior.getLeaderId())) {
415                     try {
416                         ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
417                         currentBehavior.handleMessage(context.getActor(),
418                                 new SendInstallSnapshot(snapshot, snapshotBytes));
419                     } catch (IOException e) {
420                         log.error("{}: Snapshot install failed due to an unrecoverable streaming error",
421                                 context.getId(), e);
422                     }
423                 } else {
424                     ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
425                 }
426             }
427
428             captureSnapshot = null;
429             SnapshotManager.this.currentState = PERSISTING;
430         }
431
432         @Override
433         public String toString() {
434             return "Creating";
435         }
436
437     }
438
439     private class Persisting extends AbstractSnapshotState {
440
441         @Override
442         @SuppressWarnings("checkstyle:IllegalCatch")
443         public void commit(final long sequenceNumber, final long timeStamp) {
444             log.debug("{}: Snapshot success -  sequence number: {}", persistenceId(), sequenceNumber);
445
446             if (applySnapshot != null) {
447                 try {
448                     Snapshot snapshot = applySnapshot.getSnapshot();
449
450                     //clears the followers log, sets the snapshot index to ensure adjusted-index works
451                     context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
452                     context.setLastApplied(snapshot.getLastAppliedIndex());
453                     context.setCommitIndex(snapshot.getLastAppliedIndex());
454                     context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
455
456                     if (snapshot.getServerConfiguration() != null) {
457                         context.updatePeerIds(snapshot.getServerConfiguration());
458                     }
459
460                     if (!(snapshot.getState() instanceof EmptyState)) {
461                         snapshotCohort.applySnapshot(snapshot.getState());
462                     }
463
464                     applySnapshot.getCallback().onSuccess();
465                 } catch (Exception e) {
466                     log.error("{}: Error applying snapshot", context.getId(), e);
467                 }
468             } else {
469                 context.getReplicatedLog().snapshotCommit();
470             }
471
472             context.getPersistenceProvider().deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
473                     timeStamp - 1, 0L, 0L));
474
475             context.getPersistenceProvider().deleteMessages(lastSequenceNumber);
476
477             snapshotComplete();
478         }
479
480         @Override
481         public void rollback() {
482             // Nothing to rollback if we're applying a snapshot from the leader.
483             if (applySnapshot == null) {
484                 context.getReplicatedLog().snapshotRollback();
485
486                 log.info("{}: Replicated Log rolled back. Snapshot will be attempted in the next cycle."
487                         + "snapshotIndex:{}, snapshotTerm:{}, log-size:{}", persistenceId(),
488                         context.getReplicatedLog().getSnapshotIndex(),
489                         context.getReplicatedLog().getSnapshotTerm(),
490                         context.getReplicatedLog().size());
491             } else {
492                 applySnapshot.getCallback().onFailure();
493             }
494
495             snapshotComplete();
496         }
497
498         private void snapshotComplete() {
499             lastSequenceNumber = -1;
500             applySnapshot = null;
501             SnapshotManager.this.currentState = IDLE;
502
503             context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
504         }
505
506         @Override
507         public String toString() {
508             return "Persisting";
509         }
510
511     }
512
513     private interface TermInformationReader {
514         long getIndex();
515
516         long getTerm();
517     }
518
519     static class LastAppliedTermInformationReader implements TermInformationReader {
520         private long index;
521         private long term;
522
523         LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
524                 final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
525             ReplicatedLogEntry entry = log.get(originalIndex);
526             this.index = -1L;
527             this.term = -1L;
528             if (!hasFollowers) {
529                 if (lastLogEntry != null) {
530                     // since we have persisted the last-log-entry to persistent journal before the capture,
531                     // we would want to snapshot from this entry.
532                     index = lastLogEntry.getIndex();
533                     term = lastLogEntry.getTerm();
534                 }
535             } else if (entry != null) {
536                 index = entry.getIndex();
537                 term = entry.getTerm();
538             } else if (log.getSnapshotIndex() > -1) {
539                 index = log.getSnapshotIndex();
540                 term = log.getSnapshotTerm();
541             }
542             return this;
543         }
544
545         @Override
546         public long getIndex() {
547             return this.index;
548         }
549
550         @Override
551         public long getTerm() {
552             return this.term;
553         }
554     }
555
556     private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
557         private long index;
558         private long term;
559
560         ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
561             ReplicatedLogEntry entry = log.get(originalIndex);
562             this.index = -1L;
563             this.term = -1L;
564
565             if (entry != null) {
566                 index = entry.getIndex();
567                 term = entry.getTerm();
568             }
569
570             return this;
571         }
572
573         @Override
574         public long getIndex() {
575             return this.index;
576         }
577
578         @Override
579         public long getTerm() {
580             return this.term;
581         }
582     }
583 }