Inject YangParserFactory into SharedSchemaRepository
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / SharedSchemaContextFactory.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 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
13
14 import com.google.common.base.Function;
15 import com.google.common.cache.Cache;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.collect.Collections2;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Maps;
21 import com.google.common.util.concurrent.AsyncFunction;
22 import com.google.common.util.concurrent.FluentFuture;
23 import com.google.common.util.concurrent.FutureCallback;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import com.google.common.util.concurrent.MoreExecutors;
27 import com.google.common.util.concurrent.SettableFuture;
28 import java.io.IOException;
29 import java.util.Collection;
30 import java.util.LinkedHashMap;
31 import java.util.LinkedHashSet;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.Set;
36 import java.util.concurrent.ExecutionException;
37 import org.antlr.v4.runtime.ParserRuleContext;
38 import org.eclipse.jdt.annotation.NonNull;
39 import org.gaul.modernizer_maven_annotations.SuppressModernizer;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
41 import org.opendaylight.yangtools.yang.model.parser.api.YangParser;
42 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
43 import org.opendaylight.yangtools.yang.model.parser.api.YangParserFactory;
44 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
45 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
47 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
48 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
49 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
50 import org.opendaylight.yangtools.yang.parser.antlr.YangStatementParser.StatementContext;
51 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
52 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 final class SharedSchemaContextFactory implements EffectiveModelContextFactory {
58     private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
59
60     private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> revisionCache = CacheBuilder.newBuilder()
61             .weakValues().build();
62     private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> semVerCache = CacheBuilder.newBuilder()
63             .weakValues().build();
64     private final @NonNull SharedSchemaRepository repository;
65     private final @NonNull SchemaContextFactoryConfiguration config;
66
67     SharedSchemaContextFactory(final @NonNull SharedSchemaRepository repository,
68             final @NonNull SchemaContextFactoryConfiguration config) {
69         this.repository = requireNonNull(repository);
70         this.config = requireNonNull(config);
71     }
72
73     @Override
74     public @NonNull ListenableFuture<EffectiveModelContext> createEffectiveModelContext(
75             final @NonNull Collection<SourceIdentifier> requiredSources) {
76         return createSchemaContext(requiredSources,
77                 config.getStatementParserMode() == StatementParserMode.SEMVER_MODE ? semVerCache : revisionCache,
78                 new AssembleSources(repository.factory(), config));
79     }
80
81     private @NonNull ListenableFuture<EffectiveModelContext> createSchemaContext(
82             final Collection<SourceIdentifier> requiredSources,
83             final Cache<Collection<SourceIdentifier>, EffectiveModelContext> cache,
84             final AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> assembleSources) {
85         // Make sources unique
86         final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
87
88         final EffectiveModelContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
89         if (existing != null) {
90             LOG.debug("Returning cached context {}", existing);
91             return immediateFluentFuture(existing);
92         }
93
94         // Request all sources be loaded
95         ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
96             this::requestSource));
97
98         // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
99         // Also remove duplicates if present
100         // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
101         sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
102             MoreExecutors.directExecutor());
103
104         // Assemble sources into a schema context
105         final ListenableFuture<EffectiveModelContext> cf = Futures.transformAsync(sf, assembleSources,
106             MoreExecutors.directExecutor());
107
108         final SettableFuture<EffectiveModelContext> rf = SettableFuture.create();
109         Futures.addCallback(cf, new FutureCallback<EffectiveModelContext>() {
110             @Override
111             public void onSuccess(final EffectiveModelContext result) {
112                 // Deduplicate concurrent loads
113                 final EffectiveModelContext existing;
114                 try {
115                     existing = cache.get(uniqueSourceIdentifiers, () -> result);
116                 } catch (ExecutionException e) {
117                     LOG.warn("Failed to recheck result with cache, will use computed value", e);
118                     rf.set(result);
119                     return;
120                 }
121
122                 rf.set(existing);
123             }
124
125             @Override
126             public void onFailure(final Throwable cause) {
127                 LOG.debug("Failed to assemble sources", cause);
128                 rf.setException(cause);
129             }
130         }, MoreExecutors.directExecutor());
131
132         return rf;
133     }
134
135     private ListenableFuture<ASTSchemaSource> requestSource(final @NonNull SourceIdentifier identifier) {
136         return repository.getSchemaSource(identifier, ASTSchemaSource.class);
137     }
138
139     /**
140      * Return a set of de-duplicated inputs.
141      *
142      * @return set (preserving ordering) from the input collection
143      */
144     private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
145         final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
146         if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
147             // Can potentially reuse input
148             return ImmutableList.copyOf(requiredSources);
149         }
150
151         LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
152             Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
153         return ImmutableList.copyOf(uniqueSourceIdentifiers);
154     }
155
156     @SuppressModernizer
157     private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
158             List<ASTSchemaSource>> {
159         private final List<SourceIdentifier> sourceIdentifiers;
160
161         SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
162             this.sourceIdentifiers = requireNonNull(sourceIdentifiers);
163         }
164
165         @Override
166         public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
167             final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
168
169             for (int i = 0; i < input.size(); i++) {
170
171                 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
172                 final ASTSchemaSource astSchemaSource = input.get(i);
173                 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
174
175                 if (!expectedSId.equals(realSId)) {
176                     LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. "
177                         + "Using actual id", expectedSId.getName(), expectedSId, realSId);
178                 }
179
180                 if (filtered.containsKey(realSId)) {
181                     LOG.warn("Duplicate source for module {} detected in reactor", realSId);
182                 }
183
184                 filtered.put(realSId, astSchemaSource);
185
186             }
187             return ImmutableList.copyOf(filtered.values());
188         }
189     }
190
191     private static final class AssembleSources implements AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> {
192         private final @NonNull YangParserFactory parserFactory;
193         private final @NonNull SchemaContextFactoryConfiguration config;
194         private final @NonNull Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
195
196         private AssembleSources(final @NonNull YangParserFactory parserFactory,
197                 final @NonNull SchemaContextFactoryConfiguration config) {
198             this.parserFactory = parserFactory;
199             this.config = config;
200             switch (config.getStatementParserMode()) {
201                 case SEMVER_MODE:
202                     this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
203                     break;
204                 default:
205                     this.getIdentifier = ASTSchemaSource::getIdentifier;
206             }
207         }
208
209         @Override
210         public FluentFuture<EffectiveModelContext> apply(final List<ASTSchemaSource> sources)
211                 throws SchemaResolutionException, ReactorException {
212             final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
213             final Map<SourceIdentifier, YangModelDependencyInfo> deps =
214                     Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
215
216             LOG.debug("Resolving dependency reactor {}", deps);
217
218             final StatementParserMode statementParserMode = config.getStatementParserMode();
219             final DependencyResolver res = statementParserMode == StatementParserMode.SEMVER_MODE
220                     ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
221             if (!res.getUnresolvedSources().isEmpty()) {
222                 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
223                     res.getUnsatisfiedImports());
224                 throw new SchemaResolutionException("Failed to resolve required models",
225                         res.getResolvedSources(), res.getUnsatisfiedImports());
226             }
227
228             final YangParser parser = parserFactory.createParser(statementParserMode);
229             config.getSupportedFeatures().ifPresent(parser::setSupportedFeatures);
230             config.getModulesDeviatedByModules().ifPresent(parser::setModulesWithSupportedDeviations);
231
232             for (final Entry<SourceIdentifier, ASTSchemaSource> entry : srcs.entrySet()) {
233                 final ASTSchemaSource ast = entry.getValue();
234                 final ParserRuleContext parserRuleCtx = ast.getAST();
235                 checkArgument(parserRuleCtx instanceof StatementContext, "Unsupported context class %s for source %s",
236                     parserRuleCtx.getClass(), entry.getKey());
237
238                 try {
239                     parser.addSource(entry.getValue());
240                 } catch (YangSyntaxErrorException | IOException e) {
241                     throw new SchemaResolutionException("Failed to add source " + entry.getKey(), e);
242                 }
243             }
244
245             final EffectiveModelContext schemaContext;
246             try {
247                 schemaContext = parser.buildEffectiveModel();
248             } catch (final YangParserException e) {
249                 throw new SchemaResolutionException("Failed to resolve required models", e);
250             }
251
252             return immediateFluentFuture(schemaContext);
253         }
254     }
255 }