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