2 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.raft;
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;
28 * Support class that handles persistence recovery for a RaftActor.
30 * @author Thomas Pantelis
32 class RaftActorRecoverySupport {
33 private final RaftActorContext context;
34 private final RaftActorRecoveryCohort cohort;
36 private int currentRecoveryBatchCount;
37 private boolean dataRecoveredWithPersistenceDisabled;
38 private boolean anyDataRecovered;
39 private boolean hasMigratedDataRecovered;
41 private Stopwatch recoveryTimer;
42 private final Logger log;
44 RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
45 this.context = context;
47 this.log = context.getLogger();
50 boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
51 log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
53 anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
55 if (isMigratedSerializable(message)) {
56 hasMigratedDataRecovered = true;
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);
78 return recoveryComplete;
81 @SuppressWarnings("checkstyle:IllegalCatch")
82 private void possiblyRestoreFromSnapshot() {
83 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
84 if (restoreFromSnapshot == null) {
88 if (anyDataRecovered) {
89 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
94 try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
95 Snapshot snapshot = (Snapshot) ois.readObject();
97 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
99 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
100 } catch (RuntimeException | ClassNotFoundException | IOException e) {
101 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
105 private ReplicatedLog replicatedLog() {
106 return context.getReplicatedLog();
109 private void initRecoveryTimer() {
110 if (recoveryTimer == null) {
111 recoveryTimer = Stopwatch.createStarted();
115 private void onRecoveredSnapshot(SnapshotOffer offer) {
116 log.debug("{}: SnapshotOffer called..", context.getId());
120 Snapshot snapshot = (Snapshot) offer.snapshot();
122 for (ReplicatedLogEntry entry: snapshot.getUnAppliedEntries()) {
123 if (isMigratedPayload(entry)) {
124 hasMigratedDataRecovered = true;
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.
132 snapshot = Snapshot.create(new byte[0], Collections.emptyList(), -1, -1, -1, -1,
133 snapshot.getElectionTerm(), snapshot.getElectionVotedFor(), snapshot.getServerConfiguration());
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
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());
145 Stopwatch timer = Stopwatch.createStarted();
147 // Apply the snapshot to the actors state
148 cohort.applyRecoverySnapshot(snapshot.getState());
150 if (snapshot.getServerConfiguration() != null) {
151 context.updatePeerIds(snapshot.getServerConfiguration());
153 if (isMigratedSerializable(snapshot.getServerConfiguration())) {
154 hasMigratedDataRecovered = true;
159 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
160 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
161 replicatedLog().getSnapshotTerm(), replicatedLog().size());
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());
170 if (isServerConfigurationPayload(logEntry)) {
171 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
174 if (isMigratedPayload(logEntry)) {
175 hasMigratedDataRecovered = true;
178 if (context.getPersistenceProvider().isRecoveryApplicable()) {
179 replicatedLog().append(logEntry);
180 } else if (!isPersistentPayload(logEntry)) {
181 dataRecoveredWithPersistenceDisabled = true;
185 private void onRecoveredApplyLogEntries(long toIndex) {
186 if (!context.getPersistenceProvider().isRecoveryApplicable()) {
187 dataRecoveredWithPersistenceDisabled = true;
191 long lastUnappliedIndex = context.getLastApplied() + 1;
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);
200 long lastApplied = lastUnappliedIndex - 1;
201 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
202 ReplicatedLogEntry logEntry = replicatedLog().get(i);
203 if (logEntry != null) {
205 batchRecoveredLogEntry(logEntry);
207 // Shouldn't happen but cover it anyway.
208 log.error("{}: Log entry not found for index {}", context.getId(), i);
213 context.setLastApplied(lastApplied);
214 context.setCommitIndex(lastApplied);
217 private void onDeleteEntries(DeleteEntries deleteEntries) {
218 if (context.getPersistenceProvider().isRecoveryApplicable()) {
219 replicatedLog().removeFrom(deleteEntries.getFromIndex());
221 dataRecoveredWithPersistenceDisabled = true;
225 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
228 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
229 if (!isServerConfigurationPayload(logEntry)) {
230 if (currentRecoveryBatchCount == 0) {
231 cohort.startLogRecoveryBatch(batchSize);
234 cohort.appendRecoveredLogEntry(logEntry.getData());
236 if (++currentRecoveryBatchCount >= batchSize) {
237 endCurrentLogRecoveryBatch();
242 private void endCurrentLogRecoveryBatch() {
243 cohort.applyCurrentLogRecoveryBatch();
244 currentRecoveryBatchCount = 0;
247 private void onRecoveryCompletedMessage(PersistentDataProvider persistentProvider) {
248 if (currentRecoveryBatchCount > 0) {
249 endCurrentLogRecoveryBatch();
252 String recoveryTime = "";
253 if (recoveryTimer != null) {
254 recoveryTimer.stop();
255 recoveryTime = " in " + recoveryTimer.toString();
256 recoveryTimer = null;
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());
264 if (dataRecoveredWithPersistenceDisabled
265 || hasMigratedDataRecovered && !context.getPersistenceProvider().isRecoveryApplicable()) {
266 if (hasMigratedDataRecovered) {
267 log.info("{}: Saving snapshot after recovery due to migrated messages", context.getId());
269 log.info("{}: Saving snapshot after recovery due to data persistence disabled", context.getId());
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.
277 Snapshot snapshot = Snapshot.create(new byte[0], Collections.<ReplicatedLogEntry>emptyList(),
279 context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
280 context.getPeerServerInfo(true));
282 persistentProvider.saveSnapshot(snapshot);
284 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
285 } else if (hasMigratedDataRecovered) {
286 log.info("{}: Snapshot capture initiated after recovery due to migrated messages", context.getId());
288 context.getSnapshotManager().capture(replicatedLog().last(), -1);
290 possiblyRestoreFromSnapshot();
294 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry) {
295 return repLogEntry.getData() instanceof ServerConfigurationPayload;
298 private static boolean isPersistentPayload(ReplicatedLogEntry repLogEntry) {
299 return repLogEntry.getData() instanceof PersistentPayload;
302 private static boolean isMigratedPayload(ReplicatedLogEntry repLogEntry) {
303 return isMigratedSerializable(repLogEntry.getData());
306 private static boolean isMigratedSerializable(Object message) {
307 return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();