Force install snapshot when follower log is ahead
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActorRecoverySupport.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.raft;
9
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;
23
24 /**
25  * Support class that handles persistence recovery for a RaftActor.
26  *
27  * @author Thomas Pantelis
28  */
29 class RaftActorRecoverySupport {
30     private final RaftActorContext context;
31     private final RaftActorRecoveryCohort cohort;
32
33     private int currentRecoveryBatchCount;
34     private boolean dataRecoveredWithPersistenceDisabled;
35     private boolean anyDataRecovered;
36
37     private Stopwatch recoveryTimer;
38     private final Logger log;
39
40     RaftActorRecoverySupport(final RaftActorContext context, final RaftActorRecoveryCohort cohort) {
41         this.context = context;
42         this.cohort = cohort;
43         this.log = context.getLogger();
44     }
45
46     boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
47         log.trace("{}: handleRecoveryMessage: {}", context.getId(), message);
48
49         anyDataRecovered = anyDataRecovered || !(message instanceof RecoveryCompleted);
50
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;
77             }
78         } else if (message instanceof RecoveryCompleted) {
79             recoveryComplete = true;
80
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());
87
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));
91
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());
95             }
96
97             onRecoveryCompletedMessage();
98             possiblyRestoreFromSnapshot();
99         } else {
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());
106                 }
107             }
108
109             if(!isServerConfigPayload){
110                 dataRecoveredWithPersistenceDisabled = true;
111             }
112         }
113
114         return recoveryComplete;
115     }
116
117     private void possiblyRestoreFromSnapshot() {
118         byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
119         if(restoreFromSnapshot == null) {
120             return;
121         }
122
123         if(anyDataRecovered) {
124             log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
125                     context.getId());
126             return;
127         }
128
129         try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
130             Snapshot snapshot = (Snapshot) ois.readObject();
131
132             log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
133
134             context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
135         } catch(Exception e) {
136             log.error("{}: Error deserializing snapshot restore", context.getId(), e);
137         }
138     }
139
140     private ReplicatedLog replicatedLog() {
141         return context.getReplicatedLog();
142     }
143
144     private void initRecoveryTimer() {
145         if(recoveryTimer == null) {
146             recoveryTimer = Stopwatch.createStarted();
147         }
148     }
149
150     private void onRecoveredSnapshot(SnapshotOffer offer) {
151         if(log.isDebugEnabled()) {
152             log.debug("{}: SnapshotOffer called..", context.getId());
153         }
154
155         initRecoveryTimer();
156
157         Snapshot snapshot = (Snapshot) offer.snapshot();
158
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
162
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());
167
168         Stopwatch timer = Stopwatch.createStarted();
169
170         // Apply the snapshot to the actors state
171         cohort.applyRecoverySnapshot(snapshot.getState());
172
173         if (snapshot.getServerConfiguration() != null) {
174             context.updatePeerIds(snapshot.getServerConfiguration());
175         }
176
177         timer.stop();
178         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
179                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
180                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
181     }
182
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());
187         }
188
189         if(isServerConfigurationPayload(logEntry)){
190             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
191         }
192         replicatedLog().append(logEntry);
193     }
194
195     private void onRecoveredApplyLogEntries(long toIndex) {
196         long lastUnappliedIndex = context.getLastApplied() + 1;
197
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);
203         }
204
205         long lastApplied = lastUnappliedIndex - 1;
206         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
207             ReplicatedLogEntry logEntry = replicatedLog().get(i);
208             if(logEntry != null) {
209                 lastApplied++;
210                 batchRecoveredLogEntry(logEntry);
211             } else {
212                 // Shouldn't happen but cover it anyway.
213                 log.error("{}: Log entry not found for index {}", context.getId(), i);
214                 break;
215             }
216         }
217
218         context.setLastApplied(lastApplied);
219         context.setCommitIndex(lastApplied);
220     }
221
222     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
223         initRecoveryTimer();
224
225         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
226         if(!isServerConfigurationPayload(logEntry)){
227             if(currentRecoveryBatchCount == 0) {
228                 cohort.startLogRecoveryBatch(batchSize);
229             }
230
231             cohort.appendRecoveredLogEntry(logEntry.getData());
232
233             if(++currentRecoveryBatchCount >= batchSize) {
234                 endCurrentLogRecoveryBatch();
235             }
236         }
237     }
238
239     private void endCurrentLogRecoveryBatch() {
240         cohort.applyCurrentLogRecoveryBatch();
241         currentRecoveryBatchCount = 0;
242     }
243
244     private void onRecoveryCompletedMessage() {
245         if(currentRecoveryBatchCount > 0) {
246             endCurrentLogRecoveryBatch();
247         }
248
249         String recoveryTime = "";
250         if(recoveryTimer != null) {
251             recoveryTimer.stop();
252             recoveryTime = " in " + recoveryTimer.toString();
253             recoveryTimer = null;
254         }
255
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());
261     }
262
263     private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
264         return (repLogEntry.getData() instanceof ServerConfigurationPayload);
265     }
266 }