17e3343804886b8ea9227d303cc6d75a25e59d06
[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             if (isMigratedSerializable(snapshot.getServerConfiguration())) {
162                 hasMigratedDataRecovered = true;
163             }
164         }
165
166         timer.stop();
167         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
168                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
169                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
170     }
171
172     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
173         if (log.isDebugEnabled()) {
174             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
175                     logEntry.getIndex(), logEntry.size());
176         }
177
178         if (isServerConfigurationPayload(logEntry)) {
179             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
180         }
181
182         if (isMigratedPayload(logEntry)) {
183             hasMigratedDataRecovered = true;
184         }
185
186         if (context.getPersistenceProvider().isRecoveryApplicable()) {
187             replicatedLog().append(logEntry);
188         } else if (!isPersistentPayload(logEntry)) {
189             dataRecoveredWithPersistenceDisabled = true;
190         }
191     }
192
193     private void onRecoveredApplyLogEntries(long toIndex) {
194         if (!context.getPersistenceProvider().isRecoveryApplicable()) {
195             dataRecoveredWithPersistenceDisabled = true;
196             return;
197         }
198
199         long lastUnappliedIndex = context.getLastApplied() + 1;
200
201         if (log.isDebugEnabled()) {
202             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
203             // but the entry itself has made it to that state and recovered via the snapshot
204             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
205                     context.getId(), lastUnappliedIndex, toIndex);
206         }
207
208         long lastApplied = lastUnappliedIndex - 1;
209         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
210             ReplicatedLogEntry logEntry = replicatedLog().get(i);
211             if (logEntry != null) {
212                 lastApplied++;
213                 batchRecoveredLogEntry(logEntry);
214             } else {
215                 // Shouldn't happen but cover it anyway.
216                 log.error("{}: Log entry not found for index {}", context.getId(), i);
217                 break;
218             }
219         }
220
221         context.setLastApplied(lastApplied);
222         context.setCommitIndex(lastApplied);
223     }
224
225     private void onDeleteEntries(DeleteEntries deleteEntries) {
226         if (context.getPersistenceProvider().isRecoveryApplicable()) {
227             replicatedLog().removeFrom(deleteEntries.getFromIndex());
228         } else {
229             dataRecoveredWithPersistenceDisabled = true;
230         }
231     }
232
233     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
234         initRecoveryTimer();
235
236         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
237         if (!isServerConfigurationPayload(logEntry)) {
238             if (currentRecoveryBatchCount == 0) {
239                 cohort.startLogRecoveryBatch(batchSize);
240             }
241
242             cohort.appendRecoveredLogEntry(logEntry.getData());
243
244             if (++currentRecoveryBatchCount >= batchSize) {
245                 endCurrentLogRecoveryBatch();
246             }
247         }
248     }
249
250     private void endCurrentLogRecoveryBatch() {
251         cohort.applyCurrentLogRecoveryBatch();
252         currentRecoveryBatchCount = 0;
253     }
254
255     private void onRecoveryCompletedMessage(PersistentDataProvider persistentProvider) {
256         if (currentRecoveryBatchCount > 0) {
257             endCurrentLogRecoveryBatch();
258         }
259
260         String recoveryTime = "";
261         if (recoveryTimer != null) {
262             recoveryTimer.stop();
263             recoveryTime = " in " + recoveryTimer.toString();
264             recoveryTimer = null;
265         }
266
267         log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " + "Persistence Id =  "
268                   + context.getId() + " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, "
269                   + "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
270                  replicatedLog().getSnapshotTerm(), replicatedLog().size());
271
272         if (dataRecoveredWithPersistenceDisabled
273                 || hasMigratedDataRecovered && !context.getPersistenceProvider().isRecoveryApplicable()) {
274             if (hasMigratedDataRecovered) {
275                 log.info("{}: Saving snapshot after recovery due to migrated messages", context.getId());
276             } else {
277                 log.info("{}: Saving snapshot after recovery due to data persistence disabled", context.getId());
278             }
279
280             // Either data persistence is disabled and we recovered some data entries (ie we must have just
281             // transitioned to disabled or a persistence backup was restored) or we recovered migrated
282             // messages. Either way, we persist a snapshot and delete all the messages from the akka journal
283             // to clean out unwanted messages.
284
285             Snapshot snapshot = Snapshot.create(
286                     EmptyState.INSTANCE, Collections.<ReplicatedLogEntry>emptyList(),
287                     -1, -1, -1, -1,
288                     context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
289                     context.getPeerServerInfo(true));
290
291             persistentProvider.saveSnapshot(snapshot);
292
293             persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
294         } else if (hasMigratedDataRecovered) {
295             log.info("{}: Snapshot capture initiated after recovery due to migrated messages", context.getId());
296
297             context.getSnapshotManager().capture(replicatedLog().last(), -1);
298         } else {
299             possiblyRestoreFromSnapshot();
300         }
301     }
302
303     private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry) {
304         return repLogEntry.getData() instanceof ServerConfigurationPayload;
305     }
306
307     private static boolean isPersistentPayload(ReplicatedLogEntry repLogEntry) {
308         return repLogEntry.getData() instanceof PersistentPayload;
309     }
310
311     private static boolean isMigratedPayload(ReplicatedLogEntry repLogEntry) {
312         return isMigratedSerializable(repLogEntry.getData());
313     }
314
315     private static boolean isMigratedSerializable(Object message) {
316         return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();
317     }
318 }