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