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 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
188 return toStringHelper.add("url", url);
193 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
195 return YangTextSchemaSource.identifierFromFilename(fileName);
196 } catch (final IllegalArgumentException e) {
197 LOG.warn("Invalid file name format in '{}'", fileName, e);
198 return RevisionSourceIdentifier.create(fileName);
203 * Try to parse all currently available yang files and build new schema context.
205 * @return new schema context iif there is at least 1 yang file registered and
206 * new schema context was successfully built.
208 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
209 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
213 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
215 * @param statementParserMode mode of statement parser
216 * @return new schema context iif there is at least 1 yang file registered and
217 * new schema context was successfully built.
219 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
220 final StatementParserMode statementParserMode) {
221 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
222 config(statementParserMode));
223 Optional<EffectiveModelContext> sc;
226 // Spin get stable context version
230 sc = currentSchemaContext.get();
234 } while (cv != contextVersion);
236 // Version has been updated
237 Collection<SourceIdentifier> sources;
240 sources = ImmutableSet.copyOf(requiredSources);
241 } while (ver != version);
244 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
246 sc = Optional.of(f.get());
248 } catch (final InterruptedException e) {
249 throw new IllegalStateException("Interrupted while assembling schema context", e);
250 } catch (final ExecutionException e) {
251 LOG.info("Failed to fully assemble schema context for {}", sources, e);
252 final Throwable cause = e.getCause();
253 Verify.verify(cause instanceof SchemaResolutionException);
254 sources = ((SchemaResolutionException) cause).getResolvedSources();
258 LOG.debug("Resolved schema context for {}", sources);
260 synchronized (this) {
261 if (contextVersion == cv) {
262 currentSchemaContext.set(sc);
263 contextVersion = ver;
266 } while (version == ver);
272 public synchronized FluentFuture<YangTextSchemaSource> getSource(
273 final SourceIdentifier sourceIdentifier) {
274 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
276 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
278 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
279 + " not registered", sourceIdentifier));
282 return immediateFluentFuture(ret.iterator().next());
286 * Return the set of sources currently available in this resolved.
288 * @return An immutable point-in-time view of available sources.
290 public synchronized Set<SourceIdentifier> getAvailableSources() {
291 return ImmutableSet.copyOf(texts.keySet());
295 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
296 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
300 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
301 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
305 @SuppressWarnings("checkstyle:avoidHidingCauseException")
306 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
307 throws SchemaResolutionException {
308 final ListenableFuture<EffectiveModelContext> future = repository
309 .createEffectiveModelContextFactory(config(statementParserMode))
310 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
314 } catch (final InterruptedException e) {
315 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
316 } catch (final ExecutionException e) {
317 final Throwable cause = e.getCause();
318 if (cause instanceof SchemaResolutionException) {
319 throw (SchemaResolutionException) cause;
322 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
327 public void close() {
331 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
332 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();