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