Do not subclass YangTextSchemaSource in yang-parser-impl
[yangtools.git] / yang / 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 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
13 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
14
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;
23 import java.net.URL;
24 import java.time.Duration;
25 import java.util.Collection;
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.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.GuavaSchemaSourceCache;
47 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
48 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
49 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
50 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
51 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
52 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
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;
57
58 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
59     private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
60     private static final Duration SOURCE_LIFETIME = Duration.ofSeconds(60);
61
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 GuavaSchemaSourceCache<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;
72
73     private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
74         this.repository = requireNonNull(repository);
75         this.registry = requireNonNull(registry);
76
77         final TextToIRTransformer t = TextToIRTransformer.create(repository, registry);
78         transReg = registry.registerSchemaSourceListener(t);
79
80         cache = GuavaSchemaSourceCache.createSoftCache(registry, IRSchemaSource.class, SOURCE_LIFETIME);
81     }
82
83     public static @NonNull YangTextSchemaContextResolver create(final String name) {
84         final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
85         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
86     }
87
88     public static @NonNull YangTextSchemaContextResolver create(final String name, final YangParserFactory factory) {
89         final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name, factory);
90         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
91     }
92
93     /**
94      * Register a {@link YangTextSchemaSource}.
95      *
96      * @param source YANG text source
97      * @return a YangTextSchemaSourceRegistration
98      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
99      * @throws IOException when the URL is not readable
100      * @throws SchemaSourceException When parsing encounters general error
101      */
102     public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull YangTextSchemaSource source)
103             throws SchemaSourceException, IOException, YangSyntaxErrorException {
104         checkArgument(source != null);
105
106         final IRSchemaSource ast = TextToIRTransformer.transformText(source);
107         LOG.trace("Resolved source {} to source {}", source, ast);
108
109         // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
110         // does not, check how much it differs and emit a warning.
111         final SourceIdentifier providedId = source.getIdentifier();
112         final SourceIdentifier parsedId = ast.getIdentifier();
113         final YangTextSchemaSource text;
114         if (!parsedId.equals(providedId)) {
115             if (!parsedId.getName().equals(providedId.getName())) {
116                 LOG.info("Provided module name {} does not match actual text {}, corrected",
117                     providedId.toYangFilename(), parsedId.toYangFilename());
118             } else {
119                 final Optional<Revision> sourceRev = providedId.getRevision();
120                 final Optional<Revision> astRev = parsedId.getRevision();
121                 if (sourceRev.isPresent()) {
122                     if (!sourceRev.equals(astRev)) {
123                         LOG.info("Provided module revision {} does not match actual text {}, corrected",
124                             providedId.toYangFilename(), parsedId.toYangFilename());
125                     }
126                 } else {
127                     LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
128                 }
129             }
130
131             text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
132         } else {
133             text = source;
134         }
135
136         synchronized (this) {
137             texts.put(parsedId, text);
138             LOG.debug("Populated {} with text", parsedId);
139
140             final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
141                 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
142             requiredSources.add(parsedId);
143             cache.schemaSourceEncountered(ast);
144             LOG.debug("Added source {} to schema context requirements", parsedId);
145             version = new Object();
146
147             return new AbstractYangTextSchemaSourceRegistration(text) {
148                 @Override
149                 protected void removeRegistration() {
150                     synchronized (YangTextSchemaContextResolver.this) {
151                         requiredSources.remove(parsedId);
152                         LOG.trace("Removed source {} from schema context requirements", parsedId);
153                         version = new Object();
154                         reg.close();
155                         texts.remove(parsedId, text);
156                     }
157                 }
158             };
159         }
160     }
161
162     /**
163      * Register a URL containing a YANG text.
164      *
165      * @param url YANG text source URL
166      * @return a YangTextSchemaSourceRegistration for this URL
167      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
168      * @throws IOException when the URL is not readable
169      * @throws SchemaSourceException When parsing encounters general error
170      */
171     public @NonNull YangTextSchemaSourceRegistration registerSource(final @NonNull URL url)
172             throws SchemaSourceException, IOException, YangSyntaxErrorException {
173         checkArgument(url != null, "Supplied URL must not be null");
174
175         final String path = url.getPath();
176         final String fileName = path.substring(path.lastIndexOf('/') + 1);
177         return registerSource(YangTextSchemaSource.forURL(url, guessSourceIdentifier(fileName)));
178     }
179
180     private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
181         try {
182             return YangTextSchemaSource.identifierFromFilename(fileName);
183         } catch (final IllegalArgumentException e) {
184             LOG.warn("Invalid file name format in '{}'", fileName, e);
185             return RevisionSourceIdentifier.create(fileName);
186         }
187     }
188
189     /**
190      * Try to parse all currently available yang files and build new schema context.
191      *
192      * @return new schema context iif there is at least 1 yang file registered and
193      *         new schema context was successfully built.
194      */
195     public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
196         return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
197     }
198
199     /**
200      * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
201      *
202      * @param statementParserMode mode of statement parser
203      * @return new schema context iif there is at least 1 yang file registered and
204      *         new schema context was successfully built.
205      */
206     public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
207             final StatementParserMode statementParserMode) {
208         final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
209             config(statementParserMode));
210         Optional<EffectiveModelContext> sc;
211         Object ver;
212         do {
213             // Spin get stable context version
214             Object cv;
215             do {
216                 cv = contextVersion;
217                 sc = currentSchemaContext.get();
218                 if (version == cv) {
219                     return sc;
220                 }
221             } while (cv != contextVersion);
222
223             // Version has been updated
224             Collection<SourceIdentifier> sources;
225             do {
226                 ver = version;
227                 sources = ImmutableSet.copyOf(requiredSources);
228             } while (ver != version);
229
230             while (true) {
231                 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
232                 try {
233                     sc = Optional.of(f.get());
234                     break;
235                 } catch (final InterruptedException e) {
236                     throw new IllegalStateException("Interrupted while assembling schema context", e);
237                 } catch (final ExecutionException e) {
238                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
239                     final Throwable cause = e.getCause();
240                     Verify.verify(cause instanceof SchemaResolutionException);
241                     sources = ((SchemaResolutionException) cause).getResolvedSources();
242                 }
243             }
244
245             LOG.debug("Resolved schema context for {}", sources);
246
247             synchronized (this) {
248                 if (contextVersion == cv) {
249                     currentSchemaContext.set(sc);
250                     contextVersion = ver;
251                 }
252             }
253         } while (version == ver);
254
255         return sc;
256     }
257
258     @Override
259     public synchronized @NonNull FluentFuture<YangTextSchemaSource> getSource(
260             final SourceIdentifier sourceIdentifier) {
261         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
262
263         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
264         if (ret.isEmpty()) {
265             return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
266                 + " not registered", sourceIdentifier));
267         }
268
269         return immediateFluentFuture(ret.iterator().next());
270     }
271
272     /**
273      * Return the set of sources currently available in this resolved.
274      *
275      * @return An immutable point-in-time view of available sources.
276      */
277     public synchronized Set<SourceIdentifier> getAvailableSources() {
278         return ImmutableSet.copyOf(texts.keySet());
279     }
280
281     @Beta
282     public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
283         return ImmutableSet.copyOf(texts.get(sourceIdentifier));
284     }
285
286     @Beta
287     public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
288         return trySchemaContext(StatementParserMode.DEFAULT_MODE);
289     }
290
291     @Beta
292     @SuppressWarnings("checkstyle:avoidHidingCauseException")
293     public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
294             throws SchemaResolutionException {
295         final ListenableFuture<EffectiveModelContext> future = repository
296                 .createEffectiveModelContextFactory(config(statementParserMode))
297                 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
298
299         try {
300             return future.get();
301         } catch (final InterruptedException e) {
302             throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
303         } catch (final ExecutionException e) {
304             final Throwable cause = e.getCause();
305             if (cause instanceof SchemaResolutionException) {
306                 throw (SchemaResolutionException) cause;
307             }
308
309             throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
310         }
311     }
312
313     @Override
314     public void close() {
315         transReg.close();
316     }
317
318     private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
319         return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();
320     }
321 }