2 * Copyright (c) 2017 Brocade Communications Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.cluster.persistence;
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;
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;
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.
58 * @author Thomas Pantelis
60 public class LocalSnapshotStore extends SnapshotStore {
61 private static final Logger LOG = LoggerFactory.getLogger(LocalSnapshotStore.class);
63 private static final int PERSISTENCE_ID_START_INDEX = "snapshot-".length();
65 private final ExecutionContext executionContext;
66 private final int maxLoadAttempts;
67 private final File snapshotDir;
69 public LocalSnapshotStore(final Config config) {
70 this.executionContext = context().system().dispatchers().lookup(config.getString("stream-dispatcher"));
71 snapshotDir = new File(config.getString("dir"));
73 int localMaxLoadAttempts = config.getInt("max-load-attempts");
74 maxLoadAttempts = localMaxLoadAttempts > 0 ? localMaxLoadAttempts : 1;
76 LOG.debug("LocalSnapshotStore ctor: snapshotDir: {}, maxLoadAttempts: {}", snapshotDir, maxLoadAttempts);
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());
92 public Future<Optional<SelectedSnapshot>> doLoadAsync(final String persistenceId,
93 final SnapshotSelectionCriteria criteria) {
94 LOG.debug("In doLoadAsync - persistenceId: {}, criteria: {}", persistenceId, criteria);
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.
100 Deque<SnapshotMetadata> metadatas = getSnapshotMetadatas(persistenceId, criteria).stream()
101 .sorted(LocalSnapshotStore::compare).collect(reverse()).stream().limit(maxLoadAttempts)
102 .collect(Collectors.toCollection(ArrayDeque::new));
104 if (metadatas.isEmpty()) {
105 return Futures.successful(Optional.empty());
108 LOG.debug("doLoadAsync - found: {}", metadatas);
110 return Futures.future(() -> doLoad(metadatas), executionContext);
113 private Optional<SelectedSnapshot> doLoad(final Deque<SnapshotMetadata> metadatas) throws IOException {
114 SnapshotMetadata metadata = metadatas.removeFirst();
115 File file = toSnapshotFile(metadata);
117 LOG.debug("doLoad {}", file);
120 Object data = deserialize(file);
122 LOG.debug("deserialized data: {}", data);
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);
128 if (metadatas.isEmpty()) {
132 return doLoad(metadatas);
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);
144 return tryDeserializeAkkaSnapshot(file);
148 private Object tryDeserializeAkkaSnapshot(final File file) throws IOException {
149 LOG.debug("tryDeserializeAkkaSnapshot {}", file);
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.
155 SnapshotSerializer snapshotSerializer = new SnapshotSerializer((ExtendedActorSystem) context().system());
157 try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
158 return ((Snapshot)snapshotSerializer.fromBinary(ByteStreams.toByteArray(in))).data();
163 public Future<Void> doSaveAsync(final SnapshotMetadata metadata, final Object snapshot) {
164 LOG.debug("In doSaveAsync - metadata: {}, snapshot: {}", metadata, snapshot);
166 return Futures.future(() -> doSave(metadata, snapshot), executionContext);
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);
173 LOG.debug("Saving to temp file: {}", temp);
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);
185 LOG.debug("Renaming to: {}", actual);
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);
200 public Future<Void> doDeleteAsync(final SnapshotMetadata metadata) {
201 LOG.debug("In doDeleteAsync - metadata: {}", metadata);
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.
207 return Futures.future(() -> doDelete(metadata), executionContext);
211 public Future<Void> doDeleteAsync(final String persistenceId, final SnapshotSelectionCriteria criteria) {
212 LOG.debug("In doDeleteAsync - persistenceId: {}, criteria: {}", persistenceId, criteria);
214 return Futures.future(() -> doDelete(persistenceId, criteria), executionContext);
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());
221 LOG.debug("Deleting files: {}", files);
223 files.forEach(file -> file.delete());
227 private Void doDelete(final SnapshotMetadata metadata) {
228 final Collection<File> files = getSnapshotFiles(metadata);
230 LOG.debug("Deleting files: {}", files);
232 files.forEach(file -> file.delete());
236 private Collection<File> getSnapshotFiles(final String persistenceId) {
237 String encodedPersistenceId = encode(persistenceId);
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");
246 return Collections.emptyList();
249 if (LOG.isDebugEnabled()) {
250 LOG.debug("getSnapshotFiles for persistenceId: {}, found files: {}", encodedPersistenceId,
251 Arrays.toString(files));
254 return Arrays.asList(files);
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());
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());
271 private static Stream<SnapshotMetadata> toStream(@Nullable final SnapshotMetadata md) {
272 return md != null ? Stream.of(md) : Stream.empty();
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) {
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) {
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()));
301 private static <T> Collector<T, ?, List<T>> reverse() {
302 return Collectors.collectingAndThen(Collectors.toList(), list -> {
303 Collections.reverse(list);
308 private static String encode(final String str) {
310 return URLEncoder.encode(str, StandardCharsets.UTF_8.name());
311 } catch (UnsupportedEncodingException e) {
313 LOG.warn("Error encoding {}", str, e);
318 private static String decode(final String str) {
320 return URLDecoder.decode(str, StandardCharsets.UTF_8.name());
321 } catch (final UnsupportedEncodingException e) {
323 LOG.warn("Error decoding {}", str, e);
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);