d0217a6bc0d7223c0976609189a939050bae5e49
[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
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     private void possiblyRestoreFromSnapshot() {
81         byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
82         if (restoreFromSnapshot == null) {
83             return;
84         }
85
86         if (anyDataRecovered) {
87             log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
88                     context.getId());
89             return;
90         }
91
92         try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
93             Snapshot snapshot = (Snapshot) ois.readObject();
94
95             log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
96
97             context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
98         } catch (Exception e) {
99             log.error("{}: Error deserializing snapshot restore", context.getId(), e);
100         }
101     }
102
103     private ReplicatedLog replicatedLog() {
104         return context.getReplicatedLog();
105     }
106
107     private void initRecoveryTimer() {
108         if (recoveryTimer == null) {
109             recoveryTimer = Stopwatch.createStarted();
110         }
111     }
112
113     private void onRecoveredSnapshot(SnapshotOffer offer) {
114         log.debug("{}: SnapshotOffer called..", context.getId());
115
116         initRecoveryTimer();
117
118         Snapshot snapshot = (Snapshot) offer.snapshot();
119
120         for (ReplicatedLogEntry entry: snapshot.getUnAppliedEntries()) {
121             if (isMigratedPayload(entry)) {
122                 hasMigratedDataRecovered = true;
123             }
124         }
125
126         if (!context.getPersistenceProvider().isRecoveryApplicable()) {
127             // We may have just transitioned to disabled and have a snapshot containing state data and/or log
128             // entries - we don't want to preserve these, only the server config and election term info.
129
130             snapshot = Snapshot.create(new byte[0], Collections.emptyList(), -1, -1, -1, -1,
131                     snapshot.getElectionTerm(), snapshot.getElectionVotedFor(), snapshot.getServerConfiguration());
132         }
133
134         // Create a replicated log with the snapshot information
135         // The replicated log can be used later on to retrieve this snapshot
136         // when we need to install it on a peer
137
138         context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
139         context.setLastApplied(snapshot.getLastAppliedIndex());
140         context.setCommitIndex(snapshot.getLastAppliedIndex());
141         context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
142
143         Stopwatch timer = Stopwatch.createStarted();
144
145         // Apply the snapshot to the actors state
146         cohort.applyRecoverySnapshot(snapshot.getState());
147
148         if (snapshot.getServerConfiguration() != null) {
149             context.updatePeerIds(snapshot.getServerConfiguration());
150
151             if (isMigratedSerializable(snapshot.getServerConfiguration())) {
152                 hasMigratedDataRecovered = true;
153             }
154         }
155
156         timer.stop();
157         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
158                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
159                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
160     }
161
162     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
163         if (log.isDebugEnabled()) {
164             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
165                     logEntry.getIndex(), logEntry.size());
166         }
167
168         if (isServerConfigurationPayload(logEntry)) {
169             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
170         }
171
172         if (isMigratedPayload(logEntry)) {
173             hasMigratedDataRecovered = true;
174         }
175
176         if (context.getPersistenceProvider().isRecoveryApplicable()) {
177             replicatedLog().append(logEntry);
178         } else if (!isPersistentPayload(logEntry)) {
179             dataRecoveredWithPersistenceDisabled = true;
180         }
181     }
182
183     private void onRecoveredApplyLogEntries(long toIndex) {
184         if (!context.getPersistenceProvider().isRecoveryApplicable()) {
185             dataRecoveredWithPersistenceDisabled = true;
186             return;
187         }
188
189         long lastUnappliedIndex = context.getLastApplied() + 1;
190
191         if (log.isDebugEnabled()) {
192             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
193             // but the entry itself has made it to that state and recovered via the snapshot
194             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
195                     context.getId(), lastUnappliedIndex, toIndex);
196         }
197
198         long lastApplied = lastUnappliedIndex - 1;
199         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
200             ReplicatedLogEntry logEntry = replicatedLog().get(i);
201             if (logEntry != null) {
202                 lastApplied++;
203                 batchRecoveredLogEntry(logEntry);
204             } else {
205                 // Shouldn't happen but cover it anyway.
206                 log.error("{}: Log entry not found for index {}", context.getId(), i);
207                 break;
208             }
209         }
210
211         context.setLastApplied(lastApplied);
212         context.setCommitIndex(lastApplied);
213     }
214
215     private void onDeleteEntries(DeleteEntries deleteEntries) {
216         if (context.getPersistenceProvider().isRecoveryApplicable()) {
217             replicatedLog().removeFrom(deleteEntries.getFromIndex());
218         } else {
219             dataRecoveredWithPersistenceDisabled = true;
220         }
221     }
222
223     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
224         initRecoveryTimer();
225
226         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
227         if (!isServerConfigurationPayload(logEntry)) {
228             if (currentRecoveryBatchCount == 0) {
229                 cohort.startLogRecoveryBatch(batchSize);
230             }
231
232             cohort.appendRecoveredLogEntry(logEntry.getData());
233
234             if (++currentRecoveryBatchCount >= batchSize) {
235                 endCurrentLogRecoveryBatch();
236             }
237         }
238     }
239
240     private void endCurrentLogRecoveryBatch() {
241         cohort.applyCurrentLogRecoveryBatch();
242         currentRecoveryBatchCount = 0;
243     }
244
245     private void onRecoveryCompletedMessage(PersistentDataProvider persistentProvider) {
246         if (currentRecoveryBatchCount > 0) {
247             endCurrentLogRecoveryBatch();
248         }
249
250         String recoveryTime = "";
251         if (recoveryTimer != null) {
252             recoveryTimer.stop();
253             recoveryTime = " in " + recoveryTimer.toString();
254             recoveryTimer = null;
255         }
256
257         log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " + "Persistence Id =  "
258                   + context.getId() + " 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(),
276                     -1, -1, -1, -1,
277                     context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
278                     context.getPeerServerInfo(true));
279
280             persistentProvider.saveSnapshot(snapshot);
281
282             persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
283         } else if (hasMigratedDataRecovered) {
284             log.info("{}: Snapshot capture initiated after recovery due to migrated messages", context.getId());
285
286             context.getSnapshotManager().capture(replicatedLog().last(), -1);
287         } else {
288             possiblyRestoreFromSnapshot();
289         }
290     }
291
292     private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry) {
293         return repLogEntry.getData() instanceof ServerConfigurationPayload;
294     }
295
296     private static boolean isPersistentPayload(ReplicatedLogEntry repLogEntry) {
297         return repLogEntry.getData() instanceof PersistentPayload;
298     }
299
300     private static boolean isMigratedPayload(ReplicatedLogEntry repLogEntry) {
301         return isMigratedSerializable(repLogEntry.getData());
302     }
303
304     private static boolean isMigratedSerializable(Object message) {
305         return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();
306     }
307 }