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