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.util.Collection;
27 import java.util.Optional;
29 import java.util.concurrent.ConcurrentLinkedDeque;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
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.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
38 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
39 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
40 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
41 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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.YangTextSchemaSource;
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.model.repo.util.InMemorySchemaSourceCache;
56 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource;
57 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
58 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer;
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<YangTextSchemaSource> {
64 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
65 private static final long SOURCE_LIFETIME_SECONDS = 60;
67 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
68 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
69 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
70 new AtomicReference<>(Optional.empty());
71 private final InMemorySchemaSourceCache<IRSchemaSource> cache;
72 private final SchemaListenerRegistration transReg;
73 private final SchemaSourceRegistry registry;
74 private final SchemaRepository repository;
75 private volatile Object version = new Object();
76 private volatile Object contextVersion = version;
78 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
79 this.repository = requireNonNull(repository);
80 this.registry = requireNonNull(registry);
82 final TextToIRTransformer t = TextToIRTransformer.create(repository, registry);
83 transReg = registry.registerSchemaSourceListener(t);
85 cache = InMemorySchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME_SECONDS,
89 public static @NonNull YangTextSchemaContextResolver create(final String name) {
90 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
91 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
94 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
95 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
96 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
100 * Register a {@link YangTextSchemaSource}.
102 * @param source YANG text source
103 * @return a YangTextSchemaSourceRegistration
104 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
105 * @throws IOException when the URL is not readable
106 * @throws SchemaSourceException When parsing encounters general error
108 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
109 throws SchemaSourceException, IOException, YangSyntaxErrorException {
110 checkArgument(source != null);
112 final ASTSchemaSource ast = TextToASTTransformer.transformText(source);
113 LOG.trace("Resolved source {} to source {}", source, ast);
115 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
116 // does not, check how much it differs and emit a warning.
117 final SourceIdentifier providedId = source.getIdentifier();
118 final SourceIdentifier parsedId = ast.getIdentifier();
119 final YangTextSchemaSource text;
120 if (!parsedId.equals(providedId)) {
121 if (!parsedId.getName().equals(providedId.getName())) {
122 LOG.info("Provided module name {} does not match actual text {}, corrected",
123 providedId.toYangFilename(), parsedId.toYangFilename());
125 final Optional<Revision> sourceRev = providedId.getRevision();
126 final Optional<Revision> astRev = parsedId.getRevision();
127 if (sourceRev.isPresent()) {
128 if (!sourceRev.equals(astRev)) {
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 SchemaSourceRegistration<YangTextSchemaSource> 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 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
184 return registerSource(new YangTextSchemaSource(guessedId) {
186 public InputStream openStream() throws IOException {
187 return url.openStream();
191 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
192 return toStringHelper.add("url", url);
197 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
199 return YangTextSchemaSource.identifierFromFilename(fileName);
200 } catch (final IllegalArgumentException e) {
201 LOG.warn("Invalid file name format in '{}'", fileName, e);
202 return RevisionSourceIdentifier.create(fileName);
207 * Try to parse all currently available yang files and build new schema context.
209 * @return new schema context iif there is at least 1 yang file registered and
210 * new schema context was successfully built.
212 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
213 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
217 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
219 * @param statementParserMode mode of statement parser
220 * @return new schema context iif there is at least 1 yang file registered and
221 * new schema context was successfully built.
223 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
224 final StatementParserMode statementParserMode) {
225 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
226 config(statementParserMode));
227 Optional<EffectiveModelContext> sc;
230 // Spin get stable context version
234 sc = currentSchemaContext.get();
238 } while (cv != contextVersion);
240 // Version has been updated
241 Collection<SourceIdentifier> sources;
244 sources = ImmutableSet.copyOf(requiredSources);
245 } while (ver != version);
248 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
250 sc = Optional.of(f.get());
252 } catch (final InterruptedException e) {
253 throw new IllegalStateException("Interrupted while assembling schema context", e);
254 } catch (final ExecutionException e) {
255 LOG.info("Failed to fully assemble schema context for {}", sources, e);
256 final Throwable cause = e.getCause();
257 Verify.verify(cause instanceof SchemaResolutionException);
258 sources = ((SchemaResolutionException) cause).getResolvedSources();
262 LOG.debug("Resolved schema context for {}", sources);
264 synchronized (this) {
265 if (contextVersion == cv) {
266 currentSchemaContext.set(sc);
267 contextVersion = ver;
270 } while (version == ver);
276 * Try to parse all currently available yang files and build new schema context.
278 * @return new schema context iif there is at least 1 yang file registered and new schema context was successfully
280 * @deprecated Use {@link #getEffectiveModelContext()} instead.
282 @Deprecated(forRemoval = true)
283 public Optional<? extends SchemaContext> getSchemaContext() {
284 return getEffectiveModelContext();
288 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
290 * @param statementParserMode mode of statement parser
291 * @return new schema context iif there is at least 1 yang file registered and
292 * new schema context was successfully built.
293 * @deprecated Use {@link #getEffectiveModelContext(StatementParserMode)} instead.
295 @Deprecated(forRemoval = true)
296 public Optional<? extends SchemaContext> getSchemaContext(final StatementParserMode statementParserMode) {
297 return getEffectiveModelContext(statementParserMode);
301 public synchronized FluentFuture<YangTextSchemaSource> getSource(
302 final SourceIdentifier sourceIdentifier) {
303 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
305 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
307 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
308 + " not registered", sourceIdentifier));
311 return immediateFluentFuture(ret.iterator().next());
315 * Return the set of sources currently available in this resolved.
317 * @return An immutable point-in-time view of available sources.
319 public synchronized Set<SourceIdentifier> getAvailableSources() {
320 return ImmutableSet.copyOf(texts.keySet());
324 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
325 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
329 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
330 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
334 @SuppressWarnings("checkstyle:avoidHidingCauseException")
335 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
336 throws SchemaResolutionException {
337 final ListenableFuture<EffectiveModelContext> future = repository
338 .createEffectiveModelContextFactory(config(statementParserMode))
339 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
343 } catch (final InterruptedException e) {
344 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
345 } catch (final ExecutionException e) {
346 final Throwable cause = e.getCause();
347 if (cause instanceof SchemaResolutionException) {
348 throw (SchemaResolutionException) cause;
351 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
356 public void close() {
360 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
361 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();