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.ApplyLogEntries;
20 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
21 import org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries;
22 import org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm;
23 import org.slf4j.Logger;
26 * Support class that handles persistence recovery for a RaftActor.
28 * @author Thomas Pantelis
30 class RaftActorRecoverySupport {
31 private final RaftActorContext context;
32 private final RaftActorRecoveryCohort cohort;
34 private int currentRecoveryBatchCount;
35 private boolean dataRecoveredWithPersistenceDisabled;
36 private boolean anyDataRecovered;
38 private Stopwatch recoveryTimer;
39 private final Logger log;
41 RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
42 this.context = context;
44 this.log = context.getLogger();
47 boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
48 log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
50 anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
52 boolean recoveryComplete = false;
53 DataPersistenceProvider persistence = context.getPersistenceProvider();
54 if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm) {
55 // Handle this message for backwards compatibility with pre-Lithium versions.
56 org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm update =
57 (org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm)message;
58 context.getTermInformation().update(update.getCurrentTerm(), update.getVotedFor());
59 } else if (message instanceof UpdateElectionTerm) {
60 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
61 ((UpdateElectionTerm) message).getVotedFor());
62 } else if(persistence.isRecoveryApplicable()) {
63 if (message instanceof SnapshotOffer) {
64 onRecoveredSnapshot((SnapshotOffer) message);
65 } else if (message instanceof ReplicatedLogEntry) {
66 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
67 } else if (message instanceof ApplyLogEntries) {
68 // Handle this message for backwards compatibility with pre-Lithium versions.
69 onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex());
70 } else if (message instanceof ApplyJournalEntries) {
71 onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
72 } else if (message instanceof DeleteEntries) {
73 replicatedLog().removeFrom(((DeleteEntries) message).getFromIndex());
74 } else if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) {
75 // Handle this message for backwards compatibility with pre-Lithium versions.
76 replicatedLog().removeFrom(((org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) message).getFromIndex());
77 } else if (message instanceof RecoveryCompleted) {
78 onRecoveryCompletedMessage();
79 possiblyRestoreFromSnapshot();
80 recoveryComplete = true;
82 } else if (message instanceof RecoveryCompleted) {
83 recoveryComplete = true;
85 if(dataRecoveredWithPersistenceDisabled) {
86 // Data persistence is disabled but we recovered some data entries so we must have just
87 // transitioned to disabled or a persistence backup was restored. Either way, delete all the
88 // messages from the akka journal for efficiency and so that we do not end up with consistency
89 // issues in case persistence is -re-enabled.
90 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
92 // Delete all the akka snapshots as they will not be needed
93 persistentProvider.deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
94 scala.Long.MaxValue(), 0L, 0L));
96 // Since we cleaned out the journal, we need to re-write the current election info.
97 context.getTermInformation().updateAndPersist(context.getTermInformation().getCurrentTerm(),
98 context.getTermInformation().getVotedFor());
101 possiblyRestoreFromSnapshot();
103 boolean isServerConfigPayload = false;
104 if(message instanceof ReplicatedLogEntry){
105 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
106 if(isServerConfigurationPayload(repLogEntry)){
107 isServerConfigPayload = true;
108 context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
112 if(!isServerConfigPayload){
113 dataRecoveredWithPersistenceDisabled = true;
117 return recoveryComplete;
120 private void possiblyRestoreFromSnapshot() {
121 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
122 if(restoreFromSnapshot == null) {
126 if(anyDataRecovered) {
127 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
132 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
133 Snapshot snapshot = (Snapshot) ois.readObject();
135 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
137 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
138 } catch(Exception e) {
139 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
143 private ReplicatedLog replicatedLog() {
144 return context.getReplicatedLog();
147 private void initRecoveryTimer() {
148 if(recoveryTimer == null) {
149 recoveryTimer = Stopwatch.createStarted();
153 private void onRecoveredSnapshot(SnapshotOffer offer) {
154 if(log.isDebugEnabled()) {
155 log.debug("{}: SnapshotOffer called..", context.getId());
160 Snapshot snapshot = (Snapshot) offer.snapshot();
162 // Create a replicated log with the snapshot information
163 // The replicated log can be used later on to retrieve this snapshot
164 // when we need to install it on a peer
166 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
167 context.setLastApplied(snapshot.getLastAppliedIndex());
168 context.setCommitIndex(snapshot.getLastAppliedIndex());
169 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
171 Stopwatch timer = Stopwatch.createStarted();
173 // Apply the snapshot to the actors state
174 cohort.applyRecoverySnapshot(snapshot.getState());
176 if (snapshot.getServerConfiguration() != null) {
177 context.updatePeerIds(snapshot.getServerConfiguration());
181 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
182 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
183 replicatedLog().getSnapshotTerm(), replicatedLog().size());
186 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
187 if(log.isDebugEnabled()) {
188 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
189 logEntry.getIndex(), logEntry.size());
192 if(isServerConfigurationPayload(logEntry)){
193 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
195 replicatedLog().append(logEntry);
198 private void onRecoveredApplyLogEntries(long toIndex) {
199 long lastUnappliedIndex = context.getLastApplied() + 1;
201 if(log.isDebugEnabled()) {
202 // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
203 // but the entry itself has made it to that state and recovered via the snapshot
204 log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
205 context.getId(), lastUnappliedIndex, toIndex);
208 long lastApplied = lastUnappliedIndex - 1;
209 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
210 ReplicatedLogEntry logEntry = replicatedLog().get(i);
211 if(logEntry != null) {
213 batchRecoveredLogEntry(logEntry);
215 // Shouldn't happen but cover it anyway.
216 log.error("{}: Log entry not found for index {}", context.getId(), i);
221 context.setLastApplied(lastApplied);
222 context.setCommitIndex(lastApplied);
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() {
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 - " +
260 "Persistence Id = " + context.getId() +
261 " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
262 "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
263 replicatedLog().getSnapshotTerm(), replicatedLog().size());
266 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
267 return (repLogEntry.getData() instanceof ServerConfigurationPayload);