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