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