Remove RevisionSourceIdentifier
[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.SchemaSourceRepresentation;
39 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
41 import org.opendaylight.yangtools.yang.model.repo.spi.AbstractSchemaSourceCache;
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 an empty cache", storageDirectory, e);
104             return;
105         }
106
107         fileVisitor.getCachedSchemas().stream().forEach(this::register);
108     }
109
110     @Override
111     public synchronized FluentFuture<? extends T> getSource(final SourceIdentifier sourceIdentifier) {
112         final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
113         if (file.exists() && file.canRead()) {
114             LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
115             final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
116                     file);
117             return immediateFluentFuture(representation.cast(restored));
118         }
119
120         LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
121         return immediateFailedFluentFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
122     }
123
124     @Override
125     protected synchronized void offer(final T source) {
126         LOG.trace("Source {} offered to cache", source.getIdentifier());
127         final File file = sourceIdToFile(source);
128         if (file.exists()) {
129             LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
130             return;
131         }
132
133         storeSource(file, source);
134         register(source.getIdentifier());
135         LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
136     }
137
138     private File sourceIdToFile(final T source) {
139         return sourceIdToFile(source.getIdentifier(), storageDirectory);
140     }
141
142     static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
143         final Revision rev = identifier.revision();
144         final File file;
145         if (rev == null) {
146             // FIXME: this does not look right
147             file = findFileWithNewestRev(identifier, storageDirectory);
148         } else {
149             file = new File(storageDirectory, identifier.toYangFilename());
150         }
151         return file;
152     }
153
154     private static File findFileWithNewestRev(final SourceIdentifier identifier, final File storageDirectory) {
155         File[] files = storageDirectory.listFiles(new FilenameFilter() {
156             final Pattern pat = Pattern.compile(Pattern.quote(identifier.name().getLocalName())
157                     + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)");
158
159             @Override
160             public boolean accept(final File dir, final String name) {
161                 return pat.matcher(name).matches();
162             }
163         });
164
165         if (files.length == 0) {
166             return new File(storageDirectory, identifier.toYangFilename());
167         }
168         if (files.length == 1) {
169             return files[0];
170         }
171
172         File file = null;
173         TreeMap<Optional<Revision>, File> map = new TreeMap<>(Revision::compare);
174         for (File sorted : files) {
175             String fileName = sorted.getName();
176             Matcher match = Revision.STRING_FORMAT_PATTERN.matcher(fileName);
177             if (match.find()) {
178                 String revStr = match.group();
179                 Revision rev;
180                 try {
181                     rev = Revision.of(revStr);
182                 } catch (final DateTimeParseException e) {
183                     LOG.info("Unable to parse date from yang file name {}, falling back to not-present", fileName, e);
184                     rev = null;
185                 }
186
187                 map.put(Optional.ofNullable(rev), sorted);
188
189             } else {
190                 map.put(Optional.empty(), sorted);
191             }
192         }
193         file = map.lastEntry().getValue();
194
195         return file;
196     }
197
198     private void storeSource(final File file, final T schemaRepresentation) {
199         STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
200     }
201
202     private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
203
204         private final Class<T> supportedType;
205
206         protected StorageAdapter(final Class<T> supportedType) {
207             this.supportedType = supportedType;
208         }
209
210         void store(final File file, final SchemaSourceRepresentation schemaSourceRepresentation) {
211             checkArgument(supportedType.isAssignableFrom(schemaSourceRepresentation.getClass()),
212                     "Cannot store schema source %s, this adapter only supports %s", schemaSourceRepresentation,
213                     supportedType);
214
215             storeAsType(file, supportedType.cast(schemaSourceRepresentation));
216         }
217
218         // FIXME: use java.nio.filePath
219         protected abstract void storeAsType(File file, T cast);
220
221         T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
222             checkArgument(cachedSource.isFile());
223             checkArgument(cachedSource.exists());
224             checkArgument(cachedSource.canRead());
225             return restoreAsType(sourceIdentifier, cachedSource);
226         }
227
228         abstract T restoreAsType(SourceIdentifier sourceIdentifier, File cachedSource);
229     }
230
231     private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
232
233         protected YangTextSchemaStorageAdapter() {
234             super(YangTextSchemaSource.class);
235         }
236
237         @Override
238         @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE",
239             justification = "https://github.com/spotbugs/spotbugs/issues/600")
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         YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
251             return YangTextSchemaSource.forPath(cachedSource.toPath(), sourceIdentifier);
252         }
253     }
254
255     private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
256         private final List<SourceIdentifier> cachedSchemas = new ArrayList<>();
257
258         @Override
259         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
260             final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
261             String fileName = file.toFile().getName();
262             fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
263
264             final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
265             if (si.isPresent()) {
266                 LOG.trace("Restoring cached file {} as {}", file, si.get());
267                 cachedSchemas.add(si.get());
268             } else {
269                 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
270                         + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
271             }
272             return fileVisitResult;
273         }
274
275         private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
276             final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
277             if (matcher.matches()) {
278                 final String moduleName = matcher.group("moduleName");
279                 final String revision = matcher.group("revision");
280                 return Optional.of(new SourceIdentifier(moduleName, revision));
281             }
282             return Optional.empty();
283         }
284
285         @Override
286         public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
287             LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
288             return FileVisitResult.CONTINUE;
289         }
290
291         public List<SourceIdentifier> getCachedSchemas() {
292             return cachedSchemas;
293         }
294     }
295 }