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.io.IOException;
29 import java.util.Collection;
30 import java.util.LinkedHashMap;
31 import java.util.LinkedHashSet;
32 import java.util.List;
34 import java.util.Map.Entry;
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;
57 final class SharedSchemaContextFactory implements EffectiveModelContextFactory {
58 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
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;
67 SharedSchemaContextFactory(final @NonNull SharedSchemaRepository repository,
68 final @NonNull SchemaContextFactoryConfiguration config) {
69 this.repository = requireNonNull(repository);
70 this.config = requireNonNull(config);
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));
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);
88 final EffectiveModelContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
89 if (existing != null) {
90 LOG.debug("Returning cached context {}", existing);
91 return immediateFluentFuture(existing);
94 // Request all sources be loaded
95 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
96 this::requestSource));
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());
104 // Assemble sources into a schema context
105 final ListenableFuture<EffectiveModelContext> cf = Futures.transformAsync(sf, assembleSources,
106 MoreExecutors.directExecutor());
108 final SettableFuture<EffectiveModelContext> rf = SettableFuture.create();
109 Futures.addCallback(cf, new FutureCallback<EffectiveModelContext>() {
111 public void onSuccess(final EffectiveModelContext result) {
112 // Deduplicate concurrent loads
113 final EffectiveModelContext existing;
115 existing = cache.get(uniqueSourceIdentifiers, () -> result);
116 } catch (ExecutionException e) {
117 LOG.warn("Failed to recheck result with cache, will use computed value", e);
126 public void onFailure(final Throwable cause) {
127 LOG.debug("Failed to assemble sources", cause);
128 rf.setException(cause);
130 }, MoreExecutors.directExecutor());
135 private ListenableFuture<ASTSchemaSource> requestSource(final @NonNull SourceIdentifier identifier) {
136 return repository.getSchemaSource(identifier, ASTSchemaSource.class);
140 * Return a set of de-duplicated inputs.
142 * @return set (preserving ordering) from the input collection
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);
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);
157 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
158 List<ASTSchemaSource>> {
159 private final List<SourceIdentifier> sourceIdentifiers;
161 SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
162 this.sourceIdentifiers = requireNonNull(sourceIdentifiers);
166 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
167 final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
169 for (int i = 0; i < input.size(); i++) {
171 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
172 final ASTSchemaSource astSchemaSource = input.get(i);
173 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
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);
180 if (filtered.containsKey(realSId)) {
181 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
184 filtered.put(realSId, astSchemaSource);
187 return ImmutableList.copyOf(filtered.values());
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;
196 private AssembleSources(final @NonNull YangParserFactory parserFactory,
197 final @NonNull SchemaContextFactoryConfiguration config) {
198 this.parserFactory = parserFactory;
199 this.config = config;
200 switch (config.getStatementParserMode()) {
202 this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
205 this.getIdentifier = ASTSchemaSource::getIdentifier;
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);
216 LOG.debug("Resolving dependency reactor {}", deps);
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());
228 final YangParser parser = parserFactory.createParser(statementParserMode);
229 config.getSupportedFeatures().ifPresent(parser::setSupportedFeatures);
230 config.getModulesDeviatedByModules().ifPresent(parser::setModulesWithSupportedDeviations);
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());
239 parser.addSource(entry.getValue());
240 } catch (YangSyntaxErrorException | IOException e) {
241 throw new SchemaResolutionException("Failed to add source " + entry.getKey(), e);
245 final EffectiveModelContext schemaContext;
247 schemaContext = parser.buildEffectiveModel();
248 } catch (final YangParserException e) {
249 throw new SchemaResolutionException("Failed to resolve required models", e);
252 return immediateFluentFuture(schemaContext);