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