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.time.Duration;
27 import java.util.Collection;
28 import java.util.Optional;
30 import java.util.concurrent.ConcurrentLinkedDeque;
31 import java.util.concurrent.ExecutionException;
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.parser.api.YangParserFactory;
37 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
38 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
39 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
40 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
45 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
46 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
47 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
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.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.parser.rfc7950.ir.IRSchemaSource;
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<YangTextSchemaSource> {
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, YangTextSchemaSource> texts = ArrayListMultimap.create();
66 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
67 new AtomicReference<>(Optional.empty());
68 private final GuavaSchemaSourceCache<IRSchemaSource> cache;
69 private final SchemaListenerRegistration transReg;
70 private final SchemaSourceRegistry registry;
71 private final SchemaRepository repository;
72 private volatile Object version = new Object();
73 private volatile Object contextVersion = version;
75 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
76 this.repository = requireNonNull(repository);
77 this.registry = requireNonNull(registry);
79 final TextToIRTransformer t = TextToIRTransformer.create(repository, registry);
80 transReg = registry.registerSchemaSourceListener(t);
82 cache = GuavaSchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME);
85 public static @NonNull YangTextSchemaContextResolver create(final String name) {
86 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
87 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
90 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
91 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
92 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
96 * Register a {@link YangTextSchemaSource}.
98 * @param source YANG text source
99 * @return a YangTextSchemaSourceRegistration
100 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
101 * @throws IOException when the URL is not readable
102 * @throws SchemaSourceException When parsing encounters general error
104 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
105 throws SchemaSourceException, IOException, YangSyntaxErrorException {
106 checkArgument(source != null);
108 final IRSchemaSource ast = TextToIRTransformer.transformText(source);
109 LOG.trace("Resolved source {} to source {}", source, ast);
111 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
112 // does not, check how much it differs and emit a warning.
113 final SourceIdentifier providedId = source.getIdentifier();
114 final SourceIdentifier parsedId = ast.getIdentifier();
115 final YangTextSchemaSource text;
116 if (!parsedId.equals(providedId)) {
117 if (!parsedId.getName().equals(providedId.getName())) {
118 LOG.info("Provided module name {} does not match actual text {}, corrected",
119 providedId.toYangFilename(), parsedId.toYangFilename());
121 final Optional<Revision> sourceRev = providedId.getRevision();
122 final Optional<Revision> astRev = parsedId.getRevision();
123 if (sourceRev.isPresent()) {
124 if (!sourceRev.equals(astRev)) {
125 LOG.info("Provided module revision {} does not match actual text {}, corrected",
126 providedId.toYangFilename(), parsedId.toYangFilename());
129 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
133 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
138 synchronized (this) {
139 texts.put(parsedId, text);
140 LOG.debug("Populated {} with text", parsedId);
142 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
143 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
144 requiredSources.add(parsedId);
145 cache.schemaSourceEncountered(ast);
146 LOG.debug("Added source {} to schema context requirements", parsedId);
147 version = new Object();
149 return new AbstractYangTextSchemaSourceRegistration(text) {
151 protected void removeRegistration() {
152 synchronized (YangTextSchemaContextResolver.this) {
153 requiredSources.remove(parsedId);
154 LOG.trace("Removed source {} from schema context requirements", parsedId);
155 version = new Object();
157 texts.remove(parsedId, text);
165 * Register a URL containing a YANG text.
167 * @param url YANG text source URL
168 * @return a YangTextSchemaSourceRegistration for this URL
169 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
170 * @throws IOException when the URL is not readable
171 * @throws SchemaSourceException When parsing encounters general error
173 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
174 throws SchemaSourceException, IOException, YangSyntaxErrorException {
175 checkArgument(url != null, "Supplied URL must not be null");
177 final String path = url.getPath();
178 final String fileName = path.substring(path.lastIndexOf('/') + 1);
179 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
180 return registerSource(new YangTextSchemaSource(guessedId) {
182 public InputStream openStream() throws IOException {
183 return url.openStream();
187 public Optional<String> getSymbolicName() {
188 return Optional.of(url.toString());
192 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
193 return toStringHelper.add("url", url);
198 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
200 return YangTextSchemaSource.identifierFromFilename(fileName);
201 } catch (final IllegalArgumentException e) {
202 LOG.warn("Invalid file name format in '{}'", fileName, e);
203 return RevisionSourceIdentifier.create(fileName);
208 * Try to parse all currently available yang files and build new schema context.
210 * @return new schema context iif there is at least 1 yang file registered and
211 * new schema context was successfully built.
213 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
214 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
218 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
220 * @param statementParserMode mode of statement parser
221 * @return new schema context iif there is at least 1 yang file registered and
222 * new schema context was successfully built.
224 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
225 final StatementParserMode statementParserMode) {
226 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
227 config(statementParserMode));
228 Optional<EffectiveModelContext> sc;
231 // Spin get stable context version
235 sc = currentSchemaContext.get();
239 } while (cv != contextVersion);
241 // Version has been updated
242 Collection<SourceIdentifier> sources;
245 sources = ImmutableSet.copyOf(requiredSources);
246 } while (ver != version);
249 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
251 sc = Optional.of(f.get());
253 } catch (final InterruptedException e) {
254 throw new IllegalStateException("Interrupted while assembling schema context", e);
255 } catch (final ExecutionException e) {
256 LOG.info("Failed to fully assemble schema context for {}", sources, e);
257 final Throwable cause = e.getCause();
258 Verify.verify(cause instanceof SchemaResolutionException);
259 sources = ((SchemaResolutionException) cause).getResolvedSources();
263 LOG.debug("Resolved schema context for {}", sources);
265 synchronized (this) {
266 if (contextVersion == cv) {
267 currentSchemaContext.set(sc);
268 contextVersion = ver;
271 } while (version == ver);
277 public synchronized FluentFuture<YangTextSchemaSource> getSource(
278 final SourceIdentifier sourceIdentifier) {
279 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
281 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
283 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
284 + " not registered", sourceIdentifier));
287 return immediateFluentFuture(ret.iterator().next());
291 * Return the set of sources currently available in this resolved.
293 * @return An immutable point-in-time view of available sources.
295 public synchronized Set<SourceIdentifier> getAvailableSources() {
296 return ImmutableSet.copyOf(texts.keySet());
300 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
301 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
305 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
306 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
310 @SuppressWarnings("checkstyle:avoidHidingCauseException")
311 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
312 throws SchemaResolutionException {
313 final ListenableFuture<EffectiveModelContext> future = repository
314 .createEffectiveModelContextFactory(config(statementParserMode))
315 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
319 } catch (final InterruptedException e) {
320 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
321 } catch (final ExecutionException e) {
322 final Throwable cause = e.getCause();
323 if (cause instanceof SchemaResolutionException) {
324 throw (SchemaResolutionException) cause;
327 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
332 public void close() {
336 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
337 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();