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