Bug 4662: Introduce a SemanticVersion concept - SchemaContextFactory
[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 org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
13
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Optional;
16 import com.google.common.base.Preconditions;
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.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URL;
25 import java.util.Collection;
26 import java.util.Set;
27 import java.util.concurrent.ConcurrentLinkedDeque;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicReference;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
32 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
33 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
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.TRANSFORMATION.apply(source).checkedGet();
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", providedId.toYangFilename(),
109                     parsedId.toYangFilename());
110             } else {
111                 final String sourceRev = providedId.getRevision();
112                 final String astRev = parsedId.getRevision();
113                 if (sourceRev != null) {
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, 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(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, statementParserMode);
221                 try {
222                     sc = Optional.of(f.checkedGet());
223                     break;
224                 } catch (SchemaResolutionException e) {
225                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
226                     sources = e.getResolvedSources();
227                 }
228             }
229
230             LOG.debug("Resolved schema context for {}", sources);
231
232             synchronized (this) {
233                 if (contextVersion == cv) {
234                     currentSchemaContext.set(sc);
235                     contextVersion = v;
236                 }
237             }
238         } while (version == v);
239
240         return sc;
241     }
242
243     @Override
244     public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
245         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
246
247         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
248         if (ret.isEmpty()) {
249             return Futures.immediateFailedCheckedFuture(
250                     new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
251         }
252
253         return Futures.immediateCheckedFuture(ret.iterator().next());
254     }
255
256     /**
257      * Return the set of sources currently available in this resolved.
258      *
259      * @return An immutable point-in-time view of available sources.
260      */
261     public synchronized Set<SourceIdentifier> getAvailableSources() {
262         return ImmutableSet.copyOf(texts.keySet());
263     }
264
265     @Override
266     public void close() {
267         transReg.close();
268     }
269 }