218c8dd48a49ab2244f34c336643523ca8028d4d
[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             protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
188                 return toStringHelper.add("url", url);
189             }
190         });
191     }
192
193     private static SourceIdentifier guessSourceIdentifier(final @NonNull String fileName) {
194         try {
195             return YangTextSchemaSource.identifierFromFilename(fileName);
196         } catch (final IllegalArgumentException e) {
197             LOG.warn("Invalid file name format in '{}'", fileName, e);
198             return RevisionSourceIdentifier.create(fileName);
199         }
200     }
201
202     /**
203      * Try to parse all currently available yang files and build new schema context.
204      *
205      * @return new schema context iif there is at least 1 yang file registered and
206      *         new schema context was successfully built.
207      */
208     public Optional<? extends EffectiveModelContext> getEffectiveModelContext() {
209         return getEffectiveModelContext(StatementParserMode.DEFAULT_MODE);
210     }
211
212     /**
213      * Try to parse all currently available yang files and build new schema context depending on specified parsing mode.
214      *
215      * @param statementParserMode mode of statement parser
216      * @return new schema context iif there is at least 1 yang file registered and
217      *         new schema context was successfully built.
218      */
219     public Optional<? extends EffectiveModelContext> getEffectiveModelContext(
220             final StatementParserMode statementParserMode) {
221         final EffectiveModelContextFactory factory = repository.createEffectiveModelContextFactory(
222             config(statementParserMode));
223         Optional<EffectiveModelContext> sc;
224         Object ver;
225         do {
226             // Spin get stable context version
227             Object cv;
228             do {
229                 cv = contextVersion;
230                 sc = currentSchemaContext.get();
231                 if (version == cv) {
232                     return sc;
233                 }
234             } while (cv != contextVersion);
235
236             // Version has been updated
237             Collection<SourceIdentifier> sources;
238             do {
239                 ver = version;
240                 sources = ImmutableSet.copyOf(requiredSources);
241             } while (ver != version);
242
243             while (true) {
244                 final ListenableFuture<EffectiveModelContext> f = factory.createEffectiveModelContext(sources);
245                 try {
246                     sc = Optional.of(f.get());
247                     break;
248                 } catch (final InterruptedException e) {
249                     throw new IllegalStateException("Interrupted while assembling schema context", e);
250                 } catch (final ExecutionException e) {
251                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
252                     final Throwable cause = e.getCause();
253                     Verify.verify(cause instanceof SchemaResolutionException);
254                     sources = ((SchemaResolutionException) cause).getResolvedSources();
255                 }
256             }
257
258             LOG.debug("Resolved schema context for {}", sources);
259
260             synchronized (this) {
261                 if (contextVersion == cv) {
262                     currentSchemaContext.set(sc);
263                     contextVersion = ver;
264                 }
265             }
266         } while (version == ver);
267
268         return sc;
269     }
270
271     @Override
272     public synchronized FluentFuture<YangTextSchemaSource> getSource(
273             final SourceIdentifier sourceIdentifier) {
274         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
275
276         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
277         if (ret.isEmpty()) {
278             return immediateFailedFluentFuture(new MissingSchemaSourceException("URL for " + sourceIdentifier
279                 + " not registered", sourceIdentifier));
280         }
281
282         return immediateFluentFuture(ret.iterator().next());
283     }
284
285     /**
286      * Return the set of sources currently available in this resolved.
287      *
288      * @return An immutable point-in-time view of available sources.
289      */
290     public synchronized Set<SourceIdentifier> getAvailableSources() {
291         return ImmutableSet.copyOf(texts.keySet());
292     }
293
294     @Beta
295     public synchronized Collection<YangTextSchemaSource> getSourceTexts(final SourceIdentifier sourceIdentifier) {
296         return ImmutableSet.copyOf(texts.get(sourceIdentifier));
297     }
298
299     @Beta
300     public EffectiveModelContext trySchemaContext() throws SchemaResolutionException {
301         return trySchemaContext(StatementParserMode.DEFAULT_MODE);
302     }
303
304     @Beta
305     @SuppressWarnings("checkstyle:avoidHidingCauseException")
306     public EffectiveModelContext trySchemaContext(final StatementParserMode statementParserMode)
307             throws SchemaResolutionException {
308         final ListenableFuture<EffectiveModelContext> future = repository
309                 .createEffectiveModelContextFactory(config(statementParserMode))
310                 .createEffectiveModelContext(ImmutableSet.copyOf(requiredSources));
311
312         try {
313             return future.get();
314         } catch (final InterruptedException e) {
315             throw new IllegalStateException("Interrupted while waiting for SchemaContext assembly", e);
316         } catch (final ExecutionException e) {
317             final Throwable cause = e.getCause();
318             if (cause instanceof SchemaResolutionException) {
319                 throw (SchemaResolutionException) cause;
320             }
321
322             throw new SchemaResolutionException("Failed to assemble SchemaContext", e);
323         }
324     }
325
326     @Override
327     public void close() {
328         transReg.close();
329     }
330
331     private static SchemaContextFactoryConfiguration config(final StatementParserMode statementParserMode) {
332         return SchemaContextFactoryConfiguration.builder().setStatementParserMode(statementParserMode).build();
333     }
334 }