BUG-5626: remove ApplyLogEntries
[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             possiblyRestoreFromSnapshot();
98         } else {
99             boolean isServerConfigPayload = false;
100             if(message instanceof ReplicatedLogEntry){
101                 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
102                 if(isServerConfigurationPayload(repLogEntry)){
103                     isServerConfigPayload = true;
104                     context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
105                 }
106             }
107
108             if(!isServerConfigPayload){
109                 dataRecoveredWithPersistenceDisabled = true;
110             }
111         }
112
113         return recoveryComplete;
114     }
115
116     private void possiblyRestoreFromSnapshot() {
117         byte[] restoreFromSnapshot = cohort.getRestoreFromSnapshot();
118         if(restoreFromSnapshot == null) {
119             return;
120         }
121
122         if(anyDataRecovered) {
123             log.warn("{}: The provided restore snapshot was not applied because the persistence store is not empty",
124                     context.getId());
125             return;
126         }
127
128         try(ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(restoreFromSnapshot))) {
129             Snapshot snapshot = (Snapshot) ois.readObject();
130
131             log.debug("{}: Deserialized restore snapshot: {}", context.getId(), snapshot);
132
133             context.getSnapshotManager().apply(new ApplySnapshot(snapshot));
134         } catch(Exception e) {
135             log.error("{}: Error deserializing snapshot restore", context.getId(), e);
136         }
137     }
138
139     private ReplicatedLog replicatedLog() {
140         return context.getReplicatedLog();
141     }
142
143     private void initRecoveryTimer() {
144         if(recoveryTimer == null) {
145             recoveryTimer = Stopwatch.createStarted();
146         }
147     }
148
149     private void onRecoveredSnapshot(SnapshotOffer offer) {
150         if(log.isDebugEnabled()) {
151             log.debug("{}: SnapshotOffer called..", context.getId());
152         }
153
154         initRecoveryTimer();
155
156         Snapshot snapshot = (Snapshot) offer.snapshot();
157
158         // Create a replicated log with the snapshot information
159         // The replicated log can be used later on to retrieve this snapshot
160         // when we need to install it on a peer
161
162         context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context));
163         context.setLastApplied(snapshot.getLastAppliedIndex());
164         context.setCommitIndex(snapshot.getLastAppliedIndex());
165         context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
166
167         Stopwatch timer = Stopwatch.createStarted();
168
169         // Apply the snapshot to the actors state
170         cohort.applyRecoverySnapshot(snapshot.getState());
171
172         if (snapshot.getServerConfiguration() != null) {
173             context.updatePeerIds(snapshot.getServerConfiguration());
174         }
175
176         timer.stop();
177         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
178                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
179                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
180     }
181
182     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
183         if(log.isDebugEnabled()) {
184             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
185                     logEntry.getIndex(), logEntry.size());
186         }
187
188         if(isServerConfigurationPayload(logEntry)){
189             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
190         }
191         replicatedLog().append(logEntry);
192     }
193
194     private void onRecoveredApplyLogEntries(long toIndex) {
195         long lastUnappliedIndex = context.getLastApplied() + 1;
196
197         if(log.isDebugEnabled()) {
198             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
199             // but the entry itself has made it to that state and recovered via the snapshot
200             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
201                     context.getId(), lastUnappliedIndex, toIndex);
202         }
203
204         long lastApplied = lastUnappliedIndex - 1;
205         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
206             ReplicatedLogEntry logEntry = replicatedLog().get(i);
207             if(logEntry != null) {
208                 lastApplied++;
209                 batchRecoveredLogEntry(logEntry);
210             } else {
211                 // Shouldn't happen but cover it anyway.
212                 log.error("{}: Log entry not found for index {}", context.getId(), i);
213                 break;
214             }
215         }
216
217         context.setLastApplied(lastApplied);
218         context.setCommitIndex(lastApplied);
219     }
220
221     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
222         initRecoveryTimer();
223
224         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
225         if(!isServerConfigurationPayload(logEntry)){
226             if(currentRecoveryBatchCount == 0) {
227                 cohort.startLogRecoveryBatch(batchSize);
228             }
229
230             cohort.appendRecoveredLogEntry(logEntry.getData());
231
232             if(++currentRecoveryBatchCount >= batchSize) {
233                 endCurrentLogRecoveryBatch();
234             }
235         }
236     }
237
238     private void endCurrentLogRecoveryBatch() {
239         cohort.applyCurrentLogRecoveryBatch();
240         currentRecoveryBatchCount = 0;
241     }
242
243     private void onRecoveryCompletedMessage() {
244         if(currentRecoveryBatchCount > 0) {
245             endCurrentLogRecoveryBatch();
246         }
247
248         String recoveryTime = "";
249         if(recoveryTimer != null) {
250             recoveryTimer.stop();
251             recoveryTime = " in " + recoveryTimer.toString();
252             recoveryTimer = null;
253         }
254
255         log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
256                  "Persistence Id =  " + context.getId() +
257                  " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
258                  "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
259                  replicatedLog().getSnapshotTerm(), replicatedLog().size());
260     }
261
262     private static boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
263         return (repLogEntry.getData() instanceof ServerConfigurationPayload);
264     }
265 }