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