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.util.Collection;
25 import java.util.Optional;
27 import java.util.concurrent.ConcurrentLinkedDeque;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeUnit;
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.PotentialSchemaSource;
47 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
48 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
52 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
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 long SOURCE_LIFETIME_SECONDS = 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 InMemorySchemaSourceCache<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 = InMemorySchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME_SECONDS,
84 public static @NonNull YangTextSchemaContextResolver create(final String name) {
85 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
86 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
89 public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
90 final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
91 return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
95 * Register a {@link YangTextSchemaSource}.
97 * @param source YANG text source
98 * @return a YangTextSchemaSourceRegistration
99 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
100 * @throws IOException when the URL is not readable
101 * @throws SchemaSourceException When parsing encounters general error
103 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
104 throws SchemaSourceException, IOException, YangSyntaxErrorException {
105 checkArgument(source != null);
107 final IRSchemaSource ast = TextToIRTransformer.transformText(source);
108 LOG.trace("Resolved source {} to source {}", source, ast);
110 // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
111 // does not, check how much it differs and emit a warning.
112 final SourceIdentifier providedId = source.getIdentifier();
113 final SourceIdentifier parsedId = ast.getIdentifier();
114 final YangTextSchemaSource text;
115 if (!parsedId.equals(providedId)) {
116 if (!parsedId.getName().equals(providedId.getName())) {
117 LOG.info("Provided module name {} does not match actual text {}, corrected",
118 providedId.toYangFilename(), parsedId.toYangFilename());
120 final Optional<Revision> sourceRev = providedId.getRevision();
121 final Optional<Revision> astRev = parsedId.getRevision();
122 if (sourceRev.isPresent()) {
123 if (!sourceRev.equals(astRev)) {
124 LOG.info("Provided module revision {} does not match actual text {}, corrected",
125 providedId.toYangFilename(), parsedId.toYangFilename());
128 LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
132 text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
137 synchronized (this) {
138 texts.put(parsedId, text);
139 LOG.debug("Populated {} with text", parsedId);
141 final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
142 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
143 requiredSources.add(parsedId);
144 cache.schemaSourceEncountered(ast);
145 LOG.debug("Added source {} to schema context requirements", parsedId);
146 version = new Object();
148 return new AbstractYangTextSchemaSourceRegistration(text) {
150 protected void removeRegistration() {
151 synchronized (YangTextSchemaContextResolver.this) {
152 requiredSources.remove(parsedId);
153 LOG.trace("Removed source {} from schema context requirements", parsedId);
154 version = new Object();
156 texts.remove(parsedId, text);
164 * Register a URL containing a YANG text.
166 * @param url YANG text source URL
167 * @return a YangTextSchemaSourceRegistration for this URL
168 * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
169 * @throws IOException when the URL is not readable
170 * @throws SchemaSourceException When parsing encounters general error
172 public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
173 throws SchemaSourceException, IOException, YangSyntaxErrorException {
174 checkArgument(url != null, "Supplied URL must not be null");
176 final String path = url.getPath();
177 final String fileName = path.substring(path.lastIndexOf('/') + 1);
178 return registerSource(YangTextSchemaSource.forURL(url, guessSourceIdentifier(fileName)));
181 private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
183 return YangTextSchemaSource.identifierFromFilename(fileName);
184 } catch (final IllegalArgumentException e) {
185 LOG.warn("Invalid file name format in '{}'", fileName, e);
186 return RevisionSourceIdentifier.create(fileName);
191 * Try to parse all currently available yang files and build new schema context.
193 * @return new schema context iif there is at least 1 yang file registered and
194 * new schema context was successfully built.
196 public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
197 return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
201 * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
203 * @param statementParserMode mode of statement parser
204 * @return new schema context iif there is at least 1 yang file registered and
205 * new schema context was successfully built.
207 public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
208 final StatementParserMode statementParserMode) {
209 final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
210 config(statementParserMode));
211 Optional<EffectiveModelContext> sc;
214 // Spin get stable context version
218 sc = currentSchemaContext.get();
222 } while (cv != contextVersion);
224 // Version has been updated
225 Collection<SourceIdentifier> sources;
228 sources = ImmutableSet.copyOf(requiredSources);
229 } while (ver != version);
232 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
234 sc = Optional.of(f.get());
236 } catch (final InterruptedException e) {
237 throw new IllegalStateException("Interrupted while assembling schema context", e);
238 } catch (final ExecutionException e) {
239 LOG.info("Failed to fully assemble schema context for {}", sources, e);
240 final Throwable cause = e.getCause();
241 Verify.verify(cause instanceof SchemaResolutionException);
242 sources = ((SchemaResolutionException) cause).getResolvedSources();
246 LOG.debug("Resolved schema context for {}", sources);
248 synchronized (this) {
249 if (contextVersion == cv) {
250 currentSchemaContext.set(sc);
251 contextVersion = ver;
254 } while (version == ver);
260 public synchronized @NonNull FluentFuture<YangTextSchemaSource> getSource(
261 final SourceIdentifier sourceIdentifier) {
262 final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
264 LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
266 return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
267 + " not registered", sourceIdentifier));
270 return immediateFluentFuture(ret.iterator().next());
274 * Return the set of sources currently available in this resolved.
276 * @return An immutable point-in-time view of available sources.
278 public synchronized Set<SourceIdentifier> getAvailableSources() {
279 return ImmutableSet.copyOf(texts.keySet());
283 public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
284 return ImmutableSet.copyOf(texts.get(sourceIdentifier));
288 public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
289 return trySchemaContext(StatementParserMode.DEFAULT_MODE);
293 @SuppressWarnings("checkstyle:avoidHidingCauseException")
294 public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
295 throws SchemaResolutionException {
296 final ListenableFuture<EffectiveModelContext> future = repository
297 .createEffectiveModelContextFactory(config(statementParserMode))
298 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
302 } catch (final InterruptedException e) {
303 throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
304 } catch (final ExecutionException e) {
305 final Throwable cause = e.getCause();
306 if (cause instanceof SchemaResolutionException) {
307 throw (SchemaResolutionException) cause;
310 throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
315 public void close() {
319 private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
320 return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();