Bump persisted PayloadVersion
[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.Snapshot.State;
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(final Object message, final 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         Snapshot 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         log.debug("{}: Restore snapshot: {}", context.getId(), restoreFromSnapshot);
95
96         context.getSnapshotManager().apply(new ApplySnapshot(restoreFromSnapshot));
97     }
98
99     private ReplicatedLog replicatedLog() {
100         return context.getReplicatedLog();
101     }
102
103     private void initRecoveryTimer() {
104         if (recoveryTimer == null) {
105             recoveryTimer = Stopwatch.createStarted();
106         }
107     }
108
109     private void onRecoveredSnapshot(final SnapshotOffer offer) {
110         log.debug("{}: SnapshotOffer called.", context.getId());
111
112         initRecoveryTimer();
113
114         Snapshot snapshot = (Snapshot) offer.snapshot();
115
116         for (ReplicatedLogEntry entry: snapshot.getUnAppliedEntries()) {
117             if (isMigratedPayload(entry)) {
118                 hasMigratedDataRecovered = true;
119             }
120         }
121
122         if (!context.getPersistenceProvider().isRecoveryApplicable()) {
123             // We may have just transitioned to disabled and have a snapshot containing state data and/or log
124             // entries - we don't want to preserve these, only the server config and election term info.
125
126             snapshot = Snapshot.create(
127                     EmptyState.INSTANCE, Collections.emptyList(), -1, -1, -1, -1,
128                     snapshot.getElectionTerm(), snapshot.getElectionVotedFor(), snapshot.getServerConfiguration());
129         }
130
131         // Create a replicated log with the snapshot information
132         // The replicated log can be used later on to retrieve this snapshot
133         // when we need to install it on a peer
134
135         context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
136         context.setLastApplied(snapshot.getLastAppliedIndex());
137         context.setCommitIndex(snapshot.getLastAppliedIndex());
138         context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
139
140         final Stopwatch timer = Stopwatch.createStarted();
141
142         // Apply the snapshot to the actors state
143         final State snapshotState = snapshot.getState();
144         if (snapshotState.needsMigration()) {
145             hasMigratedDataRecovered = true;
146         }
147         if (!(snapshotState instanceof EmptyState)) {
148             cohort.applyRecoverySnapshot(snapshotState);
149         }
150
151         if (snapshot.getServerConfiguration() != null) {
152             context.updatePeerIds(snapshot.getServerConfiguration());
153         }
154
155         timer.stop();
156         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
157                 context.getId(), timer, replicatedLog().getSnapshotIndex(), replicatedLog().getSnapshotTerm(),
158                 replicatedLog().size());
159     }
160
161     private void onRecoveredJournalLogEntry(final ReplicatedLogEntry logEntry) {
162         if (log.isDebugEnabled()) {
163             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
164                     logEntry.getIndex(), logEntry.size());
165         }
166
167         if (isServerConfigurationPayload(logEntry)) {
168             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
169         }
170
171         if (isMigratedPayload(logEntry)) {
172             hasMigratedDataRecovered = true;
173         }
174
175         if (context.getPersistenceProvider().isRecoveryApplicable()) {
176             replicatedLog().append(logEntry);
177         } else if (!isPersistentPayload(logEntry)) {
178             dataRecoveredWithPersistenceDisabled = true;
179         }
180     }
181
182     private void onRecoveredApplyLogEntries(final long toIndex) {
183         if (!context.getPersistenceProvider().isRecoveryApplicable()) {
184             dataRecoveredWithPersistenceDisabled = true;
185             return;
186         }
187
188         long lastUnappliedIndex = context.getLastApplied() + 1;
189
190         if (log.isDebugEnabled()) {
191             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
192             // but the entry itself has made it to that state and recovered via the snapshot
193             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
194                     context.getId(), lastUnappliedIndex, toIndex);
195         }
196
197         long lastApplied = lastUnappliedIndex - 1;
198         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
199             ReplicatedLogEntry logEntry = replicatedLog().get(i);
200             if (logEntry != null) {
201                 lastApplied++;
202                 batchRecoveredLogEntry(logEntry);
203             } else {
204                 // Shouldn't happen but cover it anyway.
205                 log.error("{}: Log entry not found for index {}", context.getId(), i);
206                 break;
207             }
208         }
209
210         context.setLastApplied(lastApplied);
211         context.setCommitIndex(lastApplied);
212     }
213
214     private void onDeleteEntries(final DeleteEntries deleteEntries) {
215         if (context.getPersistenceProvider().isRecoveryApplicable()) {
216             replicatedLog().removeFrom(deleteEntries.getFromIndex());
217         } else {
218             dataRecoveredWithPersistenceDisabled = true;
219         }
220     }
221
222     private void batchRecoveredLogEntry(final ReplicatedLogEntry logEntry) {
223         initRecoveryTimer();
224
225         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
226         if (!isServerConfigurationPayload(logEntry)) {
227             if (currentRecoveryBatchCount == 0) {
228                 cohort.startLogRecoveryBatch(batchSize);
229             }
230
231             cohort.appendRecoveredLogEntry(logEntry.getData());
232
233             if (++currentRecoveryBatchCount >= batchSize) {
234                 endCurrentLogRecoveryBatch();
235             }
236         }
237     }
238
239     private void endCurrentLogRecoveryBatch() {
240         cohort.applyCurrentLogRecoveryBatch();
241         currentRecoveryBatchCount = 0;
242     }
243
244     private void onRecoveryCompletedMessage(final PersistentDataProvider persistentProvider) {
245         if (currentRecoveryBatchCount > 0) {
246             endCurrentLogRecoveryBatch();
247         }
248
249         String recoveryTime = "";
250         if (recoveryTimer != null) {
251             recoveryTimer.stop();
252             recoveryTime = " in " + recoveryTimer.toString();
253             recoveryTimer = null;
254         }
255
256         log.info("{}: Recovery completed {} - Switching actor to Follower - last log index = {}, last log term = {}, "
257                 + "snapshot index = {}, snapshot term = {}, journal size = {}", context.getId(), recoveryTime,
258                 replicatedLog().lastIndex(), replicatedLog().lastTerm(), replicatedLog().getSnapshotIndex(),
259                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
260
261         if (dataRecoveredWithPersistenceDisabled
262                 || hasMigratedDataRecovered && !context.getPersistenceProvider().isRecoveryApplicable()) {
263             if (hasMigratedDataRecovered) {
264                 log.info("{}: Saving snapshot after recovery due to migrated messages", context.getId());
265             } else {
266                 log.info("{}: Saving snapshot after recovery due to data persistence disabled", context.getId());
267             }
268
269             // Either data persistence is disabled and we recovered some data entries (ie we must have just
270             // transitioned to disabled or a persistence backup was restored) or we recovered migrated
271             // messages. Either way, we persist a snapshot and delete all the messages from the akka journal
272             // to clean out unwanted messages.
273
274             Snapshot snapshot = Snapshot.create(
275                     EmptyState.INSTANCE, 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(final ReplicatedLogEntry repLogEntry) {
293         return repLogEntry.getData() instanceof ServerConfigurationPayload;
294     }
295
296     private static boolean isPersistentPayload(final ReplicatedLogEntry repLogEntry) {
297         return repLogEntry.getData() instanceof PersistentPayload;
298     }
299
300     private static boolean isMigratedPayload(final ReplicatedLogEntry repLogEntry) {
301         return isMigratedSerializable(repLogEntry.getData());
302     }
303
304     private static boolean isMigratedSerializable(final Object message) {
305         return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();
306     }
307 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.