2 * Copyright (c) 2015 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.parser.repo;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Verify;
16 import com.google.common.collect.ArrayListMultimap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Multimap;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import java.io.IOException;
22 import java.io.InputStream;
24 import java.util.Collection;
25 import java.util.Optional;
27 import java.util.concurrent.ConcurrentLinkedDeque;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicReference;
31 import javax.annotation.Nonnull;
32 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
33 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
34 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
37 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
38 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
41 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
43 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
44 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
45 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
46 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
47 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
48 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
50 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
51 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
52 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
57 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
58 private static final long SOURCE_LIFETIME_SECONDS = 60;
60 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
61 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
62 private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
63 new AtomicReference<>(Optional.empty());
64 private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
65 private final SchemaListenerRegistration transReg;
66 private final SchemaSourceRegistry registry;
67 private final SchemaRepository repository;
68 private volatile Object version = new Object();
69 private volatile Object contextVersion = version;
71 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
72 this.repository = Preconditions.checkNotNull(repository);
73 this.registry = Preconditions.checkNotNull(registry);
75 final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
76 transReg = registry.registerSchemaSourceListener(t);
78 cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
82 public static YangTextSchemaContextResolver create(final String name) {
83 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
84 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
88 * Register a {@link YangTextSchemaSource}.
90 * @param source YANG text source
91 * @return a YangTextSchemaSourceRegistration
92 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
93 * @throws IOException when the URL is not readable
94 * @throws SchemaSourceException When parsing encounters general error
96 public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
97 throws SchemaSourceException, IOException, YangSyntaxErrorException {
98 checkArgument(source != null);
100 final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
101 LOG.trace("Resolved source {} to source {}", source, ast);
103 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
104 // does not, check how much it differs and emit a warning.
105 final SourceIdentifier providedId = source.getIdentifier();
106 final SourceIdentifier parsedId = ast.getIdentifier();
107 final YangTextSchemaSource text;
108 if (!parsedId.equals(providedId)) {
109 if (!parsedId.getName().equals(providedId.getName())) {
110 LOG.info("Provided module name {} does not match actual text {}, corrected",
111 providedId.toYangFilename(), parsedId.toYangFilename());
113 final String sourceRev = providedId.getRevision();
114 final String astRev = parsedId.getRevision();
115 if (sourceRev != null && !SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(sourceRev)) {
116 if (!sourceRev.equals(astRev)) {
117 LOG.info("Provided module revision {} does not match actual text {}, corrected",
118 providedId.toYangFilename(), parsedId.toYangFilename());
121 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
125 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
130 synchronized (this) {
131 texts.put(parsedId, text);
132 LOG.debug("Populated {} with text", parsedId);
134 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
135 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
136 requiredSources.add(parsedId);
137 cache.schemaSourceEncountered(ast);
138 LOG.debug("Added source {} to schema context requirements", parsedId);
139 version = new Object();
141 return new AbstractYangTextSchemaSourceRegistration(text) {
143 protected void removeRegistration() {
144 synchronized (YangTextSchemaContextResolver.this) {
145 requiredSources.remove(parsedId);
146 LOG.trace("Removed source {} from schema context requirements", parsedId);
147 version = new Object();
149 texts.remove(parsedId, text);
157 * Register a URL containing a YANG text.
159 * @param url YANG text source URL
160 * @return a YangTextSchemaSourceRegistration for this URL
161 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
162 * @throws IOException when the URL is not readable
163 * @throws SchemaSourceException When parsing encounters general error
165 public YangTextSchemaSourceRegistration registerSource(@Nonnull final URL url) throws SchemaSourceException,
166 IOException, YangSyntaxErrorException {
167 checkArgument(url != null, "Supplied URL must not be null");
169 final String path = url.getPath();
170 final String fileName = path.substring(path.lastIndexOf('/') + 1);
171 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
172 return registerSource(new YangTextSchemaSource(guessedId) {
174 public InputStream openStream() throws IOException {
175 return url.openStream();
179 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
180 return toStringHelper.add("url", url);
185 private static SourceIdentifier guessSourceIdentifier(final String fileName) {
187 return YangTextSchemaSource.identifierFromFilename(fileName);
188 } catch (IllegalArgumentException e) {
189 LOG.warn("Invalid file name format in '{}'", fileName, e);
190 return RevisionSourceIdentifier.create(fileName);
195 * Try to parse all currently available yang files and build new schema context.
197 * @return new schema context iif there is at least 1 yang file registered and
198 * new schema context was successfully built.
200 public Optional<SchemaContext> getSchemaContext() {
201 return getSchemaContext(StatementParserMode.DEFAULT_MODE);
205 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
207 * @param statementParserMode mode of statement parser
208 * @return new schema context iif there is at least 1 yang file registered and
209 * new schema context was successfully built.
211 public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
212 final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
213 Optional<SchemaContext> sc;
216 // Spin get stable context version
220 sc = currentSchemaContext.get();
224 } while (cv != contextVersion);
226 // Version has been updated
227 Collection<SourceIdentifier> sources;
230 sources = ImmutableSet.copyOf(requiredSources);
231 } while (ver != version);
234 final ListenableFuture<SchemaContext> f = factory.createSchemaContext(sources, statementParserMode);
236 sc = Optional.of(f.get());
238 } catch (InterruptedException e) {
239 throw new RuntimeException("Interrupted while assembling schema context", e);
240 } catch (ExecutionException e) {
241 LOG.info("Failed to fully assemble schema context for {}", sources, e);
242 final Throwable cause = e.getCause();
243 Verify.verify(cause instanceof SchemaResolutionException);
244 sources = ((SchemaResolutionException) cause).getResolvedSources();
248 LOG.debug("Resolved schema context for {}", sources);
250 synchronized (this) {
251 if (contextVersion == cv) {
252 currentSchemaContext.set(sc);
253 contextVersion = ver;
256 } while (version == ver);
262 public synchronized ListenableFuture<YangTextSchemaSource> getSource(
263 final SourceIdentifier sourceIdentifier) {
264 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
266 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
268 return Futures.immediateFailedFuture(new MissingSchemaSourceException(
269 "URL for " + sourceIdentifier + " not registered", sourceIdentifier));
272 return Futures.immediateFuture(ret.iterator().next());
276 * Return the set of sources currently available in this resolved.
278 * @return An immutable point-in-time view of available sources.
280 public synchronized Set<SourceIdentifier> getAvailableSources() {
281 return ImmutableSet.copyOf(texts.keySet());
285 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
286 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
290 public SchemaContext trySchemaContext() throws SchemaResolutionException {
291 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
295 public SchemaContext trySchemaContext(final StatementParserMode statementParserMode)
296 throws SchemaResolutionException {
297 final ListenableFuture<SchemaContext> future = repository
298 .createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT)
299 .createSchemaContext(ImmutableSet.copyOf(requiredSources), statementParserMode);
303 } catch (InterruptedException e) {
304 throw new RuntimeException("Interrupted while waiting for SchemaContext assembly", e);
305 } catch (ExecutionException e) {
306 final Throwable cause = e.getCause();
307 if (cause instanceof SchemaResolutionException) {
308 throw (SchemaResolutionException) cause;
311 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
316 public void close() {