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;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.ArrayListMultimap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Multimap;
18 import com.google.common.util.concurrent.FluentFuture;
19 import java.io.IOException;
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.stmt.FeatureSet;
41 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
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.YangIRSchemaSource;
49 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
50 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
51 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
52 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
54 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
55 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
56 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
57 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
58 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
63 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
64 private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
66 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
67 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
69 private final Map<QNameModule, List<ImmutableSet<String>>> registeredFeatures = new HashMap<>();
70 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
71 new AtomicReference<>(Optional.empty());
72 private final GuavaSchemaSourceCache<YangIRSchemaSource> cache;
73 private final SchemaListenerRegistration transReg;
74 private final SchemaSourceRegistry registry;
75 private final SchemaRepository repository;
77 private volatile Object version = new Object();
78 private volatile Object contextVersion = version;
80 private FeatureSet supportedFeatures = null;
82 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
83 this.repository = requireNonNull(repository);
84 this.registry = requireNonNull(registry);
86 transReg = registry.registerSchemaSourceListener(TextToIRTransformer.create(repository, registry));
87 cache = GuavaSchemaSourceCache.createSoftCache(registry, YangIRSchemaSource.class, SOURCE_LIFETIME);
90 public static @NonNull YangTextSchemaContextResolver create(final String name) {
91 final var sharedRepo = new SharedSchemaRepository(name);
92 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
95 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
96 final var sharedRepo = new SharedSchemaRepository(name, factory);
97 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
101 * Register a {@link YangTextSchemaSource}.
103 * @param source YANG text source
104 * @return a YangTextSchemaSourceRegistration
105 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
106 * @throws IOException when the URL is not readable
107 * @throws SchemaSourceException When parsing encounters general error
109 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
110 throws SchemaSourceException, IOException, YangSyntaxErrorException {
111 checkArgument(source != null);
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.getIdentifier();
119 final var parsedId = ast.getIdentifier();
120 final YangTextSchemaSource 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 = YangTextSchemaSource.delegateForByteSource(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, YangTextSchemaSource.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 AbstractYangTextSchemaSourceRegistration(text) {
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
177 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
178 throws SchemaSourceException, IOException, YangSyntaxErrorException {
179 checkArgument(url != null, "Supplied URL must not be null");
181 final String path = url.getPath();
182 final String fileName = path.substring(path.lastIndexOf('/') + 1);
183 return registerSource(YangTextSchemaSource.forURL(url, guessSourceIdentifier(fileName)));
187 * Register a {@link QNameModule} as a known module namespace with a set of supported features. Union of these
188 * registrations is forwarded to {@link FeatureSet} and this is then used in {@link #getEffectiveModelContext()} and
191 * @param module Module namespace
192 * @param features Features supported for that module namespace
193 * @return a {@link Registration}, use {@link Registration#close()} to revert the effects of this method
194 * @throws NullPointerException if any argument is {@code null}
196 public @NonNull Registration registerSupportedFeatures(final QNameModule module, final Set<String> features) {
197 final var checked = requireNonNull(module);
198 final var copy = ImmutableSet.copyOf(features);
200 synchronized (this) {
201 version = new Object();
202 supportedFeatures = null;
203 registeredFeatures.computeIfAbsent(module, ignored -> new ArrayList<>()).add(copy);
205 return new AbstractRegistration() {
207 protected void removeRegistration() {
208 removeFeatures(checked, copy);
213 private synchronized void removeFeatures(final QNameModule module, final ImmutableSet<String> features) {
214 final var moduleFeatures = registeredFeatures.get(module);
215 if (moduleFeatures != null && moduleFeatures.remove(features)) {
216 if (moduleFeatures.isEmpty()) {
217 registeredFeatures.remove(module);
219 supportedFeatures = null;
220 version = new Object();
224 private synchronized @Nullable FeatureSet getSupportedFeatures() {
225 var local = supportedFeatures;
226 if (local == null && !registeredFeatures.isEmpty()) {
227 final var builder = FeatureSet.builder();
228 for (var entry : registeredFeatures.entrySet()) {
229 for (var features : entry.getValue()) {
230 builder.addModuleFeatures(entry.getKey(), features);
233 supportedFeatures = local = builder.build();
238 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
240 return YangTextSchemaSource.identifierFromFilename(fileName);
241 } catch (IllegalArgumentException e) {
242 LOG.warn("Invalid file name format in '{}'", fileName, e);
243 return new SourceIdentifier(fileName);
248 * Try to parse all currently available yang files and build new schema context.
250 * @return new schema context iif there is at least 1 yang file registered and
251 * new schema context was successfully built.
253 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
254 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
258 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
260 * @param statementParserMode mode of statement parser
261 * @return new schema context iif there is at least 1 yang file registered and
262 * new schema context was successfully built.
264 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
265 final StatementParserMode statementParserMode) {
266 Optional<EffectiveModelContext> sc;
269 // Spin get stable context version
273 sc = currentSchemaContext.get();
277 } while (cv != contextVersion);
279 // Version has been updated
280 Collection<SourceIdentifier> sources;
283 sources = ImmutableSet.copyOf(requiredSources);
284 } while (ver != version);
286 final var factory = repository.createEffectiveModelContextFactory(
287 config(statementParserMode, getSupportedFeatures()));
290 final var f = factory.createEffectiveModelContext(sources);
292 sc = Optional.of(f.get());
294 } catch (InterruptedException e) {
295 throw new IllegalStateException("Interrupted while assembling schema context", e);
296 } catch (ExecutionException e) {
297 LOG.info("Failed to fully assemble schema context for {}", sources, e);
298 final var cause = e.getCause();
299 Verify.verify(cause instanceof SchemaResolutionException);
300 sources = ((SchemaResolutionException) cause).getResolvedSources();
304 LOG.debug("Resolved schema context for {}", sources);
306 synchronized (this) {
307 if (contextVersion == cv) {
308 currentSchemaContext.set(sc);
309 contextVersion = ver;
312 } while (version == ver);
318 public synchronized @NonNull FluentFuture<YangTextSchemaSource> getSource(
319 final SourceIdentifier sourceIdentifier) {
320 final var ret = texts.get(sourceIdentifier);
322 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
324 return FluentFutures.immediateFailedFluentFuture(
325 new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
328 return FluentFutures.immediateFluentFuture(ret.iterator().next());
332 * Return the set of sources currently available in this resolved.
334 * @return An immutable point-in-time view of available sources.
336 public synchronized Set<SourceIdentifier> getAvailableSources() {
337 return ImmutableSet.copyOf(texts.keySet());
341 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
342 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
346 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
347 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
351 @SuppressWarnings("checkstyle:avoidHidingCauseException")
352 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
353 throws SchemaResolutionException {
354 final var future = repository
355 .createEffectiveModelContextFactory(config(statementParserMode, getSupportedFeatures()))
356 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
360 } catch (InterruptedException e) {
361 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
362 } catch (ExecutionException e) {
363 final var cause = e.getCause();
364 if (cause instanceof SchemaResolutionException resolutionException) {
365 throw resolutionException;
367 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
372 public void close() {
376 private static @NonNull SchemaContextFactoryConfiguration config(
377 final StatementParserMode statementParserMode, final @Nullable FeatureSet supportedFeatures) {
378 final var builder = SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode);
379 if (supportedFeatures != null) {
380 builder.setSupportedFeatures(supportedFeatures);
382 return builder.build();