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