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