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.EffectiveModelContext;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
38 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
39 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
40 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
41 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
46 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
47 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
48 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
49 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
50 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
54 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
55 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
56 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
57 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
62 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
63 private static final long SOURCE_LIFETIME_SECONDS = 60;
65 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
66 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
67 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
68 new AtomicReference<>(Optional.empty());
69 private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
70 private final SchemaListenerRegistration transReg;
71 private final SchemaSourceRegistry registry;
72 private final SchemaRepository repository;
73 private volatile Object version = new Object();
74 private volatile Object contextVersion = version;
76 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
77 this.repository = requireNonNull(repository);
78 this.registry = requireNonNull(registry);
80 final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
81 transReg = registry.registerSchemaSourceListener(t);
83 cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
87 public static @NonNull YangTextSchemaContextResolver create(final String name) {
88 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
89 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
92 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
93 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
94 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
98 * Register a {@link YangTextSchemaSource}.
100 * @param source YANG text source
101 * @return a YangTextSchemaSourceRegistration
102 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
103 * @throws IOException when the URL is not readable
104 * @throws SchemaSourceException When parsing encounters general error
106 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
107 throws SchemaSourceException, IOException, YangSyntaxErrorException {
108 checkArgument(source != null);
110 final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
111 LOG.trace("Resolved source {} to source {}", source, ast);
113 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
114 // does not, check how much it differs and emit a warning.
115 final SourceIdentifier providedId = source.getIdentifier();
116 final SourceIdentifier parsedId = ast.getIdentifier();
117 final YangTextSchemaSource text;
118 if (!parsedId.equals(providedId)) {
119 if (!parsedId.getName().equals(providedId.getName())) {
120 LOG.info("Provided module name {} does not match actual text {}, corrected",
121 providedId.toYangFilename(), parsedId.toYangFilename());
123 final Optional<Revision> sourceRev = providedId.getRevision();
124 final Optional<Revision> astRev = parsedId.getRevision();
125 if (sourceRev.isPresent()) {
126 if (!sourceRev.equals(astRev)) {
127 LOG.info("Provided module revision {} does not match actual text {}, corrected",
128 providedId.toYangFilename(), parsedId.toYangFilename());
131 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
135 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
140 synchronized (this) {
141 texts.put(parsedId, text);
142 LOG.debug("Populated {} with text", parsedId);
144 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
145 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
146 requiredSources.add(parsedId);
147 cache.schemaSourceEncountered(ast);
148 LOG.debug("Added source {} to schema context requirements", parsedId);
149 version = new Object();
151 return new AbstractYangTextSchemaSourceRegistration(text) {
153 protected void removeRegistration() {
154 synchronized (YangTextSchemaContextResolver.this) {
155 requiredSources.remove(parsedId);
156 LOG.trace("Removed source {} from schema context requirements", parsedId);
157 version = new Object();
159 texts.remove(parsedId, text);
167 * Register a URL containing a YANG text.
169 * @param url YANG text source URL
170 * @return a YangTextSchemaSourceRegistration for this URL
171 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
172 * @throws IOException when the URL is not readable
173 * @throws SchemaSourceException When parsing encounters general error
175 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
176 throws SchemaSourceException, IOException, YangSyntaxErrorException {
177 checkArgument(url != null, "Supplied URL must not be null");
179 final String path = url.getPath();
180 final String fileName = path.substring(path.lastIndexOf('/') + 1);
181 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
182 return registerSource(new YangTextSchemaSource(guessedId) {
184 public InputStream openStream() throws IOException {
185 return url.openStream();
189 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
190 return toStringHelper.add("url", url);
195 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
197 return YangTextSchemaSource.identifierFromFilename(fileName);
198 } catch (final IllegalArgumentException e) {
199 LOG.warn("Invalid file name format in '{}'", fileName, e);
200 return RevisionSourceIdentifier.create(fileName);
205 * Try to parse all currently available yang files and build new schema context.
207 * @return new schema context iif there is at least 1 yang file registered and
208 * new schema context was successfully built.
210 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
211 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
215 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
217 * @param statementParserMode mode of statement parser
218 * @return new schema context iif there is at least 1 yang file registered and
219 * new schema context was successfully built.
221 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
222 final StatementParserMode statementParserMode) {
223 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
224 config(statementParserMode));
225 Optional<EffectiveModelContext> sc;
228 // Spin get stable context version
232 sc = currentSchemaContext.get();
236 } while (cv != contextVersion);
238 // Version has been updated
239 Collection<SourceIdentifier> sources;
242 sources = ImmutableSet.copyOf(requiredSources);
243 } while (ver != version);
246 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
248 sc = Optional.of(f.get());
250 } catch (final InterruptedException e) {
251 throw new IllegalStateException("Interrupted while assembling schema context", e);
252 } catch (final ExecutionException e) {
253 LOG.info("Failed to fully assemble schema context for {}", sources, e);
254 final Throwable cause = e.getCause();
255 Verify.verify(cause instanceof SchemaResolutionException);
256 sources = ((SchemaResolutionException) cause).getResolvedSources();
260 LOG.debug("Resolved schema context for {}", sources);
262 synchronized (this) {
263 if (contextVersion == cv) {
264 currentSchemaContext.set(sc);
265 contextVersion = ver;
268 } while (version == ver);
274 * Try to parse all currently available yang files and build new schema context.
276 * @return new schema context iif there is at least 1 yang file registered and new schema context was successfully
278 * @deprecated Use {@link #getEffectiveModelContext()} instead.
280 @Deprecated(forRemoval = true)
281 public Optional<? extends SchemaContext> getSchemaContext() {
282 return getEffectiveModelContext();
286 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
288 * @param statementParserMode mode of statement parser
289 * @return new schema context iif there is at least 1 yang file registered and
290 * new schema context was successfully built.
291 * @deprecated Use {@link #getEffectiveModelContext(StatementParserMode)} instead.
293 @Deprecated(forRemoval = true)
294 public Optional<? extends SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
295 return getEffectiveModelContext(statementParserMode);
299 public synchronized FluentFuture<YangTextSchemaSource> getSource(
300 final SourceIdentifier sourceIdentifier) {
301 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
303 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
305 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
306 + " not registered", sourceIdentifier));
309 return immediateFluentFuture(ret.iterator().next());
313 * Return the set of sources currently available in this resolved.
315 * @return An immutable point-in-time view of available sources.
317 public synchronized Set<SourceIdentifier> getAvailableSources() {
318 return ImmutableSet.copyOf(texts.keySet());
322 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
323 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
327 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
328 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
332 @SuppressWarnings("checkstyle:avoidHidingCauseException")
333 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
334 throws SchemaResolutionException {
335 final ListenableFuture<EffectiveModelContext> future = repository
336 .createEffectiveModelContextFactory(config(statementParserMode))
337 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
341 } catch (final InterruptedException e) {
342 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
343 } catch (final ExecutionException e) {
344 final Throwable cause = e.getCause();
345 if (cause instanceof SchemaResolutionException) {
346 throw (SchemaResolutionException) cause;
349 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
354 public void close() {
358 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
359 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();