2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.model.repo.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
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;
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;
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;
50 * Cache implementation that stores schemas in form of files under provided folder.
52 public final class FilesystemSchemaSourceCache<T extends SchemaSourceRepresentation>
53 extends AbstractSchemaSourceCache<T> {
55 private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaSourceCache.class);
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());
62 private static final Pattern CACHED_FILE_PATTERN =
63 Pattern.compile("(?<moduleName>[^@]+)" + "(@(?<revision>" + SourceIdentifier.REVISION_PATTERN + "))?");
65 private final Class<T> representation;
66 private final File storageDirectory;
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);
74 checkSupportedRepresentation(representation);
76 if (!storageDirectory.exists()) {
77 checkArgument(storageDirectory.mkdirs(), "Unable to create cache directory at %s", storageDirectory);
79 checkArgument(storageDirectory.exists());
80 checkArgument(storageDirectory.isDirectory());
81 checkArgument(storageDirectory.canWrite());
82 checkArgument(storageDirectory.canRead());
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)) {
94 throw new IllegalArgumentException(String.format(
95 "This cache does not support representation: %s, supported representations are: %s",
96 representation, STORAGE_ADAPTERS.keySet()));
100 * Restore cache state.
102 private void init() {
104 final CachedModulesFileVisitor fileVisitor = new CachedModulesFileVisitor();
106 Files.walkFileTree(storageDirectory.toPath(), fileVisitor);
107 } catch (final IOException e) {
108 LOG.warn("Unable to restore cache from {}. Starting with empty cache", storageDirectory);
112 for (final SourceIdentifier cachedSchema : fileVisitor.getCachedSchemas()) {
113 register(cachedSchema);
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,
125 return Futures.immediateFuture(representation.cast(restored));
128 LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
129 return Futures.immediateFailedFuture(new MissingSchemaSourceException("Source not found", sourceIdentifier));
133 protected synchronized void offer(final T source) {
134 LOG.trace("Source {} offered to cache", source.getIdentifier());
135 final File file = sourceIdToFile(source);
137 LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
141 storeSource(file, source);
142 register(source.getIdentifier());
143 LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
146 private File sourceIdToFile(final T source) {
147 return sourceIdToFile(source.getIdentifier(), storageDirectory);
150 static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
151 final String rev = identifier.getRevision();
153 if (Strings.isNullOrEmpty(rev)) {
154 file = findFileWithNewestRev(identifier, storageDirectory);
156 file = new File(storageDirectory, identifier.toYangFilename());
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)");
167 public boolean accept(final File dir, final String name) {
168 return pat.matcher(name).matches();
172 if (files.length == 0) {
173 return new File(storageDirectory, identifier.toYangFilename());
175 if (files.length == 1) {
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);
185 String revStr = match.group();
187 * FIXME: Consider using string for comparison.
188 * String is comparable, pattern check tested format
189 * so comparing as ASCII string should be sufficient
191 DateFormat df = SimpleDateFormatUtil.getRevisionFormat();
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);
201 map.put(new Date(0L), sorted);
204 file = map.lastEntry().getValue();
209 private void storeSource(final File file, final T schemaRepresentation) {
210 STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
213 private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
215 private final Class<T> supportedType;
217 protected StorageAdapter(final Class<T> supportedType) {
218 this.supportedType = supportedType;
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,
226 storeAsType(file, supportedType.cast(schemaSourceRepresentation));
229 protected abstract void storeAsType(File file, T cast);
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);
238 protected abstract T restoreAsType(SourceIdentifier sourceIdentifier, File cachedSource);
241 private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
243 protected YangTextSchemaStorageAdapter() {
244 super(YangTextSchemaSource.class);
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,
258 public YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
259 return new YangTextSchemaSource(sourceIdentifier) {
262 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
263 return toStringHelper;
267 public InputStream openStream() throws IOException {
268 return Files.newInputStream(cachedSource.toPath());
274 private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
275 private final List<SourceIdentifier> cachedSchemas = Lists.newArrayList();
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);
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());
288 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
289 + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
291 return fileVisitResult;
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)));
301 return Optional.empty();
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;
310 public List<SourceIdentifier> getCachedSchemas() {
311 return cachedSchemas;