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.base.MoreObjects.ToStringHelper;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.ArrayListMultimap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Multimap;
18 import com.google.common.util.concurrent.CheckedFuture;
19 import com.google.common.util.concurrent.Futures;
20 import java.io.IOException;
21 import java.io.InputStream;
23 import java.util.Collection;
25 import java.util.concurrent.ConcurrentLinkedDeque;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.atomic.AtomicReference;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
31 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
32 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
37 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
38 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
40 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
41 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
42 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
44 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
45 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
46 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
47 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
48 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
49 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
54 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
55 private static final long SOURCE_LIFETIME_SECONDS = 60;
57 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
58 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
59 private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
60 new AtomicReference<>(Optional.absent());
61 private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
62 private final SchemaListenerRegistration transReg;
63 private final SchemaSourceRegistry registry;
64 private final SchemaRepository repository;
65 private volatile Object version = new Object();
66 private volatile Object contextVersion = version;
68 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
69 this.repository = Preconditions.checkNotNull(repository);
70 this.registry = Preconditions.checkNotNull(registry);
72 final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
73 transReg = registry.registerSchemaSourceListener(t);
75 cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
79 public static YangTextSchemaContextResolver create(final String name) {
80 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
81 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
85 * Register a {@link YangTextSchemaSource}.
87 * @param source YANG text source
88 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
89 * @throws IOException when the URL is not readable
90 * @throws SchemaSourceException When parsing encounters general error
91 * @return a YangTextSchemaSourceRegistration
93 public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
94 throws SchemaSourceException, IOException, YangSyntaxErrorException {
95 checkArgument(source != null);
97 final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
98 LOG.trace("Resolved source {} to source {}", source, ast);
100 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
101 // does not, check how much it differs and emit a warning.
102 final SourceIdentifier providedId = source.getIdentifier();
103 final SourceIdentifier parsedId = ast.getIdentifier();
104 final YangTextSchemaSource text;
105 if (!parsedId.equals(providedId)) {
106 if (!parsedId.getName().equals(providedId.getName())) {
107 LOG.info("Provided module name {} does not match actual text {}, corrected",
108 providedId.toYangFilename(), parsedId.toYangFilename());
110 final String sourceRev = providedId.getRevision();
111 final String astRev = parsedId.getRevision();
112 if (sourceRev != null && !SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION.equals(sourceRev)) {
113 if (!sourceRev.equals(astRev)) {
114 LOG.info("Provided module revision {} does not match actual text {}, corrected",
115 providedId.toYangFilename(), parsedId.toYangFilename());
118 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
122 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
127 synchronized (this) {
128 texts.put(parsedId, text);
129 LOG.debug("Populated {} with text", parsedId);
131 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
132 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
133 requiredSources.add(parsedId);
134 cache.schemaSourceEncountered(ast);
135 LOG.debug("Added source {} to schema context requirements", parsedId);
136 version = new Object();
138 return new AbstractYangTextSchemaSourceRegistration(text) {
140 protected void removeRegistration() {
141 synchronized (YangTextSchemaContextResolver.this) {
142 requiredSources.remove(parsedId);
143 LOG.trace("Removed source {} from schema context requirements", parsedId);
144 version = new Object();
146 texts.remove(parsedId, text);
154 * Register a URL containing a YANG text.
156 * @param url YANG text source URL
157 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
158 * @throws IOException when the URL is not readable
159 * @throws SchemaSourceException When parsing encounters general error
160 * @return a YangTextSchemaSourceRegistration for this URL
162 public YangTextSchemaSourceRegistration registerSource(@Nonnull final URL url) throws SchemaSourceException,
163 IOException, YangSyntaxErrorException {
164 checkArgument(url != null, "Supplied URL must not be null");
166 final SourceIdentifier guessedId = RevisionSourceIdentifier.create(url.getFile(), Optional.absent());
167 return registerSource(new YangTextSchemaSource(guessedId) {
169 public InputStream openStream() throws IOException {
170 return url.openStream();
174 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
175 return toStringHelper.add("url", url);
181 * Try to parse all currently available yang files and build new schema context.
182 * @return new schema context iif there is at least 1 yang file registered and
183 * new schema context was successfully built.
185 public Optional<SchemaContext> getSchemaContext() {
186 return getSchemaContext(StatementParserMode.DEFAULT_MODE);
190 * Try to parse all currently available yang files and build new schema context
191 * in dependence on specified parsing mode.
193 * @param statementParserMode mode of statement parser
194 * @return new schema context iif there is at least 1 yang file registered and
195 * new schema context was successfully built.
197 public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
198 final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
199 Optional<SchemaContext> sc;
202 // Spin get stable context version
206 sc = currentSchemaContext.get();
210 } while (cv != contextVersion);
212 // Version has been updated
213 Collection<SourceIdentifier> sources;
216 sources = ImmutableSet.copyOf(requiredSources);
217 } while (v != version);
220 final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory.createSchemaContext(sources,
221 statementParserMode);
223 sc = Optional.of(f.checkedGet());
225 } catch (SchemaResolutionException e) {
226 LOG.info("Failed to fully assemble schema context for {}", sources, e);
227 sources = e.getResolvedSources();
231 LOG.debug("Resolved schema context for {}", sources);
233 synchronized (this) {
234 if (contextVersion == cv) {
235 currentSchemaContext.set(sc);
239 } while (version == v);
245 public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
246 final SourceIdentifier sourceIdentifier) {
247 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
249 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
251 return Futures.immediateFailedCheckedFuture(new MissingSchemaSourceException(
252 "URL for " + sourceIdentifier + " not registered", sourceIdentifier));
255 return Futures.immediateCheckedFuture(ret.iterator().next());
259 * Return the set of sources currently available in this resolved.
261 * @return An immutable point-in-time view of available sources.
263 public synchronized Set<SourceIdentifier> getAvailableSources() {
264 return ImmutableSet.copyOf(texts.keySet());
268 public void close() {