bb6e4d40e3485afa24701a99e09bc101eaddfc77
[yangtools.git] / parser / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / YangTextSchemaContextResolver.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.repo;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Verify;
15 import com.google.common.collect.ArrayListMultimap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Multimap;
18 import com.google.common.util.concurrent.FluentFuture;
19 import java.io.IOException;
20 import java.net.URL;
21 import java.time.Duration;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.concurrent.ConcurrentLinkedDeque;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.atomic.AtomicReference;
32 import org.checkerframework.checker.lock.qual.GuardedBy;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.yangtools.concepts.AbstractRegistration;
36 import org.opendaylight.yangtools.concepts.Registration;
37 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureSet;
41 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
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.YangIRSchemaSource;
49 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
50 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
51 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
52 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
54 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
55 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
56 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
57 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
58 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
61
62 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
63     private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
64     private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
65
66     private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
67     private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
68     @GuardedBy("this")
69     private final Map<QNameModule, List<ImmutableSet<String>>> registeredFeatures = new HashMap<>();
70     private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
71             new AtomicReference<>(Optional.empty());
72     private final GuavaSchemaSourceCache<YangIRSchemaSource> cache;
73     private final SchemaListenerRegistration transReg;
74     private final SchemaSourceRegistry registry;
75     private final SchemaRepository repository;
76
77     private volatile Object version = new Object();
78     private volatile Object contextVersion = version;
79     @GuardedBy("this")
80     private FeatureSet supportedFeatures = null;
81
82     private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
83         this.repository = requireNonNull(repository);
84         this.registry = requireNonNull(registry);
85
86         transReg = registry.registerSchemaSourceListener(TextToIRTransformer.create(repository, registry));
87         cache = GuavaSchemaSourceCache.createSoftCache(registry, YangIRSchemaSource.class, SOURCE_LIFETIME);
88     }
89
90     public static @NonNull YangTextSchemaContextResolver create(final String name) {
91         final var sharedRepo = new SharedSchemaRepository(name);
92         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
93     }
94
95     public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
96         final var sharedRepo = new SharedSchemaRepository(name, factory);
97         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
98     }
99
100     /**
101      * Register a {@link YangTextSchemaSource}.
102      *
103      * @param source YANG text source
104      * @return a YangTextSchemaSourceRegistration
105      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
106      * @throws IOException when the URL is not readable
107      * @throws SchemaSourceException When parsing encounters general error
108      */
109     public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
110             throws SchemaSourceException, IOException, YangSyntaxErrorException {
111         checkArgument(source != null);
112
113         final var ast = TextToIRTransformer.transformText(source);
114         LOG.trace("Resolved source {} to source {}", source, ast);
115
116         // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
117         // does not, check how much it differs and emit a warning.
118         final var providedId = source.getIdentifier();
119         final var parsedId = ast.getIdentifier();
120         final YangTextSchemaSource text;
121         if (!parsedId.equals(providedId)) {
122             if (!parsedId.name().equals(providedId.name())) {
123                 LOG.info("Provided module name {} does not match actual text {}, corrected",
124                     providedId.toYangFilename(), parsedId.toYangFilename());
125             } else {
126                 final var sourceRev = providedId.revision();
127                 if (sourceRev != null) {
128                     if (!sourceRev.equals(parsedId.revision())) {
129                         LOG.info("Provided module revision {} does not match actual text {}, corrected",
130                             providedId.toYangFilename(), parsedId.toYangFilename());
131                     }
132                 } else {
133                     LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
134                 }
135             }
136
137             text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
138         } else {
139             text = source;
140         }
141
142         synchronized (this) {
143             texts.put(parsedId, text);
144             LOG.debug("Populated {} with text", parsedId);
145
146             final var 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();
152
153             return new AbstractYangTextSchemaSourceRegistration(text) {
154                 @Override
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();
160                         reg.close();
161                         texts.remove(parsedId, text);
162                     }
163                 }
164             };
165         }
166     }
167
168     /**
169      * Register a URL containing a YANG text.
170      *
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
176      */
177     public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
178             throws SchemaSourceException, IOException, YangSyntaxErrorException {
179         checkArgument(url != null, "Supplied URL must not be null");
180
181         final String path = url.getPath();
182         final String fileName = path.substring(path.lastIndexOf('/') + 1);
183         return registerSource(YangTextSchemaSource.forURL(url, guessSourceIdentifier(fileName)));
184     }
185
186     /**
187      * Register a {@link QNameModule} as a known module namespace with a set of supported features. Union of these
188      * registrations is forwarded to {@link FeatureSet} and this is then used in {@link #getEffectiveModelContext()} and
189      * related methods.
190      *
191      * @param module Module namespace
192      * @param features Features supported for that module namespace
193      * @return a {@link Registration}, use {@link Registration#close()} to revert the effects of this method
194      * @throws NullPointerException if any argument is {@code null}
195      */
196     public @NonNull Registration registerSupportedFeatures(final QNameModule module, final Set<String> features) {
197         final var checked = requireNonNull(module);
198         final var copy = ImmutableSet.copyOf(features);
199
200         synchronized (this) {
201             version = new Object();
202             supportedFeatures = null;
203             registeredFeatures.computeIfAbsent(module, ignored -> new ArrayList<>()).add(copy);
204         }
205         return new AbstractRegistration() {
206             @Override
207             protected void removeRegistration() {
208                 removeFeatures(checked, copy);
209             }
210         };
211     }
212
213     private synchronized void removeFeatures(final QNameModule module, final ImmutableSet<String> features) {
214         final var moduleFeatures = registeredFeatures.get(module);
215         if (moduleFeatures != null && moduleFeatures.remove(features)) {
216             if (moduleFeatures.isEmpty()) {
217                 registeredFeatures.remove(module);
218             }
219             supportedFeatures = null;
220             version = new Object();
221         }
222     }
223
224     private synchronized @Nullable FeatureSet getSupportedFeatures() {
225         var local = supportedFeatures;
226         if (local == null && !registeredFeatures.isEmpty()) {
227             final var builder = FeatureSet.builder();
228             for (var entry : registeredFeatures.entrySet()) {
229                 for (var features : entry.getValue()) {
230                     builder.addModuleFeatures(entry.getKey(), features);
231                 }
232             }
233             supportedFeatures = local = builder.build();
234         }
235         return local;
236     }
237
238     private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
239         try {
240             return YangTextSchemaSource.identifierFromFilename(fileName);
241         } catch (IllegalArgumentException e) {
242             LOG.warn("Invalid file name format in '{}'", fileName, e);
243             return new SourceIdentifier(fileName);
244         }
245     }
246
247     /**
248      * Try to parse all currently available yang files and build new schema context.
249      *
250      * @return new schema context iif there is at least 1 yang file registered and
251      *         new schema context was successfully built.
252      */
253     public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
254         return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
255     }
256
257     /**
258      * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
259      *
260      * @param statementParserMode mode of statement parser
261      * @return new schema context iif there is at least 1 yang file registered and
262      *         new schema context was successfully built.
263      */
264     public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
265             final StatementParserMode statementParserMode) {
266         Optional<EffectiveModelContext> sc;
267         Object ver;
268         do {
269             // Spin get stable context version
270             Object cv;
271             do {
272                 cv = contextVersion;
273                 sc = currentSchemaContext.get();
274                 if (version == cv) {
275                     return sc;
276                 }
277             } while (cv != contextVersion);
278
279             // Version has been updated
280             Collection<SourceIdentifier> sources;
281             do {
282                 ver = version;
283                 sources = ImmutableSet.copyOf(requiredSources);
284             } while (ver != version);
285
286             final var factory = repository.createEffectiveModelContextFactory(
287                 config(statementParserMode, getSupportedFeatures()));
288
289             while (true) {
290                 final var f = factory.createEffectiveModelContext(sources);
291                 try {
292                     sc = Optional.of(f.get());
293                     break;
294                 } catch (InterruptedException e) {
295                     throw new IllegalStateException("Interrupted while assembling schema context", e);
296                 } catch (ExecutionException e) {
297                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
298                     final var cause = e.getCause();
299                     Verify.verify(cause instanceof SchemaResolutionException);
300                     sources = ((SchemaResolutionException) cause).getResolvedSources();
301                 }
302             }
303
304             LOG.debug("Resolved schema context for {}", sources);
305
306             synchronized (this) {
307                 if (contextVersion == cv) {
308                     currentSchemaContext.set(sc);
309                     contextVersion = ver;
310                 }
311             }
312         } while (version == ver);
313
314         return sc;
315     }
316
317     @Override
318     public synchronized @NonNull FluentFuture<YangTextSchemaSource> getSource(
319             final SourceIdentifier sourceIdentifier) {
320         final var ret = texts.get(sourceIdentifier);
321
322         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
323         if (ret.isEmpty()) {
324             return FluentFutures.immediateFailedFluentFuture(
325                 new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
326         }
327
328         return FluentFutures.immediateFluentFuture(ret.iterator().next());
329     }
330
331     /**
332      * Return the set of sources currently available in this resolved.
333      *
334      * @return An immutable point-in-time view of available sources.
335      */
336     public synchronized Set<SourceIdentifier> getAvailableSources() {
337         return ImmutableSet.copyOf(texts.keySet());
338     }
339
340     @Beta
341     public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
342         return ImmutableSet.copyOf(texts.get(sourceIdentifier));
343     }
344
345     @Beta
346     public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
347         return trySchemaContext(StatementParserMode.DEFAULT_MODE);
348     }
349
350     @Beta
351     @SuppressWarnings("checkstyle:avoidHidingCauseException")
352     public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
353             throws SchemaResolutionException {
354         final var future = repository
355                 .createEffectiveModelContextFactory(config(statementParserMode, getSupportedFeatures()))
356                 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
357
358         try {
359             return future.get();
360         } catch (InterruptedException e) {
361             throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
362         } catch (ExecutionException e) {
363             final var cause = e.getCause();
364             if (cause instanceof SchemaResolutionException resolutionException) {
365                 throw resolutionException;
366             }
367             throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
368         }
369     }
370
371     @Override
372     public void close() {
373         transReg.close();
374     }
375
376     private static @NonNull SchemaContextFactoryConfiguration config(
377             final StatementParserMode statementParserMode, final @Nullable FeatureSet supportedFeatures) {
378         final var builder = SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode);
379         if (supportedFeatures != null) {
380             builder.setSupportedFeatures(supportedFeatures);
381         }
382         return builder.build();
383     }
384 }