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.Verify;
17 import com.google.common.collect.ArrayListMultimap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Multimap;
20 import com.google.common.util.concurrent.FluentFuture;
21 import com.google.common.util.concurrent.ListenableFuture;
22 import java.io.IOException;
24 import java.time.Duration;
25 import java.util.Collection;
26 import java.util.Optional;
28 import java.util.concurrent.ConcurrentLinkedDeque;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.atomic.AtomicReference;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
34 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
35 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
36 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
37 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
38 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
43 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
44 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
45 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
46 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
47 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
48 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
53 import org.opendaylight.yangtools.yang.parser.rfc7950.ir.IRSchemaSource;
54 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
59 private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
60 private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
62 private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
63 private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
64 private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
65 new AtomicReference<>(Optional.empty());
66 private final GuavaSchemaSourceCache<IRSchemaSource> cache;
67 private final SchemaListenerRegistration transReg;
68 private final SchemaSourceRegistry registry;
69 private final SchemaRepository repository;
70 private volatile Object version = new Object();
71 private volatile Object contextVersion = version;
73 private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
74 this.repository = requireNonNull(repository);
75 this.registry = requireNonNull(registry);
77 final TextToIRTransformer t = TextToIRTransformer.create(repository, registry);
78 transReg = registry.registerSchemaSourceListener(t);
80 cache = GuavaSchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME);
83 public static @NonNull YangTextSchemaContextResolver create(final String name) {
84 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
85 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
88 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
89 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
90 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
94 * Register a {@link YangTextSchemaSource}.
96 * @param source YANG text source
97 * @return a YangTextSchemaSourceRegistration
98 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
99 * @throws IOException when the URL is not readable
100 * @throws SchemaSourceException When parsing encounters general error
102 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
103 throws SchemaSourceException, IOException, YangSyntaxErrorException {
104 checkArgument(source != null);
106 final IRSchemaSource ast = TextToIRTransformer.transformText(source);
107 LOG.trace("Resolved source {} to source {}", source, ast);
109 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
110 // does not, check how much it differs and emit a warning.
111 final SourceIdentifier providedId = source.getIdentifier();
112 final SourceIdentifier parsedId = ast.getIdentifier();
113 final YangTextSchemaSource text;
114 if (!parsedId.equals(providedId)) {
115 if (!parsedId.getName().equals(providedId.getName())) {
116 LOG.info("Provided module name {} does not match actual text {}, corrected",
117 providedId.toYangFilename(), parsedId.toYangFilename());
119 final Optional<Revision> sourceRev = providedId.getRevision();
120 final Optional<Revision> astRev = parsedId.getRevision();
121 if (sourceRev.isPresent()) {
122 if (!sourceRev.equals(astRev)) {
123 LOG.info("Provided module revision {} does not match actual text {}, corrected",
124 providedId.toYangFilename(), parsedId.toYangFilename());
127 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
131 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
136 synchronized (this) {
137 texts.put(parsedId, text);
138 LOG.debug("Populated {} with text", parsedId);
140 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
141 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
142 requiredSources.add(parsedId);
143 cache.schemaSourceEncountered(ast);
144 LOG.debug("Added source {} to schema context requirements", parsedId);
145 version = new Object();
147 return new AbstractYangTextSchemaSourceRegistration(text) {
149 protected void removeRegistration() {
150 synchronized (YangTextSchemaContextResolver.this) {
151 requiredSources.remove(parsedId);
152 LOG.trace("Removed source {} from schema context requirements", parsedId);
153 version = new Object();
155 texts.remove(parsedId, text);
163 * Register a URL containing a YANG text.
165 * @param url YANG text source URL
166 * @return a YangTextSchemaSourceRegistration for this URL
167 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
168 * @throws IOException when the URL is not readable
169 * @throws SchemaSourceException When parsing encounters general error
171 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
172 throws SchemaSourceException, IOException, YangSyntaxErrorException {
173 checkArgument(url != null, "Supplied URL must not be null");
175 final String path = url.getPath();
176 final String fileName = path.substring(path.lastIndexOf('/') + 1);
177 return registerSource(YangTextSchemaSource.forURL(url, guessSourceIdentifier(fileName)));
180 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
182 return YangTextSchemaSource.identifierFromFilename(fileName);
183 } catch (final IllegalArgumentException e) {
184 LOG.warn("Invalid file name format in '{}'", fileName, e);
185 return RevisionSourceIdentifier.create(fileName);
190 * Try to parse all currently available yang files and build new schema context.
192 * @return new schema context iif there is at least 1 yang file registered and
193 * new schema context was successfully built.
195 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
196 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
200 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
202 * @param statementParserMode mode of statement parser
203 * @return new schema context iif there is at least 1 yang file registered and
204 * new schema context was successfully built.
206 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
207 final StatementParserMode statementParserMode) {
208 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
209 config(statementParserMode));
210 Optional<EffectiveModelContext> sc;
213 // Spin get stable context version
217 sc = currentSchemaContext.get();
221 } while (cv != contextVersion);
223 // Version has been updated
224 Collection<SourceIdentifier> sources;
227 sources = ImmutableSet.copyOf(requiredSources);
228 } while (ver != version);
231 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
233 sc = Optional.of(f.get());
235 } catch (final InterruptedException e) {
236 throw new IllegalStateException("Interrupted while assembling schema context", e);
237 } catch (final ExecutionException e) {
238 LOG.info("Failed to fully assemble schema context for {}", sources, e);
239 final Throwable cause = e.getCause();
240 Verify.verify(cause instanceof SchemaResolutionException);
241 sources = ((SchemaResolutionException) cause).getResolvedSources();
245 LOG.debug("Resolved schema context for {}", sources);
247 synchronized (this) {
248 if (contextVersion == cv) {
249 currentSchemaContext.set(sc);
250 contextVersion = ver;
253 } while (version == ver);
259 public synchronized @NonNull FluentFuture<YangTextSchemaSource> getSource(
260 final SourceIdentifier sourceIdentifier) {
261 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
263 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
265 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
266 + " not registered", sourceIdentifier));
269 return immediateFluentFuture(ret.iterator().next());
273 * Return the set of sources currently available in this resolved.
275 * @return An immutable point-in-time view of available sources.
277 public synchronized Set<SourceIdentifier> getAvailableSources() {
278 return ImmutableSet.copyOf(texts.keySet());
282 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
283 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
287 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
288 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
292 @SuppressWarnings("checkstyle:avoidHidingCauseException")
293 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
294 throws SchemaResolutionException {
295 final ListenableFuture<EffectiveModelContext> future = repository
296 .createEffectiveModelContextFactory(config(statementParserMode))
297 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
301 } catch (final InterruptedException e) {
302 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
303 } catch (final ExecutionException e) {
304 final Throwable cause = e.getCause();
305 if (cause instanceof SchemaResolutionException) {
306 throw (SchemaResolutionException) cause;
309 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
314 public void close() {
318 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
319 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();