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