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