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