2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.repo;
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;
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;
33 import java.util.Map.Entry;
35 import java.util.concurrent.ExecutionException;
36 import org.antlr.v4.runtime.ParserRuleContext;
37 import org.eclipse.jdt.annotation.NonNull;
38 import org.gaul.modernizer_maven_annotations.SuppressModernizer;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
41 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
42 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactoryConfiguration;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
45 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
46 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
47 import org.opendaylight.yangtools.yang.parser.impl.DefaultReactors;
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.rfc7950.repo.YangStatementStreamSource;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor.BuildAction;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 final class SharedSchemaContextFactory implements EffectiveModelContextFactory {
57 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
59 private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> revisionCache = CacheBuilder.newBuilder()
60 .weakValues().build();
61 private final Cache<Collection<SourceIdentifier>, EffectiveModelContext> semVerCache = CacheBuilder.newBuilder()
62 .weakValues().build();
63 private final @NonNull SchemaRepository repository;
64 private final @NonNull SchemaContextFactoryConfiguration config;
66 SharedSchemaContextFactory(final @NonNull SchemaRepository repository,
67 final @NonNull SchemaContextFactoryConfiguration config) {
68 this.repository = requireNonNull(repository);
69 this.config = requireNonNull(config);
73 public @NonNull ListenableFuture<EffectiveModelContext> createEffectiveModelContext(
74 final @NonNull Collection<SourceIdentifier> requiredSources) {
75 return createSchemaContext(requiredSources,
76 config.getStatementParserMode() == StatementParserMode.SEMVER_MODE ? semVerCache : revisionCache,
77 new AssembleSources(config));
80 private @NonNull ListenableFuture<EffectiveModelContext> createSchemaContext(
81 final Collection<SourceIdentifier> requiredSources,
82 final Cache<Collection<SourceIdentifier>, EffectiveModelContext> cache,
83 final AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> assembleSources) {
84 // Make sources unique
85 final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
87 final EffectiveModelContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
88 if (existing != null) {
89 LOG.debug("Returning cached context {}", existing);
90 return immediateFluentFuture(existing);
93 // Request all sources be loaded
94 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
95 this::requestSource));
97 // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
98 // Also remove duplicates if present
99 // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
100 sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
101 MoreExecutors.directExecutor());
103 // Assemble sources into a schema context
104 final ListenableFuture<EffectiveModelContext> cf = Futures.transformAsync(sf, assembleSources,
105 MoreExecutors.directExecutor());
107 final SettableFuture<EffectiveModelContext> rf = SettableFuture.create();
108 Futures.addCallback(cf, new FutureCallback<EffectiveModelContext>() {
110 public void onSuccess(final EffectiveModelContext result) {
111 // Deduplicate concurrent loads
112 final EffectiveModelContext existing;
114 existing = cache.get(uniqueSourceIdentifiers, () -> result);
115 } catch (ExecutionException e) {
116 LOG.warn("Failed to recheck result with cache, will use computed value", e);
125 public void onFailure(final Throwable cause) {
126 LOG.debug("Failed to assemble sources", cause);
127 rf.setException(cause);
129 }, MoreExecutors.directExecutor());
134 private ListenableFuture<ASTSchemaSource> requestSource(final @NonNull SourceIdentifier identifier) {
135 return repository.getSchemaSource(identifier, ASTSchemaSource.class);
139 * Return a set of de-duplicated inputs.
141 * @return set (preserving ordering) from the input collection
143 private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
144 final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
145 if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
146 // Can potentially reuse input
147 return ImmutableList.copyOf(requiredSources);
150 LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
151 Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
152 return ImmutableList.copyOf(uniqueSourceIdentifiers);
156 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
157 List<ASTSchemaSource>> {
158 private final List<SourceIdentifier> sourceIdentifiers;
160 SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
161 this.sourceIdentifiers = requireNonNull(sourceIdentifiers);
165 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
166 final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
168 for (int i = 0; i < input.size(); i++) {
170 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
171 final ASTSchemaSource astSchemaSource = input.get(i);
172 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
174 if (!expectedSId.equals(realSId)) {
175 LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. "
176 + "Using actual id", expectedSId.getName(), expectedSId, realSId);
179 if (filtered.containsKey(realSId)) {
180 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
183 filtered.put(realSId, astSchemaSource);
186 return ImmutableList.copyOf(filtered.values());
190 private static final class AssembleSources implements AsyncFunction<List<ASTSchemaSource>, EffectiveModelContext> {
191 private final @NonNull SchemaContextFactoryConfiguration config;
192 private final @NonNull Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
194 private AssembleSources(final @NonNull SchemaContextFactoryConfiguration config) {
195 this.config = config;
196 switch (config.getStatementParserMode()) {
198 this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
201 this.getIdentifier = ASTSchemaSource::getIdentifier;
206 public FluentFuture<EffectiveModelContext> apply(final List<ASTSchemaSource> sources)
207 throws SchemaResolutionException, ReactorException {
208 final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
209 final Map<SourceIdentifier, YangModelDependencyInfo> deps =
210 Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
212 LOG.debug("Resolving dependency reactor {}", deps);
214 final StatementParserMode statementParserMode = config.getStatementParserMode();
215 final DependencyResolver res = statementParserMode == StatementParserMode.SEMVER_MODE
216 ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
217 if (!res.getUnresolvedSources().isEmpty()) {
218 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
219 res.getUnsatisfiedImports());
220 throw new SchemaResolutionException("Failed to resolve required models",
221 res.getResolvedSources(), res.getUnsatisfiedImports());
224 final BuildAction reactor = DefaultReactors.defaultReactor().newBuild(statementParserMode);
225 config.getSupportedFeatures().ifPresent(reactor::setSupportedFeatures);
226 config.getModulesDeviatedByModules().ifPresent(reactor::setModulesWithSupportedDeviations);
228 for (final Entry<SourceIdentifier, ASTSchemaSource> e : srcs.entrySet()) {
229 final ASTSchemaSource ast = e.getValue();
230 final ParserRuleContext parserRuleCtx = ast.getAST();
231 checkArgument(parserRuleCtx instanceof StatementContext, "Unsupported context class %s for source %s",
232 parserRuleCtx.getClass(), e.getKey());
234 reactor.addSource(YangStatementStreamSource.create(e.getKey(), (StatementContext) parserRuleCtx,
235 ast.getSymbolicName().orElse(null)));
238 final EffectiveModelContext schemaContext;
240 schemaContext = reactor.buildEffective();
241 } catch (final ReactorException ex) {
242 throw new SchemaResolutionException("Failed to resolve required models", ex.getSourceIdentifier(), ex);
245 return immediateFluentFuture(schemaContext);