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