Move YangTextSource
[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 java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Verify;
14 import com.google.common.collect.ArrayListMultimap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Multimap;
17 import com.google.common.util.concurrent.FluentFuture;
18 import java.io.IOException;
19 import java.net.URL;
20 import java.nio.charset.StandardCharsets;
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.source.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
42 import org.opendaylight.yangtools.yang.model.api.stmt.FeatureSet;
43 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
47 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
48 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
49 import org.opendaylight.yangtools.yang.model.repo.spi.GuavaSchemaSourceCache;
50 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
51 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
53 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
54 import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
55 import org.opendaylight.yangtools.yang.model.spi.source.URLYangTextSource;
56 import org.opendaylight.yangtools.yang.model.spi.source.YangIRSchemaSource;
57 import org.opendaylight.yangtools.yang.parser.api.YangParserFactory;
58 import org.opendaylight.yangtools.yang.parser.api.YangSyntaxErrorException;
59 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToIRTransformer;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSource> {
64     private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
65     private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
66
67     private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
68     private final Multimap<SourceIdentifier, YangTextSource> texts = ArrayListMultimap.create();
69     @GuardedBy("this")
70     private final Map<QNameModule, List<ImmutableSet<String>>> registeredFeatures = new HashMap<>();
71     private final AtomicReference<Optional<EffectiveModelContext>> currentSchemaContext =
72             new AtomicReference<>(Optional.empty());
73     private final GuavaSchemaSourceCache<YangIRSchemaSource> cache;
74     private final SchemaSourceRegistry registry;
75     private final SchemaRepository repository;
76     private final Registration transReg;
77
78     private volatile Object version = new Object();
79     private volatile Object contextVersion = version;
80     @GuardedBy("this")
81     private FeatureSet supportedFeatures = null;
82
83     private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
84         this.repository = requireNonNull(repository);
85         this.registry = requireNonNull(registry);
86
87         transReg = registry.registerSchemaSourceListener(TextToIRTransformer.create(repository, registry));
88         cache = GuavaSchemaSourceCache.createSoftCache(registry, YangIRSchemaSource.class, SOURCE_LIFETIME);
89     }
90
91     public static @NonNull YangTextSchemaContextResolver create(final String name) {
92         final var sharedRepo = new SharedSchemaRepository(name);
93         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
94     }
95
96     public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
97         final var sharedRepo = new SharedSchemaRepository(name, factory);
98         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
99     }
100
101     /**
102      * Register a {@link YangTextSource}.
103      *
104      * @param source YANG text source
105      * @return a {@link Registration}
106      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
107      * @throws IOException when the URL is not readable
108      * @throws SchemaSourceException When parsing encounters general error
109      * @throws NullPointerException if {@code source} is {@code null}
110      */
111     public @NonNull Registration registerSource(final @NonNull YangTextSource source)
112             throws SchemaSourceException, IOException, YangSyntaxErrorException {
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.sourceId();
119         final var parsedId = ast.sourceId();
120         final YangTextSource 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 = new DelegatedYangTextSource(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, YangTextSource.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 AbstractRegistration() {
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      * @throws NullPointerException if {@code url} is {@code null}
177      */
178     public @NonNull Registration registerSource(final @NonNull URL url)
179             throws SchemaSourceException, IOException, YangSyntaxErrorException {
180         final String path = url.getPath();
181         final String fileName = path.substring(path.lastIndexOf('/') + 1);
182         return registerSource(new URLYangTextSource(guessSourceIdentifier(fileName), url, StandardCharsets.UTF_8));
183     }
184
185     /**
186      * Register a {@link QNameModule} as a known module namespace with a set of supported features. Union of these
187      * registrations is forwarded to {@link FeatureSet} and this is then used in {@link #getEffectiveModelContext()} and
188      * related methods.
189      *
190      * @param module Module namespace
191      * @param features Features supported for that module namespace
192      * @return a {@link Registration}, use {@link Registration#close()} to revert the effects of this method
193      * @throws NullPointerException if any argument is {@code null}
194      */
195     public @NonNull Registration registerSupportedFeatures(final QNameModule module, final Set<String> features) {
196         final var checked = requireNonNull(module);
197         final var copy = ImmutableSet.copyOf(features);
198
199         synchronized (this) {
200             version = new Object();
201             supportedFeatures = null;
202             registeredFeatures.computeIfAbsent(module, ignored -> new ArrayList<>()).add(copy);
203         }
204         return new AbstractRegistration() {
205             @Override
206             protected void removeRegistration() {
207                 removeFeatures(checked, copy);
208             }
209         };
210     }
211
212     private synchronized void removeFeatures(final QNameModule module, final ImmutableSet<String> features) {
213         final var moduleFeatures = registeredFeatures.get(module);
214         if (moduleFeatures != null && moduleFeatures.remove(features)) {
215             if (moduleFeatures.isEmpty()) {
216                 registeredFeatures.remove(module);
217             }
218             supportedFeatures = null;
219             version = new Object();
220         }
221     }
222
223     private synchronized @Nullable FeatureSet getSupportedFeatures() {
224         var local = supportedFeatures;
225         if (local == null && !registeredFeatures.isEmpty()) {
226             final var builder = FeatureSet.builder();
227             for (var entry : registeredFeatures.entrySet()) {
228                 for (var features : entry.getValue()) {
229                     builder.addModuleFeatures(entry.getKey(), features);
230                 }
231             }
232             supportedFeatures = local = builder.build();
233         }
234         return local;
235     }
236
237     private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
238         try {
239             return SourceIdentifier.ofYangFileName(fileName);
240         } catch (IllegalArgumentException e) {
241             LOG.warn("Invalid file name format in '{}'", fileName, e);
242             return new SourceIdentifier(fileName);
243         }
244     }
245
246     /**
247      * Try to parse all currently available yang files and build new schema context.
248      *
249      * @return new schema context iif there is at least 1 yang file registered and
250      *         new schema context was successfully built.
251      */
252     public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
253         return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
254     }
255
256     /**
257      * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
258      *
259      * @param statementParserMode mode of statement parser
260      * @return new schema context iif there is at least 1 yang file registered and
261      *         new schema context was successfully built.
262      */
263     public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
264             final StatementParserMode statementParserMode) {
265         Optional<EffectiveModelContext> sc;
266         Object ver;
267         do {
268             // Spin get stable context version
269             Object cv;
270             do {
271                 cv = contextVersion;
272                 sc = currentSchemaContext.get();
273                 if (version == cv) {
274                     return sc;
275                 }
276             } while (cv != contextVersion);
277
278             // Version has been updated
279             Collection<SourceIdentifier> sources;
280             do {
281                 ver = version;
282                 sources = ImmutableSet.copyOf(requiredSources);
283             } while (ver != version);
284
285             final var factory = repository.createEffectiveModelContextFactory(
286                 config(statementParserMode, getSupportedFeatures()));
287
288             while (true) {
289                 final var f = factory.createEffectiveModelContext(sources);
290                 try {
291                     sc = Optional.of(f.get());
292                     break;
293                 } catch (InterruptedException e) {
294                     throw new IllegalStateException("Interrupted while assembling schema context", e);
295                 } catch (ExecutionException e) {
296                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
297                     final var cause = e.getCause();
298                     Verify.verify(cause instanceof SchemaResolutionException);
299                     sources = ((SchemaResolutionException) cause).getResolvedSources();
300                 }
301             }
302
303             LOG.debug("Resolved schema context for {}", sources);
304
305             synchronized (this) {
306                 if (contextVersion == cv) {
307                     currentSchemaContext.set(sc);
308                     contextVersion = ver;
309                 }
310             }
311         } while (version == ver);
312
313         return sc;
314     }
315
316     @Override
317     public synchronized @NonNull FluentFuture<YangTextSource> getSource(final SourceIdentifier sourceIdentifier) {
318         final var ret = texts.get(sourceIdentifier);
319
320         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
321         if (ret.isEmpty()) {
322             return FluentFutures.immediateFailedFluentFuture(
323                 new MissingSchemaSourceException(sourceIdentifier, "URL for " + sourceIdentifier + " not registered"));
324         }
325
326         return FluentFutures.immediateFluentFuture(ret.iterator().next());
327     }
328
329     /**
330      * Return the set of sources currently available in this resolved.
331      *
332      * @return An immutable point-in-time view of available sources.
333      */
334     public synchronized Set<SourceIdentifier> getAvailableSources() {
335         return ImmutableSet.copyOf(texts.keySet());
336     }
337
338     @Beta
339     public synchronized Collection<YangTextSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
340         return ImmutableSet.copyOf(texts.get(sourceIdentifier));
341     }
342
343     @Beta
344     public EffectiveModelContext trySchemaContext() throws SchemaResolutionException, ExecutionException {
345         return trySchemaContext(StatementParserMode.DEFAULT_MODE);
346     }
347
348     @Beta
349     @SuppressWarnings("checkstyle:avoidHidingCauseException")
350     public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
351             throws SchemaResolutionException, ExecutionException {
352         final var future = repository
353                 .createEffectiveModelContextFactory(config(statementParserMode, getSupportedFeatures()))
354                 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
355
356         try {
357             return future.get();
358         } catch (InterruptedException e) {
359             throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
360         } catch (ExecutionException e) {
361             if (e.getCause() instanceof SchemaResolutionException sre) {
362                 throw sre;
363             }
364             throw e;
365         }
366     }
367
368     @Override
369     public void close() {
370         transReg.close();
371     }
372
373     private static @NonNull SchemaContextFactoryConfiguration config(
374             final StatementParserMode statementParserMode, final @Nullable FeatureSet supportedFeatures) {
375         final var builder = SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode);
376         if (supportedFeatures != null) {
377             builder.setSupportedFeatures(supportedFeatures);
378         }
379         return builder.build();
380     }
381 }