Take snapshot after recovery on migrated messages
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActorRecoverySupport.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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.RecoveryCompleted;
11 import akka.persistence.SnapshotOffer;
12 import com.google.common.base.Stopwatch;
13 import java.io.ByteArrayInputStream;
14 import java.io.ObjectInputStream;
15 import java.util.Collections;
16 import org.opendaylight.controller.cluster.PersistentDataProvider;
17 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
18 import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
19 import org.opendaylight.controller.cluster.raft.persisted.DeleteEntries;
20 import org.opendaylight.controller.cluster.raft.persisted.MigratedSerializable;
21 import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
22 import org.opendaylight.controller.cluster.raft.persisted.UpdateElectionTerm;
23 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.PersistentPayload;
24 import org.slf4j.Logger;
25 /**
26  * Support class that handles persistence recovery for a RaftActor.
27  *
28  * @author Thomas Pantelis
29  */
30 class RaftActorRecoverySupport {
31     private final RaftActorContext context;
32     private final RaftActorRecoveryCohort cohort;
33
34     private int currentRecoveryBatchCount;
35     private boolean dataRecoveredWithPersistenceDisabled;
36     private boolean anyDataRecovered;
37     private boolean hasMigratedDataRecovered;
38
39     private Stopwatch recoveryTimer;
40     private final Logger log;
41
42     RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
43         this.context = context;
44         this.cohort = cohort;
45         this.log = context.getLogger();
46     }
47
48     boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
49         log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
50
51         anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
52
53         if(isMigratedSerializable(message)) {
54             hasMigratedDataRecovered = true;
55         }
56
57         boolean recoveryComplete = false;
58         if (message instanceof UpdateElectionTerm) {
59             context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
60                     ((UpdateElectionTerm) message).getVotedFor());
61         } else if (message instanceof SnapshotOffer) {
62             onRecoveredSnapshot((SnapshotOffer) message);
63         } else if (message instanceof ReplicatedLogEntry) {
64             onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
65         } else if (message instanceof ApplyJournalEntries) {
66             onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
67         } else if (message instanceof DeleteEntries) {
68             onDeleteEntries((DeleteEntries) message);
69         } else if (message instanceof RecoveryCompleted) {
70             recoveryComplete = true;
71             onRecoveryCompletedMessage(persistentProvider);
72         }
73
74         return recoveryComplete;
75     }
76
77     private void possiblyRestoreFromSnapshot() {
78         byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
79         if(restoreFromSnapshot == null) {
80             return;
81         }
82
83         if(anyDataRecovered) {
84             log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
85                     context.getId());
86             return;
87         }
88
89         try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
90             Snapshot snapshot = (Snapshot) ois.readObject();
91
92             log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
93
94             context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
95         } catch(Exception e) {
96             log.error("{}: Error deserializing snapshot restore", context.getId(), e);
97         }
98     }
99
100     private ReplicatedLog replicatedLog() {
101         return context.getReplicatedLog();
102     }
103
104     private void initRecoveryTimer() {
105         if(recoveryTimer == null) {
106             recoveryTimer = Stopwatch.createStarted();
107         }
108     }
109
110     private void onRecoveredSnapshot(SnapshotOffer offer) {
111         if(log.isDebugEnabled()) {
112             log.debug("{}: SnapshotOffer called..", context.getId());
113         }
114
115         initRecoveryTimer();
116
117         Snapshot snapshot = (Snapshot) offer.snapshot();
118
119         for(ReplicatedLogEntry entry: snapshot.getUnAppliedEntries()) {
120             if(isMigratedPayload(entry)) {
121                 hasMigratedDataRecovered = true;
122             }
123         }
124
125         if(!context.getPersistenceProvider().isRecoveryApplicable()) {
126             // We may have just transitioned to disabled and have a snapshot containing state data and/or log
127             // entries - we don't want to preserve these, only the server config and election term info.
128
129             snapshot = Snapshot.create(new byte[0], Collections.emptyList(), -1, -1, -1, -1,
130                     snapshot.getElectionTerm(), snapshot.getElectionVotedFor(), snapshot.getServerConfiguration());
131         }
132
133         // Create a replicated log with the snapshot information
134         // The replicated log can be used later on to retrieve this snapshot
135         // when we need to install it on a peer
136
137         context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
138         context.setLastApplied(snapshot.getLastAppliedIndex());
139         context.setCommitIndex(snapshot.getLastAppliedIndex());
140         context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
141
142         Stopwatch timer = Stopwatch.createStarted();
143
144         // Apply the snapshot to the actors state
145         cohort.applyRecoverySnapshot(snapshot.getState());
146
147         if (snapshot.getServerConfiguration() != null) {
148             context.updatePeerIds(snapshot.getServerConfiguration());
149
150             if(isMigratedSerializable(snapshot.getServerConfiguration())) {
151                 hasMigratedDataRecovered = true;
152             }
153         }
154
155         timer.stop();
156         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
157                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
158                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
159     }
160
161     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
162         if(log.isDebugEnabled()) {
163             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
164                     logEntry.getIndex(), logEntry.size());
165         }
166
167         if(isServerConfigurationPayload(logEntry)){
168             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
169         }
170
171         if(isMigratedPayload(logEntry)) {
172             hasMigratedDataRecovered = true;
173         }
174
175         if(context.getPersistenceProvider().isRecoveryApplicable()) {
176             replicatedLog().append(logEntry);
177         } else if(!isPersistentPayload(logEntry)) {
178             dataRecoveredWithPersistenceDisabled = true;
179         }
180     }
181
182     private void onRecoveredApplyLogEntries(long toIndex) {
183         if(!context.getPersistenceProvider().isRecoveryApplicable()) {
184             dataRecoveredWithPersistenceDisabled = true;
185             return;
186         }
187
188         long lastUnappliedIndex = context.getLastApplied() + 1;
189
190         if(log.isDebugEnabled()) {
191             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
192             // but the entry itself has made it to that state and recovered via the snapshot
193             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
194                     context.getId(), lastUnappliedIndex, toIndex);
195         }
196
197         long lastApplied = lastUnappliedIndex - 1;
198         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
199             ReplicatedLogEntry logEntry = replicatedLog().get(i);
200             if(logEntry != null) {
201                 lastApplied++;
202                 batchRecoveredLogEntry(logEntry);
203             } else {
204                 // Shouldn't happen but cover it anyway.
205                 log.error("{}: Log entry not found for index {}", context.getId(), i);
206                 break;
207             }
208         }
209
210         context.setLastApplied(lastApplied);
211         context.setCommitIndex(lastApplied);
212     }
213
214     private void onDeleteEntries(DeleteEntries deleteEntries) {
215         if(context.getPersistenceProvider().isRecoveryApplicable()) {
216             replicatedLog().removeFrom(deleteEntries.getFromIndex());
217         } else {
218             dataRecoveredWithPersistenceDisabled = true;
219         }
220     }
221
222     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
223         initRecoveryTimer();
224
225         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
226         if(!isServerConfigurationPayload(logEntry)){
227             if(currentRecoveryBatchCount == 0) {
228                 cohort.startLogRecoveryBatch(batchSize);
229             }
230
231             cohort.appendRecoveredLogEntry(logEntry.getData());
232
233             if(++currentRecoveryBatchCount >= batchSize) {
234                 endCurrentLogRecoveryBatch();
235             }
236         }
237     }
238
239     private void endCurrentLogRecoveryBatch() {
240         cohort.applyCurrentLogRecoveryBatch();
241         currentRecoveryBatchCount = 0;
242     }
243
244     private void onRecoveryCompletedMessage(PersistentDataProvider persistentProvider) {
245         if(currentRecoveryBatchCount > 0) {
246             endCurrentLogRecoveryBatch();
247         }
248
249         String recoveryTime = "";
250         if(recoveryTimer != null) {
251             recoveryTimer.stop();
252             recoveryTime = " in " + recoveryTimer.toString();
253             recoveryTimer = null;
254         }
255
256         log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
257                  "Persistence Id =  " + context.getId() +
258                  " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
259                  "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
260                  replicatedLog().getSnapshotTerm(), replicatedLog().size());
261
262         if(dataRecoveredWithPersistenceDisabled ||
263                 (hasMigratedDataRecovered && !context.getPersistenceProvider().isRecoveryApplicable())) {
264             if(hasMigratedDataRecovered) {
265                 log.info("{}: Saving snapshot after recovery due to migrated messages", context.getId());
266             } else {
267                 log.info("{}: Saving snapshot after recovery due to data persistence disabled", context.getId());
268             }
269
270             // Either data persistence is disabled and we recovered some data entries (ie we must have just
271             // transitioned to disabled or a persistence backup was restored) or we recovered migrated
272             // messages. Either way, we persist a snapshot and delete all the messages from the akka journal
273             // to clean out unwanted messages.
274
275             Snapshot snapshot = Snapshot.create(new byte[0], Collections.<ReplicatedLogEntry>emptyList(), -1, -1, -1, -1,
276                     context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
277                     context.getPeerServerInfo(true));
278
279             persistentProvider.saveSnapshot(snapshot);
280
281             persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
282         } else if(hasMigratedDataRecovered) {
283             log.info("{}: Snapshot capture initiated after recovery due to migrated messages", context.getId());
284
285             context.getSnapshotManager().capture(replicatedLog().last(), -1);
286         } else {
287             possiblyRestoreFromSnapshot();
288         }
289     }
290
291     private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
292         return repLogEntry.getData() instanceof ServerConfigurationPayload;
293     }
294
295     private static boolean isPersistentPayload(ReplicatedLogEntry repLogEntry){
296         return repLogEntry.getData() instanceof PersistentPayload;
297     }
298
299     private static boolean isMigratedPayload(ReplicatedLogEntry repLogEntry){
300         return isMigratedSerializable(repLogEntry.getData());
301     }
302
303     private static boolean isMigratedSerializable(Object message){
304         return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();
305     }
306 }