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.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.PotentialSchemaSource;
49 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
54 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
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 long SOURCE_LIFETIME_SECONDS = 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 InMemorySchemaSourceCache<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 = InMemorySchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME_SECONDS,
86 public static @NonNull YangTextSchemaContextResolver create(final String name) {
87 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
88 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
91 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
92 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
93 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
97 * Register a {@link YangTextSchemaSource}.
99 * @param source YANG text source
100 * @return a YangTextSchemaSourceRegistration
101 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
102 * @throws IOException when the URL is not readable
103 * @throws SchemaSourceException When parsing encounters general error
105 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
106 throws SchemaSourceException, IOException, YangSyntaxErrorException {
107 checkArgument(source != null);
109 final IRSchemaSource ast = TextToIRTransformer.transformText(source);
110 LOG.trace("Resolved source {} to source {}", source, ast);
112 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
113 // does not, check how much it differs and emit a warning.
114 final SourceIdentifier providedId = source.getIdentifier();
115 final SourceIdentifier parsedId = ast.getIdentifier();
116 final YangTextSchemaSource text;
117 if (!parsedId.equals(providedId)) {
118 if (!parsedId.getName().equals(providedId.getName())) {
119 LOG.info("Provided module name {} does not match actual text {}, corrected",
120 providedId.toYangFilename(), parsedId.toYangFilename());
122 final Optional<Revision> sourceRev = providedId.getRevision();
123 final Optional<Revision> astRev = parsedId.getRevision();
124 if (sourceRev.isPresent()) {
125 if (!sourceRev.equals(astRev)) {
126 LOG.info("Provided module revision {} does not match actual text {}, corrected",
127 providedId.toYangFilename(), parsedId.toYangFilename());
130 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
134 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
139 synchronized (this) {
140 texts.put(parsedId, text);
141 LOG.debug("Populated {} with text", parsedId);
143 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
144 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
145 requiredSources.add(parsedId);
146 cache.schemaSourceEncountered(ast);
147 LOG.debug("Added source {} to schema context requirements", parsedId);
148 version = new Object();
150 return new AbstractYangTextSchemaSourceRegistration(text) {
152 protected void removeRegistration() {
153 synchronized (YangTextSchemaContextResolver.this) {
154 requiredSources.remove(parsedId);
155 LOG.trace("Removed source {} from schema context requirements", parsedId);
156 version = new Object();
158 texts.remove(parsedId, text);
166 * Register a URL containing a YANG text.
168 * @param url YANG text source URL
169 * @return a YangTextSchemaSourceRegistration for this URL
170 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
171 * @throws IOException when the URL is not readable
172 * @throws SchemaSourceException When parsing encounters general error
174 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
175 throws SchemaSourceException, IOException, YangSyntaxErrorException {
176 checkArgument(url != null, "Supplied URL must not be null");
178 final String path = url.getPath();
179 final String fileName = path.substring(path.lastIndexOf('/') + 1);
180 final SourceIdentifier guessedId = guessSourceIdentifier(fileName);
181 return registerSource(new YangTextSchemaSource(guessedId) {
183 public InputStream openStream() throws IOException {
184 return url.openStream();
188 public Optional<String> getSymbolicName() {
189 return Optional.of(url.toString());
193 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
194 return toStringHelper.add("url", url);
199 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
201 return YangTextSchemaSource.identifierFromFilename(fileName);
202 } catch (final IllegalArgumentException e) {
203 LOG.warn("Invalid file name format in '{}'", fileName, e);
204 return RevisionSourceIdentifier.create(fileName);
209 * Try to parse all currently available yang files and build new schema context.
211 * @return new schema context iif there is at least 1 yang file registered and
212 * new schema context was successfully built.
214 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
215 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
219 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
221 * @param statementParserMode mode of statement parser
222 * @return new schema context iif there is at least 1 yang file registered and
223 * new schema context was successfully built.
225 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
226 final StatementParserMode statementParserMode) {
227 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
228 config(statementParserMode));
229 Optional<EffectiveModelContext> sc;
232 // Spin get stable context version
236 sc = currentSchemaContext.get();
240 } while (cv != contextVersion);
242 // Version has been updated
243 Collection<SourceIdentifier> sources;
246 sources = ImmutableSet.copyOf(requiredSources);
247 } while (ver != version);
250 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
252 sc = Optional.of(f.get());
254 } catch (final InterruptedException e) {
255 throw new IllegalStateException("Interrupted while assembling schema context", e);
256 } catch (final ExecutionException e) {
257 LOG.info("Failed to fully assemble schema context for {}", sources, e);
258 final Throwable cause = e.getCause();
259 Verify.verify(cause instanceof SchemaResolutionException);
260 sources = ((SchemaResolutionException) cause).getResolvedSources();
264 LOG.debug("Resolved schema context for {}", sources);
266 synchronized (this) {
267 if (contextVersion == cv) {
268 currentSchemaContext.set(sc);
269 contextVersion = ver;
272 } while (version == ver);
278 public synchronized FluentFuture<YangTextSchemaSource> getSource(
279 final SourceIdentifier sourceIdentifier) {
280 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
282 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
284 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
285 + " not registered", sourceIdentifier));
288 return immediateFluentFuture(ret.iterator().next());
292 * Return the set of sources currently available in this resolved.
294 * @return An immutable point-in-time view of available sources.
296 public synchronized Set<SourceIdentifier> getAvailableSources() {
297 return ImmutableSet.copyOf(texts.keySet());
301 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
302 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
306 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
307 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
311 @SuppressWarnings("checkstyle:avoidHidingCauseException")
312 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
313 throws SchemaResolutionException {
314 final ListenableFuture<EffectiveModelContext> future = repository
315 .createEffectiveModelContextFactory(config(statementParserMode))
316 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
320 } catch (final InterruptedException e) {
321 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
322 } catch (final ExecutionException e) {
323 final Throwable cause = e.getCause();
324 if (cause instanceof SchemaResolutionException) {
325 throw (SchemaResolutionException) cause;
328 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
333 public void close() {
337 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
338 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();