Improve FilesystemSchemaSourceCache mkdirs handling
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / repo / util / FilesystemSchemaSourceCache.java
1 /*
2  * Copyright (c) 2014 Cisco 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.yangtools.yang.model.repo.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
13 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
14
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.collect.Lists;
17 import com.google.common.util.concurrent.FluentFuture;
18 import java.io.File;
19 import java.io.FilenameFilter;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.nio.file.FileVisitResult;
23 import java.nio.file.Files;
24 import java.nio.file.Path;
25 import java.nio.file.SimpleFileVisitor;
26 import java.nio.file.StandardCopyOption;
27 import java.nio.file.attribute.BasicFileAttributes;
28 import java.time.format.DateTimeParseException;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.opendaylight.yangtools.yang.common.Revision;
37 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
38 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
42 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Cache implementation that stores schemas in form of files under provided folder.
49  */
50 public final class FilesystemSchemaSourceCache<T extends SchemaSourceRepresentation>
51         extends AbstractSchemaSourceCache<T> {
52
53     private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaSourceCache.class);
54
55     // Init storage adapters
56     private static final Map<Class<? extends SchemaSourceRepresentation>,
57             StorageAdapter<? extends SchemaSourceRepresentation>> STORAGE_ADAPTERS = Collections.singletonMap(
58                     YangTextSchemaSource.class, new YangTextSchemaStorageAdapter());
59
60     private static final Pattern CACHED_FILE_PATTERN =
61             Pattern.compile("(?<moduleName>[^@]+)" + "(@(?<revision>" + Revision.STRING_FORMAT_PATTERN + "))?");
62
63     private final Class<T> representation;
64     private final File storageDirectory;
65
66     public FilesystemSchemaSourceCache(
67             final SchemaSourceRegistry consumer, final Class<T> representation, final File storageDirectory) {
68         super(consumer, representation, Costs.LOCAL_IO);
69         this.representation = representation;
70         this.storageDirectory = requireNonNull(storageDirectory);
71
72         checkSupportedRepresentation(representation);
73
74         checkArgument(storageDirectory.mkdirs() || storageDirectory.isDirectory(),
75                 "Unable to create cache directory at %s", storageDirectory);
76         checkArgument(storageDirectory.canWrite());
77         checkArgument(storageDirectory.canRead());
78
79         init();
80     }
81
82     private static void checkSupportedRepresentation(final Class<? extends SchemaSourceRepresentation> representation) {
83         for (final Class<? extends SchemaSourceRepresentation> supportedRepresentation : STORAGE_ADAPTERS.keySet()) {
84             if (supportedRepresentation.isAssignableFrom(representation)) {
85                 return;
86             }
87         }
88
89         throw new IllegalArgumentException(String.format(
90                    "This cache does not support representation: %s, supported representations are: %s",
91                    representation, STORAGE_ADAPTERS.keySet()));
92     }
93
94     /**
95      * Restore cache state.
96      */
97     private void init() {
98
99         final CachedModulesFileVisitor fileVisitor = new CachedModulesFileVisitor();
100         try {
101             Files.walkFileTree(storageDirectory.toPath(), fileVisitor);
102         } catch (final IOException e) {
103             LOG.warn("Unable to restore cache from {}. Starting with empty cache", storageDirectory);
104             return;
105         }
106
107         for (final SourceIdentifier cachedSchema : fileVisitor.getCachedSchemas()) {
108             register(cachedSchema);
109         }
110     }
111
112     @Override
113     public synchronized FluentFuture<? extends T> getSource(
114             final SourceIdentifier sourceIdentifier) {
115         final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
116         if (file.exists() && file.canRead()) {
117             LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
118             final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
119                     file);
120             return immediateFluentFuture(representation.cast(restored));
121         }
122
123         LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
124         return immediateFailedFluentFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
125     }
126
127     @Override
128     protected synchronized void offer(final T source) {
129         LOG.trace("Source {} offered to cache", source.getIdentifier());
130         final File file = sourceIdToFile(source);
131         if (file.exists()) {
132             LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
133             return;
134         }
135
136         storeSource(file, source);
137         register(source.getIdentifier());
138         LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
139     }
140
141     private File sourceIdToFile(final T source) {
142         return sourceIdToFile(source.getIdentifier(), storageDirectory);
143     }
144
145     static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
146         final Optional<Revision> rev = identifier.getRevision();
147         final File file;
148         if (!rev.isPresent()) {
149             // FIXME: this does not look right
150             file = findFileWithNewestRev(identifier, storageDirectory);
151         } else {
152             file = new File(storageDirectory, identifier.toYangFilename());
153         }
154         return file;
155     }
156
157     private static File findFileWithNewestRev(final SourceIdentifier identifier, final File storageDirectory) {
158         File[] files = storageDirectory.listFiles(new FilenameFilter() {
159             final Pattern pat = Pattern.compile(Pattern.quote(identifier.getName())
160                     + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)");
161
162             @Override
163             public boolean accept(final File dir, final String name) {
164                 return pat.matcher(name).matches();
165             }
166         });
167
168         if (files.length == 0) {
169             return new File(storageDirectory, identifier.toYangFilename());
170         }
171         if (files.length == 1) {
172             return files[0];
173         }
174
175         File file = null;
176         TreeMap<Optional<Revision>, File> map = new TreeMap<>(Revision::compare);
177         for (File sorted : files) {
178             String fileName = sorted.getName();
179             Matcher match = Revision.STRING_FORMAT_PATTERN.matcher(fileName);
180             if (match.find()) {
181                 String revStr = match.group();
182                 Revision rev;
183                 try {
184                     rev = Revision.of(revStr);
185                 } catch (final DateTimeParseException e) {
186                     LOG.info("Unable to parse date from yang file name {}, falling back to not-present", fileName, e);
187                     rev = null;
188                 }
189
190                 map.put(Optional.ofNullable(rev), sorted);
191
192             } else {
193                 map.put(Optional.empty(), sorted);
194             }
195         }
196         file = map.lastEntry().getValue();
197
198         return file;
199     }
200
201     private void storeSource(final File file, final T schemaRepresentation) {
202         STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
203     }
204
205     private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
206
207         private final Class<T> supportedType;
208
209         protected StorageAdapter(final Class<T> supportedType) {
210             this.supportedType = supportedType;
211         }
212
213         void store(final File file, final SchemaSourceRepresentation schemaSourceRepresentation) {
214             checkArgument(supportedType.isAssignableFrom(schemaSourceRepresentation.getClass()),
215                     "Cannot store schema source %s, this adapter only supports %s", schemaSourceRepresentation,
216                     supportedType);
217
218             storeAsType(file, supportedType.cast(schemaSourceRepresentation));
219         }
220
221         protected abstract void storeAsType(File file, T cast);
222
223         public T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
224             checkArgument(cachedSource.isFile());
225             checkArgument(cachedSource.exists());
226             checkArgument(cachedSource.canRead());
227             return restoreAsType(sourceIdentifier, cachedSource);
228         }
229
230         protected abstract T restoreAsType(SourceIdentifier sourceIdentifier, File cachedSource);
231     }
232
233     private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
234
235         protected YangTextSchemaStorageAdapter() {
236             super(YangTextSchemaSource.class);
237         }
238
239         @Override
240         protected void storeAsType(final File file, final YangTextSchemaSource cast) {
241             try (InputStream castStream = cast.openStream()) {
242                 Files.copy(castStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
243             } catch (final IOException e) {
244                 throw new IllegalStateException("Cannot store schema source " + cast.getIdentifier() + " to " + file,
245                         e);
246             }
247         }
248
249         @Override
250         public YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
251             return new YangTextSchemaSource(sourceIdentifier) {
252
253                 @Override
254                 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
255                     return toStringHelper;
256                 }
257
258                 @Override
259                 public InputStream openStream() throws IOException {
260                     return Files.newInputStream(cachedSource.toPath());
261                 }
262             };
263         }
264     }
265
266     private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
267         private final List<SourceIdentifier> cachedSchemas = Lists.newArrayList();
268
269         @Override
270         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
271             final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
272             String fileName = file.toFile().getName();
273             fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
274
275             final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
276             if (si.isPresent()) {
277                 LOG.trace("Restoring cached file {} as {}", file, si.get());
278                 cachedSchemas.add(si.get());
279             } else {
280                 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
281                         + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
282             }
283             return fileVisitResult;
284         }
285
286         private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
287             final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
288             if (matcher.matches()) {
289                 final String moduleName = matcher.group("moduleName");
290                 final String revision = matcher.group("revision");
291                 return Optional.of(RevisionSourceIdentifier.create(moduleName, Revision.ofNullable(revision)));
292             }
293             return Optional.empty();
294         }
295
296         @Override
297         public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
298             LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
299             return FileVisitResult.CONTINUE;
300         }
301
302         public List<SourceIdentifier> getCachedSchemas() {
303             return cachedSchemas;
304         }
305     }
306 }