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.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;
27 * Support class that handles persistence recovery for a RaftActor.
29 * @author Thomas Pantelis
31 class RaftActorRecoverySupport {
32 private final RaftActorContext context;
33 private final RaftActorRecoveryCohort cohort;
35 private int currentRecoveryBatchCount;
36 private boolean dataRecoveredWithPersistenceDisabled;
37 private boolean anyDataRecovered;
38 private boolean hasMigratedDataRecovered;
40 private Stopwatch recoveryTimer;
41 private final Logger log;
43 RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
44 this.context = context;
46 this.log = context.getLogger();
49 boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
50 log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
52 anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
54 if (isMigratedSerializable(message)) {
55 hasMigratedDataRecovered = true;
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);
77 return recoveryComplete;
80 @SuppressWarnings("checkstyle:IllegalCatch")
81 private void possiblyRestoreFromSnapshot() {
82 Snapshot restoreFromSnapshot = cohort.getRestoreFromSnapshot();
83 if (restoreFromSnapshot == null) {
87 if (anyDataRecovered) {
88 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
93 log.debug("{}: Restore snapshot: {}", context.getId(), restoreFromSnapshot);
95 context.getSnapshotManager().apply(new ApplySnapshot(restoreFromSnapshot));
98 private ReplicatedLog replicatedLog() {
99 return context.getReplicatedLog();
102 private void initRecoveryTimer() {
103 if (recoveryTimer == null) {
104 recoveryTimer = Stopwatch.createStarted();
108 private void onRecoveredSnapshot(SnapshotOffer offer) {
109 log.debug("{}: SnapshotOffer called.", context.getId());
113 Snapshot snapshot = (Snapshot) offer.snapshot();
115 for (ReplicatedLogEntry entry: snapshot.getUnAppliedEntries()) {
116 if (isMigratedPayload(entry)) {
117 hasMigratedDataRecovered = true;
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.
125 snapshot = Snapshot.create(
126 EmptyState.INSTANCE, Collections.emptyList(), -1, -1, -1, -1,
127 snapshot.getElectionTerm(), snapshot.getElectionVotedFor(), snapshot.getServerConfiguration());
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
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());
139 Stopwatch timer = Stopwatch.createStarted();
141 // Apply the snapshot to the actors state
142 if (!(snapshot.getState() instanceof EmptyState)) {
143 cohort.applyRecoverySnapshot(snapshot.getState());
146 if (snapshot.getServerConfiguration() != null) {
147 context.updatePeerIds(snapshot.getServerConfiguration());
151 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
152 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
153 replicatedLog().getSnapshotTerm(), replicatedLog().size());
156 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
157 if (log.isDebugEnabled()) {
158 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
159 logEntry.getIndex(), logEntry.size());
162 if (isServerConfigurationPayload(logEntry)) {
163 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
166 if (isMigratedPayload(logEntry)) {
167 hasMigratedDataRecovered = true;
170 if (context.getPersistenceProvider().isRecoveryApplicable()) {
171 replicatedLog().append(logEntry);
172 } else if (!isPersistentPayload(logEntry)) {
173 dataRecoveredWithPersistenceDisabled = true;
177 private void onRecoveredApplyLogEntries(long toIndex) {
178 if (!context.getPersistenceProvider().isRecoveryApplicable()) {
179 dataRecoveredWithPersistenceDisabled = true;
183 long lastUnappliedIndex = context.getLastApplied() + 1;
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);
192 long lastApplied = lastUnappliedIndex - 1;
193 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
194 ReplicatedLogEntry logEntry = replicatedLog().get(i);
195 if (logEntry != null) {
197 batchRecoveredLogEntry(logEntry);
199 // Shouldn't happen but cover it anyway.
200 log.error("{}: Log entry not found for index {}", context.getId(), i);
205 context.setLastApplied(lastApplied);
206 context.setCommitIndex(lastApplied);
209 private void onDeleteEntries(DeleteEntries deleteEntries) {
210 if (context.getPersistenceProvider().isRecoveryApplicable()) {
211 replicatedLog().removeFrom(deleteEntries.getFromIndex());
213 dataRecoveredWithPersistenceDisabled = true;
217 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
220 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
221 if (!isServerConfigurationPayload(logEntry)) {
222 if (currentRecoveryBatchCount == 0) {
223 cohort.startLogRecoveryBatch(batchSize);
226 cohort.appendRecoveredLogEntry(logEntry.getData());
228 if (++currentRecoveryBatchCount >= batchSize) {
229 endCurrentLogRecoveryBatch();
234 private void endCurrentLogRecoveryBatch() {
235 cohort.applyCurrentLogRecoveryBatch();
236 currentRecoveryBatchCount = 0;
239 private void onRecoveryCompletedMessage(PersistentDataProvider persistentProvider) {
240 if (currentRecoveryBatchCount > 0) {
241 endCurrentLogRecoveryBatch();
244 String recoveryTime = "";
245 if (recoveryTimer != null) {
246 recoveryTimer.stop();
247 recoveryTime = " in " + recoveryTimer.toString();
248 recoveryTimer = null;
251 log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " + "Persistence Id = "
252 + context.getId() + " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, "
253 + "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
254 replicatedLog().getSnapshotTerm(), replicatedLog().size());
256 if (dataRecoveredWithPersistenceDisabled
257 || hasMigratedDataRecovered && !context.getPersistenceProvider().isRecoveryApplicable()) {
258 if (hasMigratedDataRecovered) {
259 log.info("{}: Saving snapshot after recovery due to migrated messages", context.getId());
261 log.info("{}: Saving snapshot after recovery due to data persistence disabled", context.getId());
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.
269 Snapshot snapshot = Snapshot.create(
270 EmptyState.INSTANCE, Collections.<ReplicatedLogEntry>emptyList(),
272 context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
273 context.getPeerServerInfo(true));
275 persistentProvider.saveSnapshot(snapshot);
277 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
278 } else if (hasMigratedDataRecovered) {
279 log.info("{}: Snapshot capture initiated after recovery due to migrated messages", context.getId());
281 context.getSnapshotManager().capture(replicatedLog().last(), -1);
283 possiblyRestoreFromSnapshot();
287 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry) {
288 return repLogEntry.getData() instanceof ServerConfigurationPayload;
291 private static boolean isPersistentPayload(ReplicatedLogEntry repLogEntry) {
292 return repLogEntry.getData() instanceof PersistentPayload;
295 private static boolean isMigratedPayload(ReplicatedLogEntry repLogEntry) {
296 return isMigratedSerializable(repLogEntry.getData());
299 private static boolean isMigratedSerializable(Object message) {
300 return message instanceof MigratedSerializable && ((MigratedSerializable)message).isMigrated();