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