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;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ArrayListMultimap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Multimap;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import java.io.IOException;
20 import java.io.InputStream;
22 import java.util.Collection;
24 import java.util.concurrent.ConcurrentLinkedDeque;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicReference;
27 import javax.annotation.Nonnull;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
30 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
38 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
39 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
42 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
44 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
45 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
46 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
51 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
52 private static final long SOURCE_LIFETIME_SECONDS = 60;
54 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
55 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
56 private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
57 new AtomicReference<>(Optional.<SchemaContext>absent());
58 private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
59 private final SchemaListenerRegistration transReg;
60 private final SchemaSourceRegistry registry;
61 private final SchemaRepository repository;
62 private volatile Object version = new Object();
63 private volatile Object contextVersion = version;
65 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
66 this.repository = Preconditions.checkNotNull(repository);
67 this.registry = Preconditions.checkNotNull(registry);
69 final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
70 transReg = registry.registerSchemaSourceListener(t);
72 cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
76 public static YangTextSchemaContextResolver create(final String name) {
77 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
78 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
82 * Register a {@link YangTextSchemaSource}.
84 * @param source YANG text source
85 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
86 * @throws IOException when the URL is not readable
87 * @throws SchemaSourceException When parsing encounters general error
88 * @return a YangTextSchemaSourceRegistration
90 public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
91 throws SchemaSourceException, IOException, YangSyntaxErrorException {
92 checkArgument(source != null);
94 final ASTSchemaSource ast = TextToASTTransformer.TRANSFORMATION.apply(source).checkedGet();
95 LOG.trace("Resolved source {} to source {}", source, ast);
97 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
98 // does not, check how much it differs and emit a warning.
99 final SourceIdentifier providedId = source.getIdentifier();
100 final SourceIdentifier parsedId = ast.getIdentifier();
101 final YangTextSchemaSource text;
102 if (!parsedId.equals(providedId)) {
103 if (!parsedId.getName().equals(providedId.getName())) {
104 LOG.info("Provided module name {} does not match actual text {}, corrected", providedId.toYangFilename(),
105 parsedId.toYangFilename());
107 final String sourceRev = providedId.getRevision();
108 final String astRev = parsedId.getRevision();
109 if (sourceRev != null) {
110 if (!sourceRev.equals(astRev)) {
111 LOG.info("Provided module revision {} does not match actual text {}, corrected",
112 providedId.toYangFilename(), parsedId.toYangFilename());
115 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
119 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
124 synchronized (this) {
125 texts.put(parsedId, text);
126 LOG.debug("Populated {} with text", parsedId);
128 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
129 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
130 requiredSources.add(parsedId);
131 cache.schemaSourceEncountered(ast);
132 LOG.debug("Added source {} to schema context requirements", parsedId);
133 version = new Object();
135 return new AbstractYangTextSchemaSourceRegistration(text) {
137 protected void removeRegistration() {
138 synchronized (YangTextSchemaContextResolver.this) {
139 requiredSources.remove(parsedId);
140 LOG.trace("Removed source {} from schema context requirements", parsedId);
141 version = new Object();
143 texts.remove(parsedId, text);
151 * Register a URL containing a YANG text.
153 * @param url YANG text source URL
154 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
155 * @throws IOException when the URL is not readable
156 * @throws SchemaSourceException When parsing encounters general error
157 * @return a YangTextSchemaSourceRegistration for this URL
159 public YangTextSchemaSourceRegistration registerSource(@Nonnull final URL url) throws SchemaSourceException, IOException, YangSyntaxErrorException {
160 checkArgument(url != null, "Supplied URL must not be null");
162 final SourceIdentifier guessedId = new SourceIdentifier(url.getFile(), Optional.<String>absent());
163 return registerSource(new YangTextSchemaSource(guessedId) {
165 public InputStream openStream() throws IOException {
166 return url.openStream();
170 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
171 return toStringHelper.add("url", url);
177 * Try to parse all currently available yang files and build new schema context.
178 * @return new schema context iif there is at least 1 yang file registered and
179 * new schema context was successfully built.
181 public Optional<SchemaContext> getSchemaContext() {
182 final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
183 Optional<SchemaContext> sc;
186 // Spin get stable context version
190 sc = currentSchemaContext.get();
194 } while (cv != contextVersion);
196 // Version has been updated
197 Collection<SourceIdentifier> sources;
200 sources = ImmutableSet.copyOf(requiredSources);
201 } while (v != version);
204 final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory.createSchemaContext(sources);
206 sc = Optional.of(f.checkedGet());
208 } catch (SchemaResolutionException e) {
209 LOG.info("Failed to fully assemble schema context for {}", sources, e);
210 sources = e.getResolvedSources();
214 LOG.debug("Resolved schema context for {}", sources);
216 synchronized (this) {
217 if (contextVersion == cv) {
218 currentSchemaContext.set(sc);
222 } while (version == v);
228 public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
229 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
231 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
233 return Futures.<YangTextSchemaSource, SchemaSourceException>immediateFailedCheckedFuture(
234 new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
237 return Futures.immediateCheckedFuture(ret.iterator().next());
241 * Return the set of sources currently available in this resolved.
243 * @return An immutable point-in-time view of available sources.
245 public synchronized Set<SourceIdentifier> getAvailableSources() {
246 return ImmutableSet.copyOf(texts.keySet());
250 public void close() {