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