128be91f42570d687ed13d1cac666cc906a7763e
[yangtools.git] / yang / yang-repo-fs / src / main / java / org / opendaylight / yangtools / yang / model / repo / fs / 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.fs;
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.util.concurrent.FluentFuture;
16 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
17 import java.io.File;
18 import java.io.FilenameFilter;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.nio.file.FileVisitResult;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.SimpleFileVisitor;
25 import java.nio.file.StandardCopyOption;
26 import java.nio.file.attribute.BasicFileAttributes;
27 import java.time.format.DateTimeParseException;
28 import java.util.ArrayList;
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.AbstractSchemaSourceCache;
43 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
44 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Cache implementation that stores schemas in form of files under provided folder.
50  */
51 public final class FilesystemSchemaSourceCache<T extends SchemaSourceRepresentation>
52         extends AbstractSchemaSourceCache<T> {
53
54     private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaSourceCache.class);
55
56     // Init storage adapters
57     private static final Map<Class<? extends SchemaSourceRepresentation>,
58             StorageAdapter<? extends SchemaSourceRepresentation>> STORAGE_ADAPTERS = Collections.singletonMap(
59                     YangTextSchemaSource.class, new YangTextSchemaStorageAdapter());
60
61     private static final Pattern CACHED_FILE_PATTERN =
62             Pattern.compile("(?<moduleName>[^@]+)" + "(@(?<revision>" + Revision.STRING_FORMAT_PATTERN + "))?");
63
64     private final Class<T> representation;
65     private final File storageDirectory;
66
67     public FilesystemSchemaSourceCache(
68             final SchemaSourceRegistry consumer, final Class<T> representation, final File storageDirectory) {
69         super(consumer, representation, Costs.LOCAL_IO);
70         this.representation = representation;
71         this.storageDirectory = requireNonNull(storageDirectory);
72
73         checkSupportedRepresentation(representation);
74
75         checkArgument(storageDirectory.mkdirs() || storageDirectory.isDirectory(),
76                 "Unable to create cache directory at %s", storageDirectory);
77         checkArgument(storageDirectory.canWrite());
78         checkArgument(storageDirectory.canRead());
79
80         init();
81     }
82
83     private static void checkSupportedRepresentation(final Class<? extends SchemaSourceRepresentation> representation) {
84         for (final Class<? extends SchemaSourceRepresentation> supportedRepresentation : STORAGE_ADAPTERS.keySet()) {
85             if (supportedRepresentation.isAssignableFrom(representation)) {
86                 return;
87             }
88         }
89
90         throw new IllegalArgumentException(String.format(
91                    "This cache does not support representation: %s, supported representations are: %s",
92                    representation, STORAGE_ADAPTERS.keySet()));
93     }
94
95     /**
96      * Restore cache state.
97      */
98     private void init() {
99
100         final CachedModulesFileVisitor fileVisitor = new CachedModulesFileVisitor();
101         try {
102             Files.walkFileTree(storageDirectory.toPath(), fileVisitor);
103         } catch (final IOException e) {
104             LOG.warn("Unable to restore cache from {}. Starting with an empty cache", storageDirectory, e);
105             return;
106         }
107
108         fileVisitor.getCachedSchemas().stream().forEach(this::register);
109     }
110
111     @Override
112     public synchronized FluentFuture<? extends T> getSource(final SourceIdentifier sourceIdentifier) {
113         final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
114         if (file.exists() && file.canRead()) {
115             LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
116             final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
117                     file);
118             return immediateFluentFuture(representation.cast(restored));
119         }
120
121         LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
122         return immediateFailedFluentFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
123     }
124
125     @Override
126     protected synchronized void offer(final T source) {
127         LOG.trace("Source {} offered to cache", source.getIdentifier());
128         final File file = sourceIdToFile(source);
129         if (file.exists()) {
130             LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
131             return;
132         }
133
134         storeSource(file, source);
135         register(source.getIdentifier());
136         LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
137     }
138
139     private File sourceIdToFile(final T source) {
140         return sourceIdToFile(source.getIdentifier(), storageDirectory);
141     }
142
143     static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
144         final Optional<Revision> rev = identifier.getRevision();
145         final File file;
146         if (rev.isEmpty()) {
147             // FIXME: this does not look right
148             file = findFileWithNewestRev(identifier, storageDirectory);
149         } else {
150             file = new File(storageDirectory, identifier.toYangFilename());
151         }
152         return file;
153     }
154
155     @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE",
156             justification = "listFiles is analyzed to return null")
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         // FIXME: use java.nio.filePath
222         protected abstract void storeAsType(File file, T cast);
223
224         T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
225             checkArgument(cachedSource.isFile());
226             checkArgument(cachedSource.exists());
227             checkArgument(cachedSource.canRead());
228             return restoreAsType(sourceIdentifier, cachedSource);
229         }
230
231         abstract T restoreAsType(SourceIdentifier sourceIdentifier, File cachedSource);
232     }
233
234     private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
235
236         protected YangTextSchemaStorageAdapter() {
237             super(YangTextSchemaSource.class);
238         }
239
240         @Override
241         @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
242             justification = "https://github.com/spotbugs/spotbugs/issues/600")
243         protected void storeAsType(final File file, final YangTextSchemaSource cast) {
244             try (InputStream castStream = cast.openStream()) {
245                 Files.copy(castStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
246             } catch (final IOException e) {
247                 throw new IllegalStateException("Cannot store schema source " + cast.getIdentifier() + " to " + file,
248                         e);
249             }
250         }
251
252         @Override
253         YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
254             return YangTextSchemaSource.forPath(cachedSource.toPath(), sourceIdentifier);
255         }
256     }
257
258     private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
259         private final List<SourceIdentifier> cachedSchemas = new ArrayList<>();
260
261         @Override
262         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
263             final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
264             String fileName = file.toFile().getName();
265             fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
266
267             final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
268             if (si.isPresent()) {
269                 LOG.trace("Restoring cached file {} as {}", file, si.get());
270                 cachedSchemas.add(si.get());
271             } else {
272                 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
273                         + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
274             }
275             return fileVisitResult;
276         }
277
278         private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
279             final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
280             if (matcher.matches()) {
281                 final String moduleName = matcher.group("moduleName");
282                 final String revision = matcher.group("revision");
283                 return Optional.of(RevisionSourceIdentifier.create(moduleName, Revision.ofNullable(revision)));
284             }
285             return Optional.empty();
286         }
287
288         @Override
289         public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
290             LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
291             return FileVisitResult.CONTINUE;
292         }
293
294         public List<SourceIdentifier> getCachedSchemas() {
295             return cachedSchemas;
296         }
297     }
298 }