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 onRecoveryCompletedMessage();
98 possiblyRestoreFromSnapshot();
100 boolean isServerConfigPayload = false;
101 if(message instanceof ReplicatedLogEntry){
102 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
103 if(isServerConfigurationPayload(repLogEntry)){
104 isServerConfigPayload = true;
105 context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
109 if(!isServerConfigPayload){
110 dataRecoveredWithPersistenceDisabled = true;
114 return recoveryComplete;
117 private void possiblyRestoreFromSnapshot() {
118 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
119 if(restoreFromSnapshot == null) {
123 if(anyDataRecovered) {
124 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
129 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
130 Snapshot snapshot = (Snapshot) ois.readObject();
132 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
134 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
135 } catch(Exception e) {
136 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
140 private ReplicatedLog replicatedLog() {
141 return context.getReplicatedLog();
144 private void initRecoveryTimer() {
145 if(recoveryTimer == null) {
146 recoveryTimer = Stopwatch.createStarted();
150 private void onRecoveredSnapshot(SnapshotOffer offer) {
151 if(log.isDebugEnabled()) {
152 log.debug("{}: SnapshotOffer called..", context.getId());
157 Snapshot snapshot = (Snapshot) offer.snapshot();
159 // Create a replicated log with the snapshot information
160 // The replicated log can be used later on to retrieve this snapshot
161 // when we need to install it on a peer
163 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
164 context.setLastApplied(snapshot.getLastAppliedIndex());
165 context.setCommitIndex(snapshot.getLastAppliedIndex());
166 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
168 Stopwatch timer = Stopwatch.createStarted();
170 // Apply the snapshot to the actors state
171 cohort.applyRecoverySnapshot(snapshot.getState());
173 if (snapshot.getServerConfiguration() != null) {
174 context.updatePeerIds(snapshot.getServerConfiguration());
178 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
179 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
180 replicatedLog().getSnapshotTerm(), replicatedLog().size());
183 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
184 if(log.isDebugEnabled()) {
185 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
186 logEntry.getIndex(), logEntry.size());
189 if(isServerConfigurationPayload(logEntry)){
190 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
192 replicatedLog().append(logEntry);
195 private void onRecoveredApplyLogEntries(long toIndex) {
196 long lastUnappliedIndex = context.getLastApplied() + 1;
198 if(log.isDebugEnabled()) {
199 // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
200 // but the entry itself has made it to that state and recovered via the snapshot
201 log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
202 context.getId(), lastUnappliedIndex, toIndex);
205 long lastApplied = lastUnappliedIndex - 1;
206 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
207 ReplicatedLogEntry logEntry = replicatedLog().get(i);
208 if(logEntry != null) {
210 batchRecoveredLogEntry(logEntry);
212 // Shouldn't happen but cover it anyway.
213 log.error("{}: Log entry not found for index {}", context.getId(), i);
218 context.setLastApplied(lastApplied);
219 context.setCommitIndex(lastApplied);
222 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
225 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
226 if(!isServerConfigurationPayload(logEntry)){
227 if(currentRecoveryBatchCount == 0) {
228 cohort.startLogRecoveryBatch(batchSize);
231 cohort.appendRecoveredLogEntry(logEntry.getData());
233 if(++currentRecoveryBatchCount >= batchSize) {
234 endCurrentLogRecoveryBatch();
239 private void endCurrentLogRecoveryBatch() {
240 cohort.applyCurrentLogRecoveryBatch();
241 currentRecoveryBatchCount = 0;
244 private void onRecoveryCompletedMessage() {
245 if(currentRecoveryBatchCount > 0) {
246 endCurrentLogRecoveryBatch();
249 String recoveryTime = "";
250 if(recoveryTimer != null) {
251 recoveryTimer.stop();
252 recoveryTime = " in " + recoveryTimer.toString();
253 recoveryTimer = null;
256 log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
257 "Persistence Id = " + context.getId() +
258 " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
259 "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
260 replicatedLog().getSnapshotTerm(), replicatedLog().size());
263 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
264 return (repLogEntry.getData() instanceof ServerConfigurationPayload);