Drop unneeded generic type specifiers
[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 com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ArrayListMultimap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Multimap;
17 import com.google.common.util.concurrent.CheckedFuture;
18 import com.google.common.util.concurrent.Futures;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.URL;
22 import java.util.Collection;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentLinkedDeque;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.atomic.AtomicReference;
27 import javax.annotation.Nonnull;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
30 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
31 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
38 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
39 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
40 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
42 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
44 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
45 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
46 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 public final class YangTextSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
51     private static final Logger LOG = LoggerFactory.getLogger(YangTextSchemaContextResolver.class);
52     private static final long SOURCE_LIFETIME_SECONDS = 60;
53
54     private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
55     private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
56     private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
57             new AtomicReference<>(Optional.absent());
58     private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
59     private final SchemaListenerRegistration transReg;
60     private final SchemaSourceRegistry registry;
61     private final SchemaRepository repository;
62     private volatile Object version = new Object();
63     private volatile Object contextVersion = version;
64
65     private YangTextSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
66         this.repository = Preconditions.checkNotNull(repository);
67         this.registry = Preconditions.checkNotNull(registry);
68
69         final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
70         transReg = registry.registerSchemaSourceListener(t);
71
72         cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class, SOURCE_LIFETIME_SECONDS,
73             TimeUnit.SECONDS);
74     }
75
76     public static YangTextSchemaContextResolver create(final String name) {
77         final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
78         return new YangTextSchemaContextResolver(sharedRepo, sharedRepo);
79     }
80
81     /**
82      * Register a {@link YangTextSchemaSource}.
83      *
84      * @param source YANG text source
85      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
86      * @throws IOException when the URL is not readable
87      * @throws SchemaSourceException When parsing encounters general error
88      * @return a YangTextSchemaSourceRegistration
89      */
90     public YangTextSchemaSourceRegistration registerSource(@Nonnull final YangTextSchemaSource source)
91             throws SchemaSourceException, IOException, YangSyntaxErrorException {
92         checkArgument(source != null);
93
94         final ASTSchemaSource ast = TextToASTTransformer.TRANSFORMATION.apply(source).checkedGet();
95         LOG.trace("Resolved source {} to source {}", source, ast);
96
97         // AST carries an accurate identifier, check if it matches the one supplied by the source. If it
98         // does not, check how much it differs and emit a warning.
99         final SourceIdentifier providedId = source.getIdentifier();
100         final SourceIdentifier parsedId = ast.getIdentifier();
101         final YangTextSchemaSource text;
102         if (!parsedId.equals(providedId)) {
103             if (!parsedId.getName().equals(providedId.getName())) {
104                 LOG.info("Provided module name {} does not match actual text {}, corrected", providedId.toYangFilename(),
105                     parsedId.toYangFilename());
106             } else {
107                 final String sourceRev = providedId.getRevision();
108                 final String astRev = parsedId.getRevision();
109                 if (sourceRev != null) {
110                     if (!sourceRev.equals(astRev)) {
111                         LOG.info("Provided module revision {} does not match actual text {}, corrected",
112                             providedId.toYangFilename(), parsedId.toYangFilename());
113                     }
114                 } else {
115                     LOG.debug("Expanded module {} to {}", providedId.toYangFilename(), parsedId.toYangFilename());
116                 }
117             }
118
119             text = YangTextSchemaSource.delegateForByteSource(parsedId, source);
120         } else {
121             text = source;
122         }
123
124         synchronized (this) {
125             texts.put(parsedId, text);
126             LOG.debug("Populated {} with text", parsedId);
127
128             final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
129                 PotentialSchemaSource.create(parsedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
130             requiredSources.add(parsedId);
131             cache.schemaSourceEncountered(ast);
132             LOG.debug("Added source {} to schema context requirements", parsedId);
133             version = new Object();
134
135             return new AbstractYangTextSchemaSourceRegistration(text) {
136                 @Override
137                 protected void removeRegistration() {
138                     synchronized (YangTextSchemaContextResolver.this) {
139                         requiredSources.remove(parsedId);
140                         LOG.trace("Removed source {} from schema context requirements", parsedId);
141                         version = new Object();
142                         reg.close();
143                         texts.remove(parsedId, text);
144                     }
145                 }
146             };
147         }
148     }
149
150     /**
151      * Register a URL containing a YANG text.
152      *
153      * @param url YANG text source URL
154      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
155      * @throws IOException when the URL is not readable
156      * @throws SchemaSourceException When parsing encounters general error
157      * @return a YangTextSchemaSourceRegistration for this URL
158      */
159     public YangTextSchemaSourceRegistration registerSource(@Nonnull final URL url) throws SchemaSourceException, IOException, YangSyntaxErrorException {
160         checkArgument(url != null, "Supplied URL must not be null");
161
162         final SourceIdentifier guessedId = new SourceIdentifier(url.getFile(), Optional.absent());
163         return registerSource(new YangTextSchemaSource(guessedId) {
164             @Override
165             public InputStream openStream() throws IOException {
166                 return url.openStream();
167             }
168
169             @Override
170             protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
171                 return toStringHelper.add("url", url);
172             }
173         });
174     }
175
176     /**
177      * Try to parse all currently available yang files and build new schema context.
178      * @return new schema context iif there is at least 1 yang file registered and
179      *         new schema context was successfully built.
180      */
181     public Optional<SchemaContext> getSchemaContext() {
182         final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
183         Optional<SchemaContext> sc;
184         Object v;
185         do {
186             // Spin get stable context version
187             Object cv;
188             do {
189                 cv = contextVersion;
190                 sc = currentSchemaContext.get();
191                 if (version == cv) {
192                     return sc;
193                 }
194             } while (cv != contextVersion);
195
196             // Version has been updated
197             Collection<SourceIdentifier> sources;
198             do {
199                 v = version;
200                 sources = ImmutableSet.copyOf(requiredSources);
201             } while (v != version);
202
203             while (true) {
204                 final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory.createSchemaContext(sources);
205                 try {
206                     sc = Optional.of(f.checkedGet());
207                     break;
208                 } catch (SchemaResolutionException e) {
209                     LOG.info("Failed to fully assemble schema context for {}", sources, e);
210                     sources = e.getResolvedSources();
211                 }
212             }
213
214             LOG.debug("Resolved schema context for {}", sources);
215
216             synchronized (this) {
217                 if (contextVersion == cv) {
218                     currentSchemaContext.set(sc);
219                     contextVersion = v;
220                 }
221             }
222         } while (version == v);
223
224         return sc;
225     }
226
227     @Override
228     public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
229         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
230
231         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
232         if (ret.isEmpty()) {
233             return Futures.immediateFailedCheckedFuture(
234                     new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
235         }
236
237         return Futures.immediateCheckedFuture(ret.iterator().next());
238     }
239
240     /**
241      * Return the set of sources currently available in this resolved.
242      *
243      * @return An immutable point-in-time view of available sources.
244      */
245     public synchronized Set<SourceIdentifier> getAvailableSources() {
246         return ImmutableSet.copyOf(texts.keySet());
247     }
248
249     @Override
250     public void close() {
251         transReg.close();
252     }
253 }