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