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.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
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 ApplyJournalEntries) {
68 onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
69 } else if (message instanceof DeleteEntries) {
70 replicatedLog().removeFrom(((DeleteEntries) message).getFromIndex());
71 } else if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) {
72 // Handle this message for backwards compatibility with pre-Lithium versions.
73 replicatedLog().removeFrom(((org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) message).getFromIndex());
74 } else if (message instanceof RecoveryCompleted) {
75 onRecoveryCompletedMessage();
76 possiblyRestoreFromSnapshot();
77 recoveryComplete = true;
79 } else if (message instanceof RecoveryCompleted) {
80 recoveryComplete = true;
82 if(dataRecoveredWithPersistenceDisabled) {
83 // Data persistence is disabled but we recovered some data entries so we must have just
84 // transitioned to disabled or a persistence backup was restored. Either way, delete all the
85 // messages from the akka journal for efficiency and so that we do not end up with consistency
86 // issues in case persistence is -re-enabled.
87 persistentProvider.deleteMessages(persistentProvider.getLastSequenceNumber());
89 // Delete all the akka snapshots as they will not be needed
90 persistentProvider.deleteSnapshots(new SnapshotSelectionCriteria(scala.Long.MaxValue(),
91 scala.Long.MaxValue(), 0L, 0L));
93 // Since we cleaned out the journal, we need to re-write the current election info.
94 context.getTermInformation().updateAndPersist(context.getTermInformation().getCurrentTerm(),
95 context.getTermInformation().getVotedFor());
98 onRecoveryCompletedMessage();
99 possiblyRestoreFromSnapshot();
101 boolean isServerConfigPayload = false;
102 if(message instanceof ReplicatedLogEntry){
103 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
104 if(isServerConfigurationPayload(repLogEntry)){
105 isServerConfigPayload = true;
106 context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
110 if(!isServerConfigPayload){
111 dataRecoveredWithPersistenceDisabled = true;
115 return recoveryComplete;
118 private void possiblyRestoreFromSnapshot() {
119 byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
120 if(restoreFromSnapshot == null) {
124 if(anyDataRecovered) {
125 log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
130 try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
131 Snapshot snapshot = (Snapshot) ois.readObject();
133 log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
135 context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
136 } catch(Exception e) {
137 log.error("{}: Error deserializing snapshot restore", context.getId(), e);
141 private ReplicatedLog replicatedLog() {
142 return context.getReplicatedLog();
145 private void initRecoveryTimer() {
146 if(recoveryTimer == null) {
147 recoveryTimer = Stopwatch.createStarted();
151 private void onRecoveredSnapshot(SnapshotOffer offer) {
152 if(log.isDebugEnabled()) {
153 log.debug("{}: SnapshotOffer called..", context.getId());
158 Snapshot snapshot = (Snapshot) offer.snapshot();
160 // Create a replicated log with the snapshot information
161 // The replicated log can be used later on to retrieve this snapshot
162 // when we need to install it on a peer
164 context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
165 context.setLastApplied(snapshot.getLastAppliedIndex());
166 context.setCommitIndex(snapshot.getLastAppliedIndex());
167 context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
169 Stopwatch timer = Stopwatch.createStarted();
171 // Apply the snapshot to the actors state
172 cohort.applyRecoverySnapshot(snapshot.getState());
174 if (snapshot.getServerConfiguration() != null) {
175 context.updatePeerIds(snapshot.getServerConfiguration());
179 log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
180 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
181 replicatedLog().getSnapshotTerm(), replicatedLog().size());
184 private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
185 if(log.isDebugEnabled()) {
186 log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
187 logEntry.getIndex(), logEntry.size());
190 if(isServerConfigurationPayload(logEntry)){
191 context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
193 replicatedLog().append(logEntry);
196 private void onRecoveredApplyLogEntries(long toIndex) {
197 long lastUnappliedIndex = context.getLastApplied() + 1;
199 if(log.isDebugEnabled()) {
200 // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
201 // but the entry itself has made it to that state and recovered via the snapshot
202 log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
203 context.getId(), lastUnappliedIndex, toIndex);
206 long lastApplied = lastUnappliedIndex - 1;
207 for (long i = lastUnappliedIndex; i <= toIndex; i++) {
208 ReplicatedLogEntry logEntry = replicatedLog().get(i);
209 if(logEntry != null) {
211 batchRecoveredLogEntry(logEntry);
213 // Shouldn't happen but cover it anyway.
214 log.error("{}: Log entry not found for index {}", context.getId(), i);
219 context.setLastApplied(lastApplied);
220 context.setCommitIndex(lastApplied);
223 private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
226 int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
227 if(!isServerConfigurationPayload(logEntry)){
228 if(currentRecoveryBatchCount == 0) {
229 cohort.startLogRecoveryBatch(batchSize);
232 cohort.appendRecoveredLogEntry(logEntry.getData());
234 if(++currentRecoveryBatchCount >= batchSize) {
235 endCurrentLogRecoveryBatch();
240 private void endCurrentLogRecoveryBatch() {
241 cohort.applyCurrentLogRecoveryBatch();
242 currentRecoveryBatchCount = 0;
245 private void onRecoveryCompletedMessage() {
246 if(currentRecoveryBatchCount > 0) {
247 endCurrentLogRecoveryBatch();
250 String recoveryTime = "";
251 if(recoveryTimer != null) {
252 recoveryTimer.stop();
253 recoveryTime = " in " + recoveryTimer.toString();
254 recoveryTimer = null;
257 log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
258 "Persistence Id = " + context.getId() +
259 " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
260 "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
261 replicatedLog().getSnapshotTerm(), replicatedLog().size());
264 private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
265 return (repLogEntry.getData() instanceof ServerConfigurationPayload);