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