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

©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.