Deduplicate concurrent SchemaContext loads
[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.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.antlr.v4.runtime.ParserRuleContext;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
44 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
45 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
46 import org.opendaylight.yangtools.yang.parser.impl.DefaultReactors;
47 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.ASTSchemaSource;
48 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangModelDependencyInfo;
49 import org.opendaylight.yangtools.yang.parser.rfc7950.repo.YangStatementStreamSource;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
51 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 final class SharedSchemaContextFactory implements EffectiveModelContextFactory {
56     private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
57
58     private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> revisionCache = CacheBuilder.newBuilder()
59             .weakValues().build();
60     private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> semVerCache = CacheBuilder.newBuilder()
61             .weakValues().build();
62     private final @NonNull SchemaRepository repository;
63     private final @NonNull SchemaContextFactoryConfiguration config;
64
65     SharedSchemaContextFactory(final @NonNull SchemaRepository repository,
66         final @NonNull SchemaContextFactoryConfiguration config) {
67         this.repository = requireNonNull(repository);
68         this.config = requireNonNull(config);
69     }
70
71     @Override
72     public @NonNull ListenableFuture<EffectiveModelContext> createEffectiveModelContext(
73             final @NonNull Collection<SourceIdentifier> requiredSources) {
74         return createSchemaContext(requiredSources,
75                 config.getStatementParserMode() == StatementParserMode.SEMVER_MODE ? semVerCache : revisionCache,
76                 new AssembleSources(config));
77     }
78
79     private @NonNull ListenableFuture<EffectiveModelContext> createSchemaContext(
80             final Collection<SourceIdentifier> requiredSources,
81             final Cache<Collection<SourceIdentifier>, EffectiveModelContext> cache,
82             final AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> assembleSources) {
83         // Make sources unique
84         final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
85
86         final EffectiveModelContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
87         if (existing != null) {
88             LOG.debug("Returning cached context {}", existing);
89             return immediateFluentFuture(existing);
90         }
91
92         // Request all sources be loaded
93         ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
94             this::requestSource));
95
96         // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
97         // Also remove duplicates if present
98         // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
99         sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
100             MoreExecutors.directExecutor());
101
102         // Assemble sources into a schema context
103         final ListenableFuture<EffectiveModelContext> cf = Futures.transformAsync(sf, assembleSources,
104             MoreExecutors.directExecutor());
105
106         final SettableFuture<EffectiveModelContext> rf = SettableFuture.create();
107         Futures.addCallback(cf, new FutureCallback<EffectiveModelContext>() {
108             @Override
109             public void onSuccess(final EffectiveModelContext result) {
110                 // Deduplicate concurrent loads
111                 final EffectiveModelContext existing;
112                 try {
113                     existing = cache.get(uniqueSourceIdentifiers, () -> result);
114                 } catch (ExecutionException e) {
115                     LOG.warn("Failed to recheck result with cache, will use computed value", e);
116                     rf.set(result);
117                     return;
118                 }
119
120                 rf.set(existing);
121             }
122
123             @Override
124             public void onFailure(final Throwable cause) {
125                 LOG.debug("Failed to assemble sources", cause);
126                 rf.setException(cause);
127             }
128         }, MoreExecutors.directExecutor());
129
130         return rf;
131     }
132
133     private ListenableFuture<ASTSchemaSource> requestSource(final @NonNull SourceIdentifier identifier) {
134         return repository.getSchemaSource(identifier, ASTSchemaSource.class);
135     }
136
137     /**
138      * Return a set of de-duplicated inputs.
139      *
140      * @return set (preserving ordering) from the input collection
141      */
142     private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
143         final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
144         if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
145             // Can potentially reuse input
146             return ImmutableList.copyOf(requiredSources);
147         }
148
149         LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
150             Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
151         return ImmutableList.copyOf(uniqueSourceIdentifiers);
152     }
153
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 SchemaContextFactoryConfiguration config;
190         private final @NonNull Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
191
192         private AssembleSources(final @NonNull SchemaContextFactoryConfiguration config) {
193             this.config = config;
194             switch (config.getStatementParserMode()) {
195                 case SEMVER_MODE:
196                     this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
197                     break;
198                 default:
199                     this.getIdentifier = ASTSchemaSource::getIdentifier;
200             }
201         }
202
203         @Override
204         public FluentFuture<EffectiveModelContext> apply(final List<ASTSchemaSource> sources)
205                 throws SchemaResolutionException, ReactorException {
206             final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
207             final Map<SourceIdentifier, YangModelDependencyInfo> deps =
208                     Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
209
210             LOG.debug("Resolving dependency reactor {}", deps);
211
212             final StatementParserMode statementParserMode = config.getStatementParserMode();
213             final DependencyResolver res = statementParserMode == StatementParserMode.SEMVER_MODE
214                     ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
215             if (!res.getUnresolvedSources().isEmpty()) {
216                 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
217                     res.getUnsatisfiedImports());
218                 throw new SchemaResolutionException("Failed to resolve required models",
219                         res.getResolvedSources(), res.getUnsatisfiedImports());
220             }
221
222             final BuildAction reactor = DefaultReactors.defaultReactor().newBuild(statementParserMode);
223             config.getSupportedFeatures().ifPresent(reactor::setSupportedFeatures);
224             config.getModulesDeviatedByModules().ifPresent(reactor::setModulesWithSupportedDeviations);
225
226             for (final Entry<SourceIdentifier, ASTSchemaSource> e : srcs.entrySet()) {
227                 final ASTSchemaSource ast = e.getValue();
228                 final ParserRuleContext parserRuleCtx = ast.getAST();
229                 checkArgument(parserRuleCtx instanceof StatementContext, "Unsupported context class %s for source %s",
230                     parserRuleCtx.getClass(), e.getKey());
231
232                 reactor.addSource(YangStatementStreamSource.create(e.getKey(), (StatementContext) parserRuleCtx,
233                     ast.getSymbolicName().orElse(null)));
234             }
235
236             final EffectiveModelContext schemaContext;
237             try {
238                 schemaContext = reactor.buildEffective();
239             } catch (final ReactorException ex) {
240                 throw new SchemaResolutionException("Failed to resolve required models", ex.getSourceIdentifier(), ex);
241             }
242
243             return immediateFluentFuture(schemaContext);
244         }
245     }
246 }