315152b05c33475bfb5f66f775e3ee8d4fb59235
[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         if (!storageDirectory.exists()) {
75             checkArgument(storageDirectory.mkdirs(), "Unable to create cache directory at %s", storageDirectory);
76         }
77         checkArgument(storageDirectory.exists());
78         checkArgument(storageDirectory.isDirectory());
79         checkArgument(storageDirectory.canWrite());
80         checkArgument(storageDirectory.canRead());
81
82         init();
83     }
84
85     private static void checkSupportedRepresentation(final Class<? extends SchemaSourceRepresentation> representation) {
86         for (final Class<? extends SchemaSourceRepresentation> supportedRepresentation : STORAGE_ADAPTERS.keySet()) {
87             if (supportedRepresentation.isAssignableFrom(representation)) {
88                 return;
89             }
90         }
91
92         throw new IllegalArgumentException(String.format(
93                    "This cache does not support representation: %s, supported representations are: %s",
94                    representation, STORAGE_ADAPTERS.keySet()));
95     }
96
97     /**
98      * Restore cache state.
99      */
100     private void init() {
101
102         final CachedModulesFileVisitor fileVisitor = new CachedModulesFileVisitor();
103         try {
104             Files.walkFileTree(storageDirectory.toPath(), fileVisitor);
105         } catch (final IOException e) {
106             LOG.warn("Unable to restore cache from {}. Starting with empty cache", storageDirectory);
107             return;
108         }
109
110         for (final SourceIdentifier cachedSchema : fileVisitor.getCachedSchemas()) {
111             register(cachedSchema);
112         }
113     }
114
115     @Override
116     public synchronized FluentFuture<? extends T> getSource(
117             final SourceIdentifier sourceIdentifier) {
118         final File file = sourceIdToFile(sourceIdentifier, storageDirectory);
119         if (file.exists() && file.canRead()) {
120             LOG.trace("Source {} found in cache as {}", sourceIdentifier, file);
121             final SchemaSourceRepresentation restored = STORAGE_ADAPTERS.get(representation).restore(sourceIdentifier,
122                     file);
123             return immediateFluentFuture(representation.cast(restored));
124         }
125
126         LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
127         return immediateFailedFluentFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
128     }
129
130     @Override
131     protected synchronized void offer(final T source) {
132         LOG.trace("Source {} offered to cache", source.getIdentifier());
133         final File file = sourceIdToFile(source);
134         if (file.exists()) {
135             LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
136             return;
137         }
138
139         storeSource(file, source);
140         register(source.getIdentifier());
141         LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
142     }
143
144     private File sourceIdToFile(final T source) {
145         return sourceIdToFile(source.getIdentifier(), storageDirectory);
146     }
147
148     static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
149         final Optional<Revision> rev = identifier.getRevision();
150         final File file;
151         if (!rev.isPresent()) {
152             // FIXME: this does not look right
153             file = findFileWithNewestRev(identifier, storageDirectory);
154         } else {
155             file = new File(storageDirectory, identifier.toYangFilename());
156         }
157         return file;
158     }
159
160     private static File findFileWithNewestRev(final SourceIdentifier identifier, final File storageDirectory) {
161         File[] files = storageDirectory.listFiles(new FilenameFilter() {
162             final Pattern pat = Pattern.compile(Pattern.quote(identifier.getName())
163                     + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)");
164
165             @Override
166             public boolean accept(final File dir, final String name) {
167                 return pat.matcher(name).matches();
168             }
169         });
170
171         if (files.length == 0) {
172             return new File(storageDirectory, identifier.toYangFilename());
173         }
174         if (files.length == 1) {
175             return files[0];
176         }
177
178         File file = null;
179         TreeMap<Optional<Revision>, File> map = new TreeMap<>(Revision::compare);
180         for (File sorted : files) {
181             String fileName = sorted.getName();
182             Matcher match = Revision.STRING_FORMAT_PATTERN.matcher(fileName);
183             if (match.find()) {
184                 String revStr = match.group();
185                 Revision rev;
186                 try {
187                     rev = Revision.of(revStr);
188                 } catch (final DateTimeParseException e) {
189                     LOG.info("Unable to parse date from yang file name {}, falling back to not-present", fileName, e);
190                     rev = null;
191                 }
192
193                 map.put(Optional.ofNullable(rev), sorted);
194
195             } else {
196                 map.put(Optional.empty(), sorted);
197             }
198         }
199         file = map.lastEntry().getValue();
200
201         return file;
202     }
203
204     private void storeSource(final File file, final T schemaRepresentation) {
205         STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
206     }
207
208     private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
209
210         private final Class<T> supportedType;
211
212         protected StorageAdapter(final Class<T> supportedType) {
213             this.supportedType = supportedType;
214         }
215
216         void store(final File file, final SchemaSourceRepresentation schemaSourceRepresentation) {
217             checkArgument(supportedType.isAssignableFrom(schemaSourceRepresentation.getClass()),
218                     "Cannot store schema source %s, this adapter only supports %s", schemaSourceRepresentation,
219                     supportedType);
220
221             storeAsType(file, supportedType.cast(schemaSourceRepresentation));
222         }
223
224         protected abstract void storeAsType(File file, T cast);
225
226         public T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
227             checkArgument(cachedSource.isFile());
228             checkArgument(cachedSource.exists());
229             checkArgument(cachedSource.canRead());
230             return restoreAsType(sourceIdentifier, cachedSource);
231         }
232
233         protected abstract T restoreAsType(SourceIdentifier sourceIdentifier, File cachedSource);
234     }
235
236     private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
237
238         protected YangTextSchemaStorageAdapter() {
239             super(YangTextSchemaSource.class);
240         }
241
242         @Override
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         public YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
254             return new YangTextSchemaSource(sourceIdentifier) {
255
256                 @Override
257                 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
258                     return toStringHelper;
259                 }
260
261                 @Override
262                 public InputStream openStream() throws IOException {
263                     return Files.newInputStream(cachedSource.toPath());
264                 }
265             };
266         }
267     }
268
269     private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
270         private final List<SourceIdentifier> cachedSchemas = Lists.newArrayList();
271
272         @Override
273         public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
274             final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
275             String fileName = file.toFile().getName();
276             fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
277
278             final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
279             if (si.isPresent()) {
280                 LOG.trace("Restoring cached file {} as {}", file, si.get());
281                 cachedSchemas.add(si.get());
282             } else {
283                 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
284                         + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
285             }
286             return fileVisitResult;
287         }
288
289         private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
290             final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
291             if (matcher.matches()) {
292                 final String moduleName = matcher.group("moduleName");
293                 final String revision = matcher.group("revision");
294                 return Optional.of(RevisionSourceIdentifier.create(moduleName, Revision.ofNullable(revision)));
295             }
296             return Optional.empty();
297         }
298
299         @Override
300         public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
301             LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
302             return FileVisitResult.CONTINUE;
303         }
304
305         public List<SourceIdentifier> getCachedSchemas() {
306             return cachedSchemas;
307         }
308     }
309 }