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