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 com.google.common.base.MoreObjects.ToStringHelper;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Lists;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.Futures;
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.text.DateFormat;
28 import java.text.ParseException;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.List;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
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.SchemaSourceException;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
41 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
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;
49 * Cache implementation that stores schemas in form of files under provided folder.
51 public final class FilesystemSchemaSourceCache<T extends SchemaSourceRepresentation>
52 extends AbstractSchemaSourceCache<T> {
54 private static final Logger LOG = LoggerFactory.getLogger(FilesystemSchemaSourceCache.class);
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());
61 private static final Pattern CACHED_FILE_PATTERN =
62 Pattern.compile("(?<moduleName>[^@]+)" + "(@(?<revision>" + SourceIdentifier.REVISION_PATTERN + "))?");
64 private final Class<T> representation;
65 private final File storageDirectory;
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 = Preconditions.checkNotNull(storageDirectory);
73 checkSupportedRepresentation(representation);
75 if (!storageDirectory.exists()) {
76 Preconditions.checkArgument(storageDirectory.mkdirs(), "Unable to create cache directory at %s",
79 Preconditions.checkArgument(storageDirectory.exists());
80 Preconditions.checkArgument(storageDirectory.isDirectory());
81 Preconditions.checkArgument(storageDirectory.canWrite());
82 Preconditions.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 CheckedFuture<? extends T, SchemaSourceException> 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.immediateCheckedFuture(representation.cast(restored));
128 LOG.debug("Source {} not found in cache as {}", sourceIdentifier, file);
129 return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException("Source not found",
134 protected synchronized void offer(final T source) {
135 LOG.trace("Source {} offered to cache", source.getIdentifier());
136 final File file = sourceIdToFile(source);
138 LOG.debug("Source {} already in cache as {}", source.getIdentifier(), file);
142 storeSource(file, source);
143 register(source.getIdentifier());
144 LOG.trace("Source {} stored in cache as {}", source.getIdentifier(), file);
147 private File sourceIdToFile(final T source) {
148 return sourceIdToFile(source.getIdentifier(), storageDirectory);
151 static File sourceIdToFile(final SourceIdentifier identifier, final File storageDirectory) {
152 final String rev = identifier.getRevision();
154 if (Strings.isNullOrEmpty(rev)) {
155 file = findFileWithNewestRev(identifier, storageDirectory);
157 file = new File(storageDirectory, identifier.toYangFilename());
162 private static File findFileWithNewestRev(final SourceIdentifier identifier, final File storageDirectory) {
163 File[] files = storageDirectory.listFiles(new FilenameFilter() {
164 final Pattern pat = Pattern.compile(Pattern.quote(identifier.getName())
165 + "(\\.yang|@\\d\\d\\d\\d-\\d\\d-\\d\\d.yang)");
168 public boolean accept(final File dir, final String name) {
169 return pat.matcher(name).matches();
173 if (files.length == 0) {
174 return new File(storageDirectory, identifier.toYangFilename());
176 if (files.length == 1) {
181 TreeMap<Date, File> map = new TreeMap<>();
182 for (File sorted : files) {
183 String fileName = sorted.getName();
184 Matcher match = SourceIdentifier.REVISION_PATTERN.matcher(fileName);
186 String revStr = match.group();
188 * FIXME: Consider using string for comparison.
189 * String is comparable, pattern check tested format
190 * so comparing as ASCII string should be sufficient
192 DateFormat df = SimpleDateFormatUtil.getRevisionFormat();
194 Date date = df.parse(revStr);
195 map.put(date, sorted);
196 } catch (final ParseException e) {
197 LOG.info("Unable to parse date from yang file name {}", fileName);
198 map.put(new Date(0L), sorted);
202 map.put(new Date(0L), sorted);
205 file = map.lastEntry().getValue();
210 private void storeSource(final File file, final T schemaRepresentation) {
211 STORAGE_ADAPTERS.get(representation).store(file, schemaRepresentation);
214 private abstract static class StorageAdapter<T extends SchemaSourceRepresentation> {
216 private final Class<T> supportedType;
218 protected StorageAdapter(final Class<T> supportedType) {
219 this.supportedType = supportedType;
222 void store(final File file, final SchemaSourceRepresentation schemaSourceRepresentation) {
223 Preconditions.checkArgument(supportedType.isAssignableFrom(schemaSourceRepresentation.getClass()),
224 "Cannot store schema source %s, this adapter only supports %s", schemaSourceRepresentation,
227 storeAsType(file, supportedType.cast(schemaSourceRepresentation));
230 protected abstract void storeAsType(final File file, final T cast);
232 public T restore(final SourceIdentifier sourceIdentifier, final File cachedSource) {
233 Preconditions.checkArgument(cachedSource.isFile());
234 Preconditions.checkArgument(cachedSource.exists());
235 Preconditions.checkArgument(cachedSource.canRead());
236 return restoreAsType(sourceIdentifier, cachedSource);
239 protected abstract T restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource);
242 private static final class YangTextSchemaStorageAdapter extends StorageAdapter<YangTextSchemaSource> {
244 protected YangTextSchemaStorageAdapter() {
245 super(YangTextSchemaSource.class);
249 protected void storeAsType(final File file, final YangTextSchemaSource cast) {
250 try (final InputStream castStream = cast.openStream()) {
251 Files.copy(castStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
252 } catch (final IOException e) {
253 throw new IllegalStateException("Cannot store schema source " + cast.getIdentifier() + " to " + file,
259 public YangTextSchemaSource restoreAsType(final SourceIdentifier sourceIdentifier, final File cachedSource) {
260 return new YangTextSchemaSource(sourceIdentifier) {
263 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
264 return toStringHelper;
268 public InputStream openStream() throws IOException {
269 return Files.newInputStream(cachedSource.toPath());
275 private static final class CachedModulesFileVisitor extends SimpleFileVisitor<Path> {
276 private final List<SourceIdentifier> cachedSchemas = Lists.newArrayList();
279 public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
280 final FileVisitResult fileVisitResult = super.visitFile(file, attrs);
281 String fileName = file.toFile().getName();
282 fileName = com.google.common.io.Files.getNameWithoutExtension(fileName);
284 final Optional<SourceIdentifier> si = getSourceIdentifier(fileName);
285 if (si.isPresent()) {
286 LOG.trace("Restoring cached file {} as {}", file, si.get());
287 cachedSchemas.add(si.get());
289 LOG.debug("Skipping cached file {}, cannot restore source identifier from filename: {},"
290 + " does not match {}", file, fileName, CACHED_FILE_PATTERN);
292 return fileVisitResult;
295 private static Optional<SourceIdentifier> getSourceIdentifier(final String fileName) {
296 final Matcher matcher = CACHED_FILE_PATTERN.matcher(fileName);
297 if (matcher.matches()) {
298 final String moduleName = matcher.group("moduleName");
299 final String revision = matcher.group("revision");
300 return Optional.of(RevisionSourceIdentifier.create(moduleName, Optional.fromNullable(revision)));
302 return Optional.absent();
306 public FileVisitResult visitFileFailed(final Path file, final IOException exc) throws IOException {
307 LOG.warn("Unable to restore cached file {}. Ignoring", file, exc);
308 return FileVisitResult.CONTINUE;
311 public List<SourceIdentifier> getCachedSchemas() {
312 return cachedSchemas;