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 java.util.Objects.requireNonNull;
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Verify;
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.FluentFuture;
18 import java.io.IOException;
20 import java.time.Duration;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Optional;
28 import java.util.concurrent.ConcurrentLinkedDeque;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.atomic.AtomicReference;
31 import org.checkerframework.checker.lock.qual.GuardedBy;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.opendaylight.yangtools.concepts.AbstractRegistration;
35 import org.opendaylight.yangtools.concepts.Registration;
36 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
37 import org.opendaylight.yangtools.yang.common.QNameModule;
38 import org.opendaylight.yangtools.yang.ir.YangIRSchemaSource;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureSet;
42 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
47 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
48 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
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.SchemaSourceProvider;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
53 import org.opendaylight.yangtools.yang.model.spi.source.YangTextSource;
54 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
55 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
56 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSource> {
61 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
62 private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
64 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
65 private final Multimap<SourceIdentifier, YangTextSource> texts = ArrayListMultimap.create();
67 private final Map<QNameModule, List<ImmutableSet<String>>> registeredFeatures = new HashMap<>();
68 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
69 new AtomicReference<>(Optional.empty());
70 private final GuavaSchemaSourceCache<YangIRSchemaSource> cache;
71 private final SchemaSourceRegistry registry;
72 private final SchemaRepository repository;
73 private final Registration transReg;
75 private volatile Object version = new Object();
76 private volatile Object contextVersion = version;
78 private FeatureSet supportedFeatures = null;
80 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
81 this.repository = requireNonNull(repository);
82 this.registry = requireNonNull(registry);
84 transReg = registry.registerSchemaSourceListener(TextToIRTransformer.create(repository, registry));
85 cache = GuavaSchemaSourceCache.createSoftCache(registry, YangIRSchemaSource.class, SOURCE_LIFETIME);
88 public static @NonNull YangTextSchemaContextResolver create(final String name) {
89 final var sharedRepo = new SharedSchemaRepository(name);
90 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
93 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
94 final var sharedRepo = new SharedSchemaRepository(name, factory);
95 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
99 * Register a {@link YangTextSource}.
101 * @param source YANG text source
102 * @return a {@link Registration}
103 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
104 * @throws IOException when the URL is not readable
105 * @throws SchemaSourceException When parsing encounters general error
106 * @throws NullPointerException if {@code source} is {@code null}
108 public @NonNull Registration registerSource(final @NonNull YangTextSource source)
109 throws SchemaSourceException, IOException, YangSyntaxErrorException {
110 final var ast = TextToIRTransformer.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 var providedId = source.sourceId();
116 final var parsedId = ast.sourceId();
117 final YangTextSource text;
118 if (!parsedId.equals(providedId)) {
119 if (!parsedId.name().equals(providedId.name())) {
120 LOG.info("Provided module name {} does not match actual text {}, corrected",
121 providedId.toYangFilename(), parsedId.toYangFilename());
123 final var sourceRev = providedId.revision();
124 if (sourceRev != null) {
125 if (!sourceRev.equals(parsedId.revision())) {
126 LOG.info("Provided module revision {} does not match actual text {}, corrected",
127 providedId.toYangFilename(), parsedId.toYangFilename());
130 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
134 text = YangTextSource.delegateForCharSource(parsedId, source);
139 synchronized (this) {
140 texts.put(parsedId, text);
141 LOG.debug("Populated {} with text", parsedId);
143 final var reg = registry.registerSchemaSource(this,
144 PotentialSchemaSource.create(parsedId, YangTextSource.class, Costs.IMMEDIATE.getValue()));
145 requiredSources.add(parsedId);
146 cache.schemaSourceEncountered(ast);
147 LOG.debug("Added source {} to schema context requirements", parsedId);
148 version = new Object();
150 return new AbstractRegistration() {
152 protected void removeRegistration() {
153 synchronized (YangTextSchemaContextResolver.this) {
154 requiredSources.remove(parsedId);
155 LOG.trace("Removed source {} from schema context requirements", parsedId);
156 version = new Object();
158 texts.remove(parsedId, text);
166 * Register a URL containing a YANG text.
168 * @param url YANG text source URL
169 * @return a YangTextSchemaSourceRegistration for this URL
170 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
171 * @throws IOException when the URL is not readable
172 * @throws SchemaSourceException When parsing encounters general error
173 * @throws NullPointerException if {@code url} is {@code null}
175 public @NonNull Registration registerSource(final @NonNull URL url)
176 throws SchemaSourceException, IOException, YangSyntaxErrorException {
177 final String path = url.getPath();
178 final String fileName = path.substring(path.lastIndexOf('/') + 1);
179 return registerSource(YangTextSource.forURL(url, guessSourceIdentifier(fileName)));
183 * Register a {@link QNameModule} as a known module namespace with a set of supported features. Union of these
184 * registrations is forwarded to {@link FeatureSet} and this is then used in {@link #getEffectiveModelContext()} and
187 * @param module Module namespace
188 * @param features Features supported for that module namespace
189 * @return a {@link Registration}, use {@link Registration#close()} to revert the effects of this method
190 * @throws NullPointerException if any argument is {@code null}
192 public @NonNull Registration registerSupportedFeatures(final QNameModule module, final Set<String> features) {
193 final var checked = requireNonNull(module);
194 final var copy = ImmutableSet.copyOf(features);
196 synchronized (this) {
197 version = new Object();
198 supportedFeatures = null;
199 registeredFeatures.computeIfAbsent(module, ignored -> new ArrayList<>()).add(copy);
201 return new AbstractRegistration() {
203 protected void removeRegistration() {
204 removeFeatures(checked, copy);
209 private synchronized void removeFeatures(final QNameModule module, final ImmutableSet<String> features) {
210 final var moduleFeatures = registeredFeatures.get(module);
211 if (moduleFeatures != null && moduleFeatures.remove(features)) {
212 if (moduleFeatures.isEmpty()) {
213 registeredFeatures.remove(module);
215 supportedFeatures = null;
216 version = new Object();
220 private synchronized @Nullable FeatureSet getSupportedFeatures() {
221 var local = supportedFeatures;
222 if (local == null && !registeredFeatures.isEmpty()) {
223 final var builder = FeatureSet.builder();
224 for (var entry : registeredFeatures.entrySet()) {
225 for (var features : entry.getValue()) {
226 builder.addModuleFeatures(entry.getKey(), features);
229 supportedFeatures = local = builder.build();
234 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
236 return YangTextSource.identifierFromFilename(fileName);
237 } catch (IllegalArgumentException e) {
238 LOG.warn("Invalid file name format in '{}'", fileName, e);
239 return new SourceIdentifier(fileName);
244 * Try to parse all currently available yang files and build new schema context.
246 * @return new schema context iif there is at least 1 yang file registered and
247 * new schema context was successfully built.
249 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
250 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
254 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
256 * @param statementParserMode mode of statement parser
257 * @return new schema context iif there is at least 1 yang file registered and
258 * new schema context was successfully built.
260 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
261 final StatementParserMode statementParserMode) {
262 Optional<EffectiveModelContext> sc;
265 // Spin get stable context version
269 sc = currentSchemaContext.get();
273 } while (cv != contextVersion);
275 // Version has been updated
276 Collection<SourceIdentifier> sources;
279 sources = ImmutableSet.copyOf(requiredSources);
280 } while (ver != version);
282 final var factory = repository.createEffectiveModelContextFactory(
283 config(statementParserMode, getSupportedFeatures()));
286 final var f = factory.createEffectiveModelContext(sources);
288 sc = Optional.of(f.get());
290 } catch (InterruptedException e) {
291 throw new IllegalStateException("Interrupted while assembling schema context", e);
292 } catch (ExecutionException e) {
293 LOG.info("Failed to fully assemble schema context for {}", sources, e);
294 final var cause = e.getCause();
295 Verify.verify(cause instanceof SchemaResolutionException);
296 sources = ((SchemaResolutionException) cause).getResolvedSources();
300 LOG.debug("Resolved schema context for {}", sources);
302 synchronized (this) {
303 if (contextVersion == cv) {
304 currentSchemaContext.set(sc);
305 contextVersion = ver;
308 } while (version == ver);
314 public synchronized @NonNull FluentFuture<YangTextSource> getSource(final SourceIdentifier sourceIdentifier) {
315 final var ret = texts.get(sourceIdentifier);
317 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
319 return FluentFutures.immediateFailedFluentFuture(
320 new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
323 return FluentFutures.immediateFluentFuture(ret.iterator().next());
327 * Return the set of sources currently available in this resolved.
329 * @return An immutable point-in-time view of available sources.
331 public synchronized Set<SourceIdentifier> getAvailableSources() {
332 return ImmutableSet.copyOf(texts.keySet());
336 public synchronized Collection<YangTextSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
337 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
341 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException, ExecutionException {
342 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
346 @SuppressWarnings("checkstyle:avoidHidingCauseException")
347 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
348 throws SchemaResolutionException, ExecutionException {
349 final var future = repository
350 .createEffectiveModelContextFactory(config(statementParserMode, getSupportedFeatures()))
351 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
355 } catch (InterruptedException e) {
356 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
357 } catch (ExecutionException e) {
358 if (e.getCause() instanceof SchemaResolutionException sre) {
366 public void close() {
370 private static @NonNull SchemaContextFactoryConfiguration config(
371 final StatementParserMode statementParserMode, final @Nullable FeatureSet supportedFeatures) {
372 final var builder = SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode);
373 if (supportedFeatures != null) {
374 builder.setSupportedFeatures(supportedFeatures);
376 return builder.build();