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 akka.persistence.SnapshotSelectionCriteria;
13 import com.google.common.base.Stopwatch;
14 import java.io.ByteArrayInputStream;
15 import java.io.ObjectInputStream;
16 import org.opendaylight.controller.cluster.DataPersistenceProvider;
17 import org.opendaylight.controller.cluster.PersistentDataProvider;
18 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
19 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
20 import org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries;
21 import org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm;
22 import org.slf4j.Logger;
25 * Support class that handles persistence recovery for a RaftActor.
27 * @author Thomas Pantelis
29 class RaftActorRecoverySupport {
30 private final RaftActorContext context;
31 private final RaftActorRecoveryCohort cohort;
33 private int currentRecoveryBatchCount;
34 private boolean dataRecoveredWithPersistenceDisabled;
35 private boolean anyDataRecovered;
37 private Stopwatch recoveryTimer;
38 private final Logger log;
40 RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
41 this.context = context;
43 this.log = context.getLogger();
46 boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
47 log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
49 anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
51 boolean recoveryComplete = false;
52 DataPersistenceProvider persistence = context.getPersistenceProvider();
53 if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm) {
54 // Handle this message for backwards compatibility with pre-Lithium versions.
55 org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm update =
56 (org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm)message;
57 context.getTermInformation().update(update.getCurrentTerm(), update.getVotedFor());
58 } else if (message instanceof UpdateElectionTerm) {
59 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
60 ((UpdateElectionTerm) message).getVotedFor());
61 } else if(persistence.isRecoveryApplicable()) {
62 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 replicatedLog().removeFrom(((DeleteEntries) message).getFromIndex());
70 } else if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) {
71 // Handle this message for backwards compatibility with pre-Lithium versions.
72 replicatedLog().removeFrom(((org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) message).getFromIndex());
73 } else if (message instanceof RecoveryCompleted) {
74 onRecoveryCompletedMessage();
75 possiblyRestoreFromSnapshot();
76 recoveryComplete = true;
78 } else if (message instanceof RecoveryCompleted) {
79 recoveryComplete = true;
81 if(dataRecoveredWithPersistenceDisabled) {
82 // Data persistence is disabled but we recovered some data entries so we must have just
83 // transitioned to disabled or a persistence backup was restored. Either way, delete all the
84 // messages from the akka journal for efficiency and so that we do not end up with consistency
85 // issues in case persistence is -re-enabled.
86 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
88 // Delete all the akka snapshots as they will not be needed
89 persistentProvider.deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
90 scala.Long.MaxValue(), 0L, 0L));
92 // Since we cleaned out the journal, we need to re-write the current election info.
93 context.getTermInformation().updateAndPersist(context.getTermInformation().getCurrentTerm(),
94 context.getTermInformation().getVotedFor());
97 possiblyRestoreFromSnapshot();
99 boolean isServerConfigPayload = false;
100 if(message instanceof ReplicatedLogEntry){
101 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
102 if(isServerConfigurationPayload(repLogEntry)){
103 isServerConfigPayload = true;
104 context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
108 if(!isServerConfigPayload){
109 dataRecoveredWithPersistenceDisabled = true;
113 return recoveryComplete;
116 private void possiblyRestoreFromSnapshot() {
117 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
118 if(restoreFromSnapshot == null) {
122 if(anyDataRecovered) {
123 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
128 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
129 Snapshot snapshot = (Snapshot) ois.readObject();
131 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
133 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
134 } catch(Exception e) {
135 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
139 private ReplicatedLog replicatedLog() {
140 return context.getReplicatedLog();
143 private void initRecoveryTimer() {
144 if(recoveryTimer == null) {
145 recoveryTimer = Stopwatch.createStarted();
149 private void onRecoveredSnapshot(SnapshotOffer offer) {
150 if(log.isDebugEnabled()) {
151 log.debug("{}: SnapshotOffer called..", context.getId());
156 Snapshot snapshot = (Snapshot) offer.snapshot();
158 // Create a replicated log with the snapshot information
159 // The replicated log can be used later on to retrieve this snapshot
160 // when we need to install it on a peer
162 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
163 context.setLastApplied(snapshot.getLastAppliedIndex());
164 context.setCommitIndex(snapshot.getLastAppliedIndex());
165 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
167 Stopwatch timer = Stopwatch.createStarted();
169 // Apply the snapshot to the actors state
170 cohort.applyRecoverySnapshot(snapshot.getState());
172 if (snapshot.getServerConfiguration() != null) {
173 context.updatePeerIds(snapshot.getServerConfiguration());
177 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
178 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
179 replicatedLog().getSnapshotTerm(), replicatedLog().size());
182 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
183 if(log.isDebugEnabled()) {
184 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
185 logEntry.getIndex(), logEntry.size());
188 if(isServerConfigurationPayload(logEntry)){
189 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
191 replicatedLog().append(logEntry);
194 private void onRecoveredApplyLogEntries(long toIndex) {
195 long lastUnappliedIndex = context.getLastApplied() + 1;
197 if(log.isDebugEnabled()) {
198 // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
199 // but the entry itself has made it to that state and recovered via the snapshot
200 log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
201 context.getId(), lastUnappliedIndex, toIndex);
204 long lastApplied = lastUnappliedIndex - 1;
205 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
206 ReplicatedLogEntry logEntry = replicatedLog().get(i);
207 if(logEntry != null) {
209 batchRecoveredLogEntry(logEntry);
211 // Shouldn't happen but cover it anyway.
212 log.error("{}: Log entry not found for index {}", context.getId(), i);
217 context.setLastApplied(lastApplied);
218 context.setCommitIndex(lastApplied);
221 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
224 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
225 if(!isServerConfigurationPayload(logEntry)){
226 if(currentRecoveryBatchCount == 0) {
227 cohort.startLogRecoveryBatch(batchSize);
230 cohort.appendRecoveredLogEntry(logEntry.getData());
232 if(++currentRecoveryBatchCount >= batchSize) {
233 endCurrentLogRecoveryBatch();
238 private void endCurrentLogRecoveryBatch() {
239 cohort.applyCurrentLogRecoveryBatch();
240 currentRecoveryBatchCount = 0;
243 private void onRecoveryCompletedMessage() {
244 if(currentRecoveryBatchCount > 0) {
245 endCurrentLogRecoveryBatch();
248 String recoveryTime = "";
249 if(recoveryTimer != null) {
250 recoveryTimer.stop();
251 recoveryTime = " in " + recoveryTimer.toString();
252 recoveryTimer = null;
255 log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
256 "Persistence Id = " + context.getId() +
257 " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
258 "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
259 replicatedLog().getSnapshotTerm(), replicatedLog().size());
262 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
263 return (repLogEntry.getData() instanceof ServerConfigurationPayload);