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.nio.charset.StandardCharsets;
21 import java.time.Duration;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.List;
27 import java.util.Optional;
29 import java.util.concurrent.ConcurrentLinkedDeque;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.atomic.AtomicReference;
32 import org.checkerframework.checker.lock.qual.GuardedBy;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.concepts.AbstractRegistration;
36 import org.opendaylight.yangtools.concepts.Registration;
37 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
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.source.YangTextSource;
42 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureSet;
43 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
47 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
48 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
49 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
50 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
51 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
54 import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
55 import org.opendaylight.yangtools.yang.model.spi.source.URLYangTextSource;
56 import org.opendaylight.yangtools.yang.model.spi.source.YangIRSchemaSource;
57 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
58 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
59 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSource> {
64 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
65 private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
67 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
68 private final Multimap<SourceIdentifier, YangTextSource> texts = ArrayListMultimap.create();
70 private final Map<QNameModule, List<ImmutableSet<String>>> registeredFeatures = new HashMap<>();
71 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
72 new AtomicReference<>(Optional.empty());
73 private final GuavaSchemaSourceCache<YangIRSchemaSource> cache;
74 private final SchemaSourceRegistry registry;
75 private final SchemaRepository repository;
76 private final Registration transReg;
78 private volatile Object version = new Object();
79 private volatile Object contextVersion = version;
81 private FeatureSet supportedFeatures = null;
83 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
84 this.repository = requireNonNull(repository);
85 this.registry = requireNonNull(registry);
87 transReg = registry.registerSchemaSourceListener(TextToIRTransformer.create(repository, registry));
88 cache = GuavaSchemaSourceCache.createSoftCache(registry, YangIRSchemaSource.class, SOURCE_LIFETIME);
91 public static @NonNull YangTextSchemaContextResolver create(final String name) {
92 final var sharedRepo = new SharedSchemaRepository(name);
93 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
96 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
97 final var sharedRepo = new SharedSchemaRepository(name, factory);
98 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
102 * Register a {@link YangTextSource}.
104 * @param source YANG text source
105 * @return a {@link Registration}
106 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
107 * @throws IOException when the URL is not readable
108 * @throws SchemaSourceException When parsing encounters general error
109 * @throws NullPointerException if {@code source} is {@code null}
111 public @NonNull Registration registerSource(final @NonNull YangTextSource source)
112 throws SchemaSourceException, IOException, YangSyntaxErrorException {
113 final var ast = TextToIRTransformer.transformText(source);
114 LOG.trace("Resolved source {} to source {}", source, ast);
116 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
117 // does not, check how much it differs and emit a warning.
118 final var providedId = source.sourceId();
119 final var parsedId = ast.sourceId();
120 final YangTextSource text;
121 if (!parsedId.equals(providedId)) {
122 if (!parsedId.name().equals(providedId.name())) {
123 LOG.info("Provided module name {} does not match actual text {}, corrected",
124 providedId.toYangFilename(), parsedId.toYangFilename());
126 final var sourceRev = providedId.revision();
127 if (sourceRev != null) {
128 if (!sourceRev.equals(parsedId.revision())) {
129 LOG.info("Provided module revision {} does not match actual text {}, corrected",
130 providedId.toYangFilename(), parsedId.toYangFilename());
133 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
137 text = new DelegatedYangTextSource(parsedId, source);
142 synchronized (this) {
143 texts.put(parsedId, text);
144 LOG.debug("Populated {} with text", parsedId);
146 final var reg = registry.registerSchemaSource(this,
147 PotentialSchemaSource.create(parsedId, YangTextSource.class, Costs.IMMEDIATE.getValue()));
148 requiredSources.add(parsedId);
149 cache.schemaSourceEncountered(ast);
150 LOG.debug("Added source {} to schema context requirements", parsedId);
151 version = new Object();
153 return new AbstractRegistration() {
155 protected void removeRegistration() {
156 synchronized (YangTextSchemaContextResolver.this) {
157 requiredSources.remove(parsedId);
158 LOG.trace("Removed source {} from schema context requirements", parsedId);
159 version = new Object();
161 texts.remove(parsedId, text);
169 * Register a URL containing a YANG text.
171 * @param url YANG text source URL
172 * @return a YangTextSchemaSourceRegistration for this URL
173 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
174 * @throws IOException when the URL is not readable
175 * @throws SchemaSourceException When parsing encounters general error
176 * @throws NullPointerException if {@code url} is {@code null}
178 public @NonNull Registration registerSource(final @NonNull URL url)
179 throws SchemaSourceException, IOException, YangSyntaxErrorException {
180 final String path = url.getPath();
181 final String fileName = path.substring(path.lastIndexOf('/') + 1);
182 return registerSource(new URLYangTextSource(guessSourceIdentifier(fileName), url, StandardCharsets.UTF_8));
186 * Register a {@link QNameModule} as a known module namespace with a set of supported features. Union of these
187 * registrations is forwarded to {@link FeatureSet} and this is then used in {@link #getEffectiveModelContext()} and
190 * @param module Module namespace
191 * @param features Features supported for that module namespace
192 * @return a {@link Registration}, use {@link Registration#close()} to revert the effects of this method
193 * @throws NullPointerException if any argument is {@code null}
195 public @NonNull Registration registerSupportedFeatures(final QNameModule module, final Set<String> features) {
196 final var checked = requireNonNull(module);
197 final var copy = ImmutableSet.copyOf(features);
199 synchronized (this) {
200 version = new Object();
201 supportedFeatures = null;
202 registeredFeatures.computeIfAbsent(module, ignored -> new ArrayList<>()).add(copy);
204 return new AbstractRegistration() {
206 protected void removeRegistration() {
207 removeFeatures(checked, copy);
212 private synchronized void removeFeatures(final QNameModule module, final ImmutableSet<String> features) {
213 final var moduleFeatures = registeredFeatures.get(module);
214 if (moduleFeatures != null && moduleFeatures.remove(features)) {
215 if (moduleFeatures.isEmpty()) {
216 registeredFeatures.remove(module);
218 supportedFeatures = null;
219 version = new Object();
223 private synchronized @Nullable FeatureSet getSupportedFeatures() {
224 var local = supportedFeatures;
225 if (local == null && !registeredFeatures.isEmpty()) {
226 final var builder = FeatureSet.builder();
227 for (var entry : registeredFeatures.entrySet()) {
228 for (var features : entry.getValue()) {
229 builder.addModuleFeatures(entry.getKey(), features);
232 supportedFeatures = local = builder.build();
237 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
239 return SourceIdentifier.ofYangFileName(fileName);
240 } catch (IllegalArgumentException e) {
241 LOG.warn("Invalid file name format in '{}'", fileName, e);
242 return new SourceIdentifier(fileName);
247 * Try to parse all currently available yang files and build new schema context.
249 * @return new schema context iif there is at least 1 yang file registered and
250 * new schema context was successfully built.
252 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
253 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
257 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
259 * @param statementParserMode mode of statement parser
260 * @return new schema context iif there is at least 1 yang file registered and
261 * new schema context was successfully built.
263 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
264 final StatementParserMode statementParserMode) {
265 Optional<EffectiveModelContext> sc;
268 // Spin get stable context version
272 sc = currentSchemaContext.get();
276 } while (cv != contextVersion);
278 // Version has been updated
279 Collection<SourceIdentifier> sources;
282 sources = ImmutableSet.copyOf(requiredSources);
283 } while (ver != version);
285 final var factory = repository.createEffectiveModelContextFactory(
286 config(statementParserMode, getSupportedFeatures()));
289 final var f = factory.createEffectiveModelContext(sources);
291 sc = Optional.of(f.get());
293 } catch (InterruptedException e) {
294 throw new IllegalStateException("Interrupted while assembling schema context", e);
295 } catch (ExecutionException e) {
296 LOG.info("Failed to fully assemble schema context for {}", sources, e);
297 final var cause = e.getCause();
298 Verify.verify(cause instanceof SchemaResolutionException);
299 sources = ((SchemaResolutionException) cause).getResolvedSources();
303 LOG.debug("Resolved schema context for {}", sources);
305 synchronized (this) {
306 if (contextVersion == cv) {
307 currentSchemaContext.set(sc);
308 contextVersion = ver;
311 } while (version == ver);
317 public synchronized @NonNull FluentFuture<YangTextSource> getSource(final SourceIdentifier sourceIdentifier) {
318 final var ret = texts.get(sourceIdentifier);
320 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
322 return FluentFutures.immediateFailedFluentFuture(
323 new MissingSchemaSourceException(sourceIdentifier, "URL for " + sourceIdentifier + " not registered"));
326 return FluentFutures.immediateFluentFuture(ret.iterator().next());
330 * Return the set of sources currently available in this resolved.
332 * @return An immutable point-in-time view of available sources.
334 public synchronized Set<SourceIdentifier> getAvailableSources() {
335 return ImmutableSet.copyOf(texts.keySet());
339 public synchronized Collection<YangTextSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
340 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
344 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException, ExecutionException {
345 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
349 @SuppressWarnings("checkstyle:avoidHidingCauseException")
350 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
351 throws SchemaResolutionException, ExecutionException {
352 final var future = repository
353 .createEffectiveModelContextFactory(config(statementParserMode, getSupportedFeatures()))
354 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
358 } catch (InterruptedException e) {
359 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
360 } catch (ExecutionException e) {
361 if (e.getCause() instanceof SchemaResolutionException sre) {
369 public void close() {
373 private static @NonNull SchemaContextFactoryConfiguration config(
374 final StatementParserMode statementParserMode, final @Nullable FeatureSet supportedFeatures) {
375 final var builder = SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode);
376 if (supportedFeatures != null) {
377 builder.setSupportedFeatures(supportedFeatures);
379 return builder.build();