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 static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
13 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.MoreObjects.ToStringHelper;
17 import com.google.common.base.Verify;
18 import com.google.common.collect.ArrayListMultimap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Multimap;
21 import com.google.common.util.concurrent.FluentFuture;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import java.io.IOException;
24 import java.io.InputStream;
26 import java.util.Collection;
27 import java.util.Optional;
29 import java.util.concurrent.ConcurrentLinkedDeque;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import java.util.concurrent.atomic.AtomicReference;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.yang.common.Revision;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
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.SchemaContextFactory;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
45 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
46 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
47 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
48 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
53 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
54 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
55 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
60 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
61 private static final long SOURCE_LIFETIME_SECONDS = 60;
63 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
64 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
65 private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
66 new AtomicReference<>(Optional.empty());
67 private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
68 private final SchemaListenerRegistration transReg;
69 private final SchemaSourceRegistry registry;
70 private final SchemaRepository repository;
71 private volatile Object version = new Object();
72 private volatile Object contextVersion = version;
74 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
75 this.repository = requireNonNull(repository);
76 this.registry = requireNonNull(registry);
78 final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
79 transReg = registry.registerSchemaSourceListener(t);
81 cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
85 public static YangTextSchemaContextResolver create(final String name) {
86 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
87 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
91 * Register a {@link YangTextSchemaSource}.
93 * @param source YANG text source
94 * @return a YangTextSchemaSourceRegistration
95 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
96 * @throws IOException when the URL is not readable
97 * @throws SchemaSourceException When parsing encounters general error
99 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
100 throws SchemaSourceException, IOException, YangSyntaxErrorException {
101 checkArgument(source != null);
103 final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
104 LOG.trace("Resolved source {} to source {}", source, ast);
106 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
107 // does not, check how much it differs and emit a warning.
108 final SourceIdentifier providedId = source.getIdentifier();
109 final SourceIdentifier parsedId = ast.getIdentifier();
110 final YangTextSchemaSource text;
111 if (!parsedId.equals(providedId)) {
112 if (!parsedId.getName().equals(providedId.getName())) {
113 LOG.info("Provided module name {} does not match actual text {}, corrected",
114 providedId.toYangFilename(), parsedId.toYangFilename());
116 final Optional<Revision> sourceRev = providedId.getRevision();
117 final Optional<Revision> astRev = parsedId.getRevision();
118 if (sourceRev.isPresent()) {
119 if (!sourceRev.equals(astRev)) {
120 LOG.info("Provided module revision {} does not match actual text {}, corrected",
121 providedId.toYangFilename(), parsedId.toYangFilename());
124 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
128 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
133 synchronized (this) {
134 texts.put(parsedId, text);
135 LOG.debug("Populated {} with text", parsedId);
137 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
138 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
139 requiredSources.add(parsedId);
140 cache.schemaSourceEncountered(ast);
141 LOG.debug("Added source {} to schema context requirements", parsedId);
142 version = new Object();
144 return new AbstractYangTextSchemaSourceRegistration(text) {
146 protected void removeRegistration() {
147 synchronized (YangTextSchemaContextResolver.this) {
148 requiredSources.remove(parsedId);
149 LOG.trace("Removed source {} from schema context requirements", parsedId);
150 version = new Object();
152 texts.remove(parsedId, text);
160 * Register a URL containing a YANG text.
162 * @param url YANG text source URL
163 * @return a YangTextSchemaSourceRegistration for this URL
164 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
165 * @throws IOException when the URL is not readable
166 * @throws SchemaSourceException When parsing encounters general error
168 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
169 throws SchemaSourceException, IOException, YangSyntaxErrorException {
170 checkArgument(url != null, "Supplied URL must not be null");
172 final String path = url.getPath();
173 final String fileName = path.substring(path.lastIndexOf('/') + 1);
174 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
175 return registerSource(new YangTextSchemaSource(guessedId) {
177 public InputStream openStream() throws IOException {
178 return url.openStream();
182 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
183 return toStringHelper.add("url", url);
188 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
190 return YangTextSchemaSource.identifierFromFilename(fileName);
191 } catch (final IllegalArgumentException e) {
192 LOG.warn("Invalid file name format in '{}'", fileName, e);
193 return RevisionSourceIdentifier.create(fileName);
198 * Try to parse all currently available yang files and build new schema context.
200 * @return new schema context iif there is at least 1 yang file registered and
201 * new schema context was successfully built.
203 public Optional<SchemaContext> getSchemaContext() {
204 return getSchemaContext(StatementParserMode.DEFAULT_MODE);
208 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
210 * @param statementParserMode mode of statement parser
211 * @return new schema context iif there is at least 1 yang file registered and
212 * new schema context was successfully built.
214 public Optional<SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
215 final SchemaContextFactory factory = repository.createSchemaContextFactory(config(statementParserMode));
216 Optional<SchemaContext> sc;
219 // Spin get stable context version
223 sc = currentSchemaContext.get();
227 } while (cv != contextVersion);
229 // Version has been updated
230 Collection<SourceIdentifier> sources;
233 sources = ImmutableSet.copyOf(requiredSources);
234 } while (ver != version);
237 final ListenableFuture<SchemaContext> f = factory.createSchemaContext(sources, statementParserMode);
239 sc = Optional.of(f.get());
241 } catch (final InterruptedException e) {
242 throw new IllegalStateException("Interrupted while assembling schema context", e);
243 } catch (final ExecutionException e) {
244 LOG.info("Failed to fully assemble schema context for {}", sources, e);
245 final Throwable cause = e.getCause();
246 Verify.verify(cause instanceof SchemaResolutionException);
247 sources = ((SchemaResolutionException) cause).getResolvedSources();
251 LOG.debug("Resolved schema context for {}", sources);
253 synchronized (this) {
254 if (contextVersion == cv) {
255 currentSchemaContext.set(sc);
256 contextVersion = ver;
259 } while (version == ver);
265 public synchronized FluentFuture<YangTextSchemaSource> getSource(
266 final SourceIdentifier sourceIdentifier) {
267 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
269 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
271 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
272 + " not registered", sourceIdentifier));
275 return immediateFluentFuture(ret.iterator().next());
279 * Return the set of sources currently available in this resolved.
281 * @return An immutable point-in-time view of available sources.
283 public synchronized Set<SourceIdentifier> getAvailableSources() {
284 return ImmutableSet.copyOf(texts.keySet());
288 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
289 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
293 public SchemaContext trySchemaContext() throws SchemaResolutionException {
294 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
298 @SuppressWarnings("checkstyle:avoidHidingCauseException")
299 public SchemaContext trySchemaContext(final StatementParserMode statementParserMode)
300 throws SchemaResolutionException {
301 final ListenableFuture<SchemaContext> future = repository
302 .createSchemaContextFactory(config(statementParserMode))
303 .createSchemaContext(ImmutableSet.copyOf(requiredSources), statementParserMode);
307 } catch (final InterruptedException e) {
308 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
309 } catch (final ExecutionException e) {
310 final Throwable cause = e.getCause();
311 if (cause instanceof SchemaResolutionException) {
312 throw (SchemaResolutionException) cause;
315 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
320 public void close() {
324 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
325 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();