Bug 8444 - Persistent prefix-based shard cannot load its snapshot
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / persistence / LocalSnapshotStore.java
1 /*
2  * Copyright (c) 2017 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.persistence;
9
10 import akka.actor.ExtendedActorSystem;
11 import akka.dispatch.Futures;
12 import akka.persistence.SelectedSnapshot;
13 import akka.persistence.SnapshotMetadata;
14 import akka.persistence.SnapshotSelectionCriteria;
15 import akka.persistence.serialization.Snapshot;
16 import akka.persistence.serialization.SnapshotSerializer;
17 import akka.persistence.snapshot.japi.SnapshotStore;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.io.ByteStreams;
20 import com.typesafe.config.Config;
21 import java.io.BufferedInputStream;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileOutputStream;
25 import java.io.FilenameFilter;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.ObjectInputStream;
29 import java.io.ObjectOutputStream;
30 import java.io.UnsupportedEncodingException;
31 import java.net.URLDecoder;
32 import java.net.URLEncoder;
33 import java.nio.charset.StandardCharsets;
34 import java.nio.file.Files;
35 import java.nio.file.StandardCopyOption;
36 import java.util.ArrayDeque;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.Deque;
41 import java.util.List;
42 import java.util.Optional;
43 import java.util.stream.Collector;
44 import java.util.stream.Collectors;
45 import java.util.stream.Stream;
46 import javax.annotation.Nullable;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import scala.concurrent.ExecutionContext;
50 import scala.concurrent.Future;
51
52 /**
53  * Akka SnapshotStore implementation backed by the local file system. This class was patterned after akka's
54  * LocalSnapshotStore class and exists because akka's version serializes to a byte[] before persisting
55  * to the file which will fail if the data reaches or exceeds Integer.MAX_VALUE in size. This class avoids that issue
56  * by serializing the data directly to the file.
57  *
58  * @author Thomas Pantelis
59  */
60 public class LocalSnapshotStore extends SnapshotStore {
61     private static final Logger LOG = LoggerFactory.getLogger(LocalSnapshotStore.class);
62
63     private static final int PERSISTENCE_ID_START_INDEX = "snapshot-".length();
64
65     private final ExecutionContext executionContext;
66     private final int maxLoadAttempts;
67     private final File snapshotDir;
68
69     public LocalSnapshotStore(final Config config) {
70         this.executionContext = context().system().dispatchers().lookup(config.getString("stream-dispatcher"));
71         snapshotDir = new File(config.getString("dir"));
72
73         int localMaxLoadAttempts = config.getInt("max-load-attempts");
74         maxLoadAttempts = localMaxLoadAttempts > 0 ? localMaxLoadAttempts : 1;
75
76         LOG.debug("LocalSnapshotStore ctor: snapshotDir: {}, maxLoadAttempts: {}", snapshotDir, maxLoadAttempts);
77     }
78
79     @Override
80     public void preStart() throws Exception {
81         if (!snapshotDir.isDirectory()) {
82             // Try to create the directory, on failure double check if someone else beat us to it.
83             if (!snapshotDir.mkdirs() && !snapshotDir.isDirectory()) {
84                 throw new IOException("Failed to create snapshot directory " + snapshotDir.getCanonicalPath());
85             }
86         }
87
88         super.preStart();
89     }
90
91     @Override
92     public Future<Optional<SelectedSnapshot>> doLoadAsync(final String persistenceId,
93                                                           final SnapshotSelectionCriteria criteria) {
94         LOG.debug("In doLoadAsync - persistenceId: {}, criteria: {}", persistenceId, criteria);
95
96         // Select the youngest 'maxLoadAttempts' snapshots that match the criteria. This may help in situations where
97         // saving of a snapshot could not be completed because of a JVM crash. Hence, an attempt to load that snapshot
98         // will fail but loading an older snapshot may succeed.
99
100         Deque<SnapshotMetadata> metadatas = getSnapshotMetadatas(persistenceId, criteria).stream()
101                 .sorted(LocalSnapshotStore::compare).collect(reverse()).stream().limit(maxLoadAttempts)
102                     .collect(Collectors.toCollection(ArrayDeque::new));
103
104         if (metadatas.isEmpty()) {
105             return Futures.successful(Optional.empty());
106         }
107
108         LOG.debug("doLoadAsync - found: {}", metadatas);
109
110         return Futures.future(() -> doLoad(metadatas), executionContext);
111     }
112
113     private Optional<SelectedSnapshot> doLoad(final Deque<SnapshotMetadata> metadatas) throws IOException {
114         SnapshotMetadata metadata = metadatas.removeFirst();
115         File file = toSnapshotFile(metadata);
116
117         LOG.debug("doLoad {}", file);
118
119         try {
120             Object data = deserialize(file);
121
122             LOG.debug("deserialized data: {}", data);
123
124             return Optional.of(new SelectedSnapshot(metadata, data));
125         } catch (IOException e) {
126             LOG.error("Error loading snapshot file {}, remaining attempts: {}", file, metadatas.size(), e);
127
128             if (metadatas.isEmpty()) {
129                 throw e;
130             }
131
132             return doLoad(metadatas);
133         }
134     }
135
136     private Object deserialize(final File file) throws IOException {
137         try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
138             return in.readObject();
139         } catch (ClassNotFoundException e) {
140             throw new IOException("Error loading snapshot file " + file, e);
141         } catch (IOException e) {
142             LOG.debug("Error loading snapshot file {}", file, e);
143
144             return tryDeserializeAkkaSnapshot(file);
145         }
146     }
147
148     private Object tryDeserializeAkkaSnapshot(final File file) throws IOException {
149         LOG.debug("tryDeserializeAkkaSnapshot {}", file);
150
151         // The snapshot was probably previously stored via akka's LocalSnapshotStore which wraps the data
152         // in a Snapshot instance and uses the SnapshotSerializer to serialize it to a byte[]. So we'll use
153         // the SnapshotSerializer to try to de-serialize it.
154
155         SnapshotSerializer snapshotSerializer = new SnapshotSerializer((ExtendedActorSystem) context().system());
156
157         try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
158             return ((Snapshot)snapshotSerializer.fromBinary(ByteStreams.toByteArray(in))).data();
159         }
160     }
161
162     @Override
163     public Future<Void> doSaveAsync(final SnapshotMetadata metadata, final Object snapshot) {
164         LOG.debug("In doSaveAsync - metadata: {}, snapshot: {}", metadata, snapshot);
165
166         return Futures.future(() -> doSave(metadata, snapshot), executionContext);
167     }
168
169     private Void doSave(final SnapshotMetadata metadata, final Object snapshot) throws IOException {
170         final File actual = toSnapshotFile(metadata);
171         final File temp = File.createTempFile(actual.getName(), null, snapshotDir);
172
173         LOG.debug("Saving to temp file: {}", temp);
174
175         try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(temp))) {
176             out.writeObject(snapshot);
177         } catch (IOException e) {
178             LOG.error("Error saving snapshot file {}. Deleting file..", temp, e);
179             if (!temp.delete()) {
180                 LOG.error("Failed to successfully delete file {}", temp);
181             }
182             throw e;
183         }
184
185         LOG.debug("Renaming to: {}", actual);
186         try {
187             Files.move(temp.toPath(), actual.toPath(), StandardCopyOption.ATOMIC_MOVE);
188         } catch (IOException e) {
189             LOG.warn("Failed to move {} to {}. Deleting {}..", temp, actual, temp, e);
190             if (!temp.delete()) {
191                 LOG.error("Failed to successfully delete file {}", temp);
192             }
193             throw e;
194         }
195
196         return null;
197     }
198
199     @Override
200     public Future<Void> doDeleteAsync(final SnapshotMetadata metadata) {
201         LOG.debug("In doDeleteAsync - metadata: {}", metadata);
202
203         // Multiple snapshot files here mean that there were multiple snapshots for this seqNr - we delete all of them.
204         // Usually snapshot-stores would keep one snapshot per sequenceNr however here in the file-based one we
205         // timestamp snapshots and allow multiple to be kept around (for the same seqNr) if desired.
206
207         return Futures.future(() -> doDelete(metadata), executionContext);
208     }
209
210     @Override
211     public Future<Void> doDeleteAsync(final String persistenceId, final SnapshotSelectionCriteria criteria) {
212         LOG.debug("In doDeleteAsync - persistenceId: {}, criteria: {}", persistenceId, criteria);
213
214         return Futures.future(() -> doDelete(persistenceId, criteria), executionContext);
215     }
216
217     private Void doDelete(final String persistenceId, final SnapshotSelectionCriteria criteria) {
218         final List<File> files = getSnapshotMetadatas(persistenceId, criteria).stream()
219                 .flatMap(md -> Stream.of(toSnapshotFile(md))).collect(Collectors.toList());
220
221         LOG.debug("Deleting files: {}", files);
222
223         files.forEach(file -> file.delete());
224         return null;
225     }
226
227     private Void doDelete(final SnapshotMetadata metadata) {
228         final Collection<File> files = getSnapshotFiles(metadata);
229
230         LOG.debug("Deleting files: {}", files);
231
232         files.forEach(file -> file.delete());
233         return null;
234     }
235
236     private Collection<File> getSnapshotFiles(final String persistenceId) {
237         String encodedPersistenceId = encode(persistenceId);
238
239         File[] files = snapshotDir.listFiles((FilenameFilter) (dir, name) -> {
240             int persistenceIdEndIndex = name.lastIndexOf('-', name.lastIndexOf('-') - 1);
241             return PERSISTENCE_ID_START_INDEX + encodedPersistenceId.length() == persistenceIdEndIndex
242                     && name.startsWith(encodedPersistenceId, PERSISTENCE_ID_START_INDEX) && !name.endsWith(".tmp");
243         });
244
245         if (files == null) {
246             return Collections.emptyList();
247         }
248
249         if (LOG.isDebugEnabled()) {
250             LOG.debug("getSnapshotFiles for persistenceId: {}, found files: {}", encodedPersistenceId,
251                     Arrays.toString(files));
252         }
253
254         return Arrays.asList(files);
255     }
256
257     private Collection<File> getSnapshotFiles(final SnapshotMetadata metadata) {
258         return getSnapshotFiles(metadata.persistenceId()).stream().filter(file -> {
259             SnapshotMetadata possible = extractMetadata(file);
260             return possible != null && possible.sequenceNr() == metadata.sequenceNr()
261                     && (metadata.timestamp() == 0L || possible.timestamp() == metadata.timestamp());
262         }).collect(Collectors.toList());
263     }
264
265     private Collection<SnapshotMetadata> getSnapshotMetadatas(final String persistenceId,
266             final SnapshotSelectionCriteria criteria) {
267         return getSnapshotFiles(persistenceId).stream().flatMap(file -> toStream(extractMetadata(file)))
268                 .filter(md -> criteria.matches(md)).collect(Collectors.toList());
269     }
270
271     private static Stream<SnapshotMetadata> toStream(@Nullable final SnapshotMetadata md) {
272         return md != null ? Stream.of(md) : Stream.empty();
273     }
274
275     @Nullable
276     private static SnapshotMetadata extractMetadata(final File file) {
277         String name = file.getName();
278         int sequenceNumberEndIndex = name.lastIndexOf('-');
279         int persistenceIdEndIndex = name.lastIndexOf('-', sequenceNumberEndIndex - 1);
280         if (PERSISTENCE_ID_START_INDEX >= persistenceIdEndIndex) {
281             return null;
282         }
283
284         try {
285             // Since the persistenceId is url encoded in the filename, we need
286             // to decode relevant filename's part to obtain persistenceId back
287             String persistenceId = decode(name.substring(PERSISTENCE_ID_START_INDEX, persistenceIdEndIndex));
288             long sequenceNumber = Long.parseLong(name.substring(persistenceIdEndIndex + 1, sequenceNumberEndIndex));
289             long timestamp = Long.parseLong(name.substring(sequenceNumberEndIndex + 1));
290             return new SnapshotMetadata(persistenceId, sequenceNumber, timestamp);
291         } catch (NumberFormatException e) {
292             return null;
293         }
294     }
295
296     private File toSnapshotFile(final SnapshotMetadata metadata) {
297         return new File(snapshotDir, String.format("snapshot-%s-%d-%d", encode(metadata.persistenceId()),
298             metadata.sequenceNr(), metadata.timestamp()));
299     }
300
301     private static <T> Collector<T, ?, List<T>> reverse() {
302         return Collectors.collectingAndThen(Collectors.toList(), list -> {
303             Collections.reverse(list);
304             return list;
305         });
306     }
307
308     private static String encode(final String str) {
309         try {
310             return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
311         } catch (UnsupportedEncodingException e) {
312             // Shouldn't happen
313             LOG.warn("Error encoding {}", str, e);
314             return str;
315         }
316     }
317
318     private static String decode(final String str) {
319         try {
320             return URLDecoder.decode(str, StandardCharsets.UTF_8.name());
321         } catch (final UnsupportedEncodingException e) {
322             // Shouldn't happen
323             LOG.warn("Error decoding {}", str, e);
324             return str;
325         }
326     }
327
328     @VisibleForTesting
329     static int compare(final SnapshotMetadata m1, final SnapshotMetadata m2) {
330         return (int) (!m1.persistenceId().equals(m2.persistenceId())
331                 ? m1.persistenceId().compareTo(m2.persistenceId()) :
332             m1.sequenceNr() != m2.sequenceNr() ? m1.sequenceNr() - m2.sequenceNr() :
333                 m1.timestamp() != m2.timestamp() ? m1.timestamp() - m2.timestamp() : 0);
334     }
335 }