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