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