Merge "BUG-997: Fix URLSchemaContextResolver"
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / URLSchemaContextResolver.java
1 /*
2  * Copyright (c) 2014 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
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.Objects.ToStringHelper;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.ArrayListMultimap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.Multimap;
19 import com.google.common.util.concurrent.CheckedFuture;
20 import com.google.common.util.concurrent.Futures;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URL;
25 import java.util.Collection;
26 import java.util.concurrent.ConcurrentLinkedDeque;
27 import java.util.concurrent.atomic.AtomicReference;
28
29 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
30 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
31 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
32 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
33 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
34 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
35 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
36 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
37 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
38 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
39 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
40 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource.Costs;
41 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration;
42 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
43 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
44 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
45 import org.opendaylight.yangtools.yang.model.repo.util.InMemorySchemaSourceCache;
46 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
47 import org.opendaylight.yangtools.yang.parser.util.TextToASTTransformer;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Beta
52 public class URLSchemaContextResolver implements AutoCloseable, SchemaSourceProvider<YangTextSchemaSource> {
53     private static final Logger LOG = LoggerFactory.getLogger(URLSchemaContextResolver.class);
54
55     private final Collection<SourceIdentifier> requiredSources = new ConcurrentLinkedDeque<>();
56     private final Multimap<SourceIdentifier, YangTextSchemaSource> texts = ArrayListMultimap.create();
57     private final AtomicReference<Optional<SchemaContext>> currentSchemaContext =
58             new AtomicReference<>(Optional.<SchemaContext>absent());
59     private final InMemorySchemaSourceCache<ASTSchemaSource> cache;
60     private final SchemaListenerRegistration transReg;
61     private final SchemaSourceRegistry registry;
62     private final SchemaRepository repository;
63     private volatile Object version = new Object();
64     private volatile Object contextVersion = version;
65
66
67     private URLSchemaContextResolver(final SchemaRepository repository, final SchemaSourceRegistry registry) {
68         this.repository = Preconditions.checkNotNull(repository);
69         this.registry = Preconditions.checkNotNull(registry);
70
71         final TextToASTTransformer t = TextToASTTransformer.create(repository, registry);
72         transReg = registry.registerSchemaSourceListener(t);
73
74         cache = InMemorySchemaSourceCache.createSoftCache(registry, ASTSchemaSource.class);
75     }
76
77     public static URLSchemaContextResolver create(final String name) {
78         final SharedSchemaRepository sharedRepo = new SharedSchemaRepository(name);
79         return new URLSchemaContextResolver(sharedRepo, sharedRepo);
80     }
81
82     /**
83      * Register a URL hosting a YANG Text file.
84      *
85      * @param url URL
86      * @throws YangSyntaxErrorException When the YANG file is syntactically invalid
87      * @throws IOException when the URL is not readable
88      * @throws SchemaSourceException When parsing encounters general error
89      */
90     public URLRegistration registerSource(final URL url) throws SchemaSourceException, IOException, YangSyntaxErrorException {
91         checkArgument(url != null, "Supplied URL must not be null");
92
93         final SourceIdentifier guessedId = new SourceIdentifier(url.getFile(), Optional.<String>absent());
94         final YangTextSchemaSource text = new YangTextSchemaSource(guessedId) {
95             @Override
96             public InputStream openStream() throws IOException {
97                 return url.openStream();
98             }
99
100             @Override
101             protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
102                 return toStringHelper.add("url", url);
103             }
104         };
105
106         final ASTSchemaSource ast = TextToASTTransformer.TRANSFORMATION.apply(text).checkedGet();
107         LOG.trace("Resolved URL {} to source {}", url, ast);
108
109         final SourceIdentifier resolvedId = ast.getIdentifier();
110
111         synchronized (this) {
112             texts.put(resolvedId, text);
113             LOG.debug("Populated {} with text", resolvedId);
114
115             final SchemaSourceRegistration<YangTextSchemaSource> reg = registry.registerSchemaSource(this,
116                 PotentialSchemaSource.create(resolvedId, YangTextSchemaSource.class, Costs.IMMEDIATE.getValue()));
117             requiredSources.add(resolvedId);
118             cache.schemaSourceEncountered(ast);
119             LOG.debug("Added source {} to schema context requirements", resolvedId);
120             version = new Object();
121
122             return new AbstractURLRegistration(text) {
123                 @Override
124                 protected void removeRegistration() {
125                     synchronized (URLSchemaContextResolver.this) {
126                         requiredSources.remove(resolvedId);
127                         LOG.trace("Removed source {} from schema context requirements", resolvedId);
128                         version = new Object();
129                         reg.close();
130                         texts.remove(resolvedId, text);
131                     }
132                 }
133             };
134         }
135     }
136
137     /**
138      * Try to parse all currently available yang files and build new schema context.
139      * @return new schema context iif there is at least 1 yang file registered and
140      *         new schema context was successfully built.
141      */
142     public Optional<SchemaContext> getSchemaContext() {
143         final SchemaContextFactory factory = repository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
144         Optional<SchemaContext> sc;
145         Object v;
146         do {
147             // Spin get stable context version
148             Object cv;
149             do {
150                 cv = contextVersion;
151                 sc = currentSchemaContext.get();
152                 if (version == cv) {
153                     return sc;
154                 }
155             } while (cv != contextVersion);
156
157             // Version has been updated
158             Collection<SourceIdentifier> sources;
159             do {
160                 v = version;
161                 sources = ImmutableSet.copyOf(requiredSources);
162             } while (v != version);
163
164             while (true) {
165                 final CheckedFuture<SchemaContext, SchemaResolutionException> f = factory.createSchemaContext(sources);
166                 try {
167                     sc = Optional.of(f.checkedGet());
168                     break;
169                 } catch (SchemaResolutionException e) {
170                     LOG.debug("Failed to fully assemble schema context for {}", sources, e);
171                     sources = e.getResolvedSources();
172                 }
173             }
174
175             LOG.debug("Resolved schema context for {}", sources);
176
177             synchronized (this) {
178                 if (contextVersion == cv) {
179                     currentSchemaContext.set(sc);
180                     contextVersion = v;
181                 }
182             }
183         } while (version == v);
184
185         return sc;
186     }
187
188     @Override
189     public synchronized CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
190         final Collection<YangTextSchemaSource> ret = texts.get(sourceIdentifier);
191
192         LOG.debug("Lookup {} result {}", sourceIdentifier, ret);
193         if (ret.isEmpty()) {
194             return Futures.<YangTextSchemaSource, SchemaSourceException>immediateFailedCheckedFuture(
195                     new MissingSchemaSourceException("URL for " + sourceIdentifier + " not registered", sourceIdentifier));
196         }
197
198         return Futures.immediateCheckedFuture(ret.iterator().next());
199     }
200
201     @Override
202     public void close() {
203         transReg.close();
204     }
205 }