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.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
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 RaftActorBehavior currentBehavior;
34 private final RaftActorRecoveryCohort cohort;
36 private int currentRecoveryBatchCount;
37 private boolean dataRecoveredWithPersistenceDisabled;
38 private boolean anyDataRecovered;
40 private Stopwatch recoveryTimer;
41 private final Logger log;
43 RaftActorRecoverySupport(RaftActorContext context, RaftActorBehavior currentBehavior,
44 RaftActorRecoveryCohort cohort) {
45 this.context = context;
46 this.currentBehavior = currentBehavior;
48 this.log = context.getLogger();
51 boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
52 log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
54 anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
56 boolean recoveryComplete = false;
57 DataPersistenceProvider persistence = context.getPersistenceProvider();
58 if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm) {
59 // Handle this message for backwards compatibility with pre-Lithium versions.
60 org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm update =
61 (org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm)message;
62 context.getTermInformation().update(update.getCurrentTerm(), update.getVotedFor());
63 } else if (message instanceof UpdateElectionTerm) {
64 context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
65 ((UpdateElectionTerm) message).getVotedFor());
66 } else if(persistence.isRecoveryApplicable()) {
67 if (message instanceof SnapshotOffer) {
68 onRecoveredSnapshot((SnapshotOffer) message);
69 } else if (message instanceof ReplicatedLogEntry) {
70 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
71 } else if (message instanceof ApplyLogEntries) {
72 // Handle this message for backwards compatibility with pre-Lithium versions.
73 onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex());
74 } else if (message instanceof ApplyJournalEntries) {
75 onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
76 } else if (message instanceof DeleteEntries) {
77 replicatedLog().removeFrom(((DeleteEntries) message).getFromIndex());
78 } else if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) {
79 // Handle this message for backwards compatibility with pre-Lithium versions.
80 replicatedLog().removeFrom(((org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) message).getFromIndex());
81 } else if (message instanceof RecoveryCompleted) {
82 onRecoveryCompletedMessage();
83 possiblyRestoreFromSnapshot();
84 recoveryComplete = true;
86 } else if (message instanceof RecoveryCompleted) {
87 recoveryComplete = true;
89 if(dataRecoveredWithPersistenceDisabled) {
90 // Data persistence is disabled but we recovered some data entries so we must have just
91 // transitioned to disabled or a persistence backup was restored. Either way, delete all the
92 // messages from the akka journal for efficiency and so that we do not end up with consistency
93 // issues in case persistence is -re-enabled.
94 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
96 // Delete all the akka snapshots as they will not be needed
97 persistentProvider.deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
98 scala.Long.MaxValue()));
100 // Since we cleaned out the journal, we need to re-write the current election info.
101 context.getTermInformation().updateAndPersist(context.getTermInformation().getCurrentTerm(),
102 context.getTermInformation().getVotedFor());
105 possiblyRestoreFromSnapshot();
107 boolean isServerConfigPayload = false;
108 if(message instanceof ReplicatedLogEntry){
109 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
110 if(isServerConfigurationPayload(repLogEntry)){
111 isServerConfigPayload = true;
112 context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
116 if(!isServerConfigPayload){
117 dataRecoveredWithPersistenceDisabled = true;
121 return recoveryComplete;
124 private void possiblyRestoreFromSnapshot() {
125 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
126 if(restoreFromSnapshot == null) {
130 if(anyDataRecovered) {
131 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
136 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
137 Snapshot snapshot = (Snapshot) ois.readObject();
139 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
141 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
142 } catch(Exception e) {
143 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
147 private ReplicatedLog replicatedLog() {
148 return context.getReplicatedLog();
151 private void initRecoveryTimer() {
152 if(recoveryTimer == null) {
153 recoveryTimer = Stopwatch.createStarted();
157 private void onRecoveredSnapshot(SnapshotOffer offer) {
158 if(log.isDebugEnabled()) {
159 log.debug("{}: SnapshotOffer called..", context.getId());
164 Snapshot snapshot = (Snapshot) offer.snapshot();
166 // Create a replicated log with the snapshot information
167 // The replicated log can be used later on to retrieve this snapshot
168 // when we need to install it on a peer
170 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior));
171 context.setLastApplied(snapshot.getLastAppliedIndex());
172 context.setCommitIndex(snapshot.getLastAppliedIndex());
173 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
175 Stopwatch timer = Stopwatch.createStarted();
177 // Apply the snapshot to the actors state
178 cohort.applyRecoverySnapshot(snapshot.getState());
180 if (snapshot.getServerConfiguration() != null) {
181 context.updatePeerIds(snapshot.getServerConfiguration());
185 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
186 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
187 replicatedLog().getSnapshotTerm(), replicatedLog().size());
190 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
191 if(log.isDebugEnabled()) {
192 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
193 logEntry.getIndex(), logEntry.size());
196 if(isServerConfigurationPayload(logEntry)){
197 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
199 replicatedLog().append(logEntry);
202 private void onRecoveredApplyLogEntries(long toIndex) {
203 long lastUnappliedIndex = context.getLastApplied() + 1;
205 if(log.isDebugEnabled()) {
206 // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
207 // but the entry itself has made it to that state and recovered via the snapshot
208 log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
209 context.getId(), lastUnappliedIndex, toIndex);
212 long lastApplied = lastUnappliedIndex - 1;
213 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
214 ReplicatedLogEntry logEntry = replicatedLog().get(i);
215 if(logEntry != null) {
217 batchRecoveredLogEntry(logEntry);
219 // Shouldn't happen but cover it anyway.
220 log.error("{}: Log entry not found for index {}", context.getId(), i);
225 context.setLastApplied(lastApplied);
226 context.setCommitIndex(lastApplied);
229 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
232 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
233 if(!isServerConfigurationPayload(logEntry)){
234 if(currentRecoveryBatchCount == 0) {
235 cohort.startLogRecoveryBatch(batchSize);
238 cohort.appendRecoveredLogEntry(logEntry.getData());
240 if(++currentRecoveryBatchCount >= batchSize) {
241 endCurrentLogRecoveryBatch();
246 private void endCurrentLogRecoveryBatch() {
247 cohort.applyCurrentLogRecoveryBatch();
248 currentRecoveryBatchCount = 0;
251 private void onRecoveryCompletedMessage() {
252 if(currentRecoveryBatchCount > 0) {
253 endCurrentLogRecoveryBatch();
256 String recoveryTime = "";
257 if(recoveryTimer != null) {
258 recoveryTimer.stop();
259 recoveryTime = " in " + recoveryTimer.toString();
260 recoveryTimer = null;
263 log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
264 "Persistence Id = " + context.getId() +
265 " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
266 "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
267 replicatedLog().getSnapshotTerm(), replicatedLog().size());
270 private boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
271 return (repLogEntry.getData() instanceof ServerConfigurationPayload);