05405dc6dfc2457d9a33a5340a619ba8990064f3
[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 org.opendaylight.controller.cluster.DataPersistenceProvider;
15 import org.opendaylight.controller.cluster.PersistentDataProvider;
16 import org.opendaylight.controller.cluster.raft.base.messages.ApplyJournalEntries;
17 import org.opendaylight.controller.cluster.raft.base.messages.ApplyLogEntries;
18 import org.opendaylight.controller.cluster.raft.base.messages.DeleteEntries;
19 import org.opendaylight.controller.cluster.raft.base.messages.UpdateElectionTerm;
20 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
21 import org.slf4j.Logger;
22
23 /**
24  * Support class that handles persistence recovery for a RaftActor.
25  *
26  * @author Thomas Pantelis
27  */
28 class RaftActorRecoverySupport {
29     private final RaftActorContext context;
30     private final RaftActorBehavior currentBehavior;
31     private final RaftActorRecoveryCohort cohort;
32
33     private int currentRecoveryBatchCount;
34     private boolean dataRecoveredWithPersistenceDisabled;
35
36     private Stopwatch recoveryTimer;
37     private final Logger log;
38
39     RaftActorRecoverySupport(RaftActorContext context, RaftActorBehavior currentBehavior,
40             RaftActorRecoveryCohort cohort) {
41         this.context = context;
42         this.currentBehavior = currentBehavior;
43         this.cohort = cohort;
44         this.log = context.getLogger();
45     }
46
47     boolean handleRecoveryMessage(Object message, PersistentDataProvider persistentProvider) {
48         log.trace("handleRecoveryMessage: {}", message);
49
50         boolean recoveryComplete = false;
51         DataPersistenceProvider persistence = context.getPersistenceProvider();
52         if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm) {
53             // Handle this message for backwards compatibility with pre-Lithium versions.
54             org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm update =
55                     (org.opendaylight.controller.cluster.raft.RaftActor.UpdateElectionTerm)message;
56             context.getTermInformation().update(update.getCurrentTerm(), update.getVotedFor());
57         } else if (message instanceof UpdateElectionTerm) {
58             context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(),
59                     ((UpdateElectionTerm) message).getVotedFor());
60         } else if(persistence.isRecoveryApplicable()) {
61             if (message instanceof SnapshotOffer) {
62                 onRecoveredSnapshot((SnapshotOffer) message);
63             } else if (message instanceof ReplicatedLogEntry) {
64                 onRecoveredJournalLogEntry((ReplicatedLogEntry) message);
65             } else if (message instanceof ApplyLogEntries) {
66                 // Handle this message for backwards compatibility with pre-Lithium versions.
67                 onRecoveredApplyLogEntries(((ApplyLogEntries) message).getToIndex());
68             } else if (message instanceof ApplyJournalEntries) {
69                 onRecoveredApplyLogEntries(((ApplyJournalEntries) message).getToIndex());
70             } else if (message instanceof DeleteEntries) {
71                 replicatedLog().removeFrom(((DeleteEntries) message).getFromIndex());
72             } else if (message instanceof org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) {
73                 // Handle this message for backwards compatibility with pre-Lithium versions.
74                 replicatedLog().removeFrom(((org.opendaylight.controller.cluster.raft.RaftActor.DeleteEntries) message).getFromIndex());
75             } else if (message instanceof RecoveryCompleted) {
76                 onRecoveryCompletedMessage();
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()));
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         } else {
98             boolean isServerConfigPayload = false;
99             if(message instanceof ReplicatedLogEntry){
100                 ReplicatedLogEntry repLogEntry = (ReplicatedLogEntry)message;
101                 if(isServerConfigurationPayload(repLogEntry)){
102                     isServerConfigPayload = true;
103                     context.updatePeerIds((ServerConfigurationPayload)repLogEntry.getData());
104                 }
105             }
106
107             if(!isServerConfigPayload){
108                 dataRecoveredWithPersistenceDisabled = true;
109             }
110         }
111
112         return recoveryComplete;
113     }
114
115     private ReplicatedLog replicatedLog() {
116         return context.getReplicatedLog();
117     }
118
119     private void initRecoveryTimer() {
120         if(recoveryTimer == null) {
121             recoveryTimer = Stopwatch.createStarted();
122         }
123     }
124
125     private void onRecoveredSnapshot(SnapshotOffer offer) {
126         if(log.isDebugEnabled()) {
127             log.debug("{}: SnapshotOffer called..", context.getId());
128         }
129
130         initRecoveryTimer();
131
132         Snapshot snapshot = (Snapshot) offer.snapshot();
133
134         // Create a replicated log with the snapshot information
135         // The replicated log can be used later on to retrieve this snapshot
136         // when we need to install it on a peer
137
138         context.setReplicatedLog(ReplicatedLogImpl.newInstance(snapshot, context, currentBehavior));
139         context.setLastApplied(snapshot.getLastAppliedIndex());
140         context.setCommitIndex(snapshot.getLastAppliedIndex());
141         context.getTermInformation().update(snapshot.getElectionTerm(), snapshot.getElectionVotedFor());
142
143         Stopwatch timer = Stopwatch.createStarted();
144
145         // Apply the snapshot to the actors state
146         cohort.applyRecoverySnapshot(snapshot.getState());
147
148         timer.stop();
149         log.info("Recovery snapshot applied for {} in {}: snapshotIndex={}, snapshotTerm={}, journal-size={}",
150                 context.getId(), timer.toString(), replicatedLog().getSnapshotIndex(),
151                 replicatedLog().getSnapshotTerm(), replicatedLog().size());
152     }
153
154     private void onRecoveredJournalLogEntry(ReplicatedLogEntry logEntry) {
155         if(log.isDebugEnabled()) {
156             log.debug("{}: Received ReplicatedLogEntry for recovery: index: {}, size: {}", context.getId(),
157                     logEntry.getIndex(), logEntry.size());
158         }
159
160         if(isServerConfigurationPayload(logEntry)){
161             context.updatePeerIds((ServerConfigurationPayload)logEntry.getData());
162         }
163         replicatedLog().append(logEntry);
164     }
165
166     private void onRecoveredApplyLogEntries(long toIndex) {
167         long lastUnappliedIndex = context.getLastApplied() + 1;
168
169         if(log.isDebugEnabled()) {
170             // it can happen that lastUnappliedIndex > toIndex, if the AJE is in the persistent journal
171             // but the entry itself has made it to that state and recovered via the snapshot
172             log.debug("{}: Received apply journal entries for recovery, applying to state: {} to {}",
173                     context.getId(), lastUnappliedIndex, toIndex);
174         }
175
176         long lastApplied = lastUnappliedIndex - 1;
177         for (long i = lastUnappliedIndex; i <= toIndex; i++) {
178             ReplicatedLogEntry logEntry = replicatedLog().get(i);
179             if(logEntry != null) {
180                 lastApplied++;
181                 batchRecoveredLogEntry(logEntry);
182             } else {
183                 // Shouldn't happen but cover it anyway.
184                 log.error("Log entry not found for index {}", i);
185                 break;
186             }
187         }
188
189         context.setLastApplied(lastApplied);
190         context.setCommitIndex(lastApplied);
191     }
192
193     private void batchRecoveredLogEntry(ReplicatedLogEntry logEntry) {
194         initRecoveryTimer();
195
196         int batchSize = context.getConfigParams().getJournalRecoveryLogBatchSize();
197         if(!isServerConfigurationPayload(logEntry)){
198             if(currentRecoveryBatchCount == 0) {
199                 cohort.startLogRecoveryBatch(batchSize);
200             }
201
202             cohort.appendRecoveredLogEntry(logEntry.getData());
203
204             if(++currentRecoveryBatchCount >= batchSize) {
205                 endCurrentLogRecoveryBatch();
206             }
207         }
208     }
209
210     private void endCurrentLogRecoveryBatch() {
211         cohort.applyCurrentLogRecoveryBatch();
212         currentRecoveryBatchCount = 0;
213     }
214
215     private void onRecoveryCompletedMessage() {
216         if(currentRecoveryBatchCount > 0) {
217             endCurrentLogRecoveryBatch();
218         }
219
220         String recoveryTime = "";
221         if(recoveryTimer != null) {
222             recoveryTimer.stop();
223             recoveryTime = " in " + recoveryTimer.toString();
224             recoveryTimer = null;
225         }
226
227         log.info("Recovery completed" + recoveryTime + " - Switching actor to Follower - " +
228                  "Persistence Id =  " + context.getId() +
229                  " Last index in log = {}, snapshotIndex = {}, snapshotTerm = {}, " +
230                  "journal-size = {}", replicatedLog().lastIndex(), replicatedLog().getSnapshotIndex(),
231                  replicatedLog().getSnapshotTerm(), replicatedLog().size());
232     }
233
234     private boolean isServerConfigurationPayload(ReplicatedLogEntry repLogEntry){
235         return (repLogEntry.getData() instanceof ServerConfigurationPayload);
236     }
237 }