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 com.google.common.base.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.Cache;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Maps;
18 import com.google.common.util.concurrent.AsyncFunction;
19 import com.google.common.util.concurrent.CheckedFuture;
20 import com.google.common.util.concurrent.FutureCallback;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.common.util.concurrent.MoreExecutors;
24 import java.util.Collection;
25 import java.util.LinkedHashMap;
26 import java.util.LinkedHashSet;
27 import java.util.List;
29 import java.util.Map.Entry;
30 import java.util.Optional;
32 import javax.annotation.Nonnull;
33 import org.antlr.v4.runtime.ParserRuleContext;
34 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
35 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
36 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
40 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
41 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
42 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
43 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
44 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
46 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
47 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
48 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
49 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 final class SharedSchemaContextFactory implements SchemaContextFactory {
54 private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper
55 .create("resolve sources", SchemaResolutionException.class);
56 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
58 private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues()
60 private final Cache<Collection<SourceIdentifier>, SchemaContext> semVerCache = CacheBuilder.newBuilder()
61 .weakValues().build();
62 private final SharedSchemaRepository repository;
63 // FIXME: ignored right now
64 private final SchemaSourceFilter filter;
66 // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository
67 // (final implementation)
68 SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
69 this.repository = Preconditions.checkNotNull(repository);
70 this.filter = Preconditions.checkNotNull(filter);
74 public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(
75 final Collection<SourceIdentifier> requiredSources, final StatementParserMode statementParserMode,
76 final Set<QName> supportedFeatures) {
77 return createSchemaContext(requiredSources,
78 statementParserMode == StatementParserMode.SEMVER_MODE ? this.semVerCache : this.cache,
79 new AssembleSources(Optional.ofNullable(supportedFeatures), statementParserMode));
82 private CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(
83 final Collection<SourceIdentifier> requiredSources,
84 final Cache<Collection<SourceIdentifier>, SchemaContext> cache,
85 final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources) {
86 // Make sources unique
87 final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
89 final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
90 if (existing != null) {
91 LOG.debug("Returning cached context {}", existing);
92 return Futures.immediateCheckedFuture(existing);
95 // Request all sources be loaded
96 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
97 this::requestSource));
99 // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
100 // Also remove duplicates if present
101 // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
102 sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
103 MoreExecutors.directExecutor());
105 // Assemble sources into a schema context
106 final ListenableFuture<SchemaContext> cf = Futures.transformAsync(sf, assembleSources,
107 MoreExecutors.directExecutor());
109 // Populate cache when successful
110 Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
112 public void onSuccess(final SchemaContext result) {
113 cache.put(uniqueSourceIdentifiers, result);
117 public void onFailure(@Nonnull final Throwable cause) {
118 LOG.debug("Failed to assemble sources", cause);
120 }, MoreExecutors.directExecutor());
122 return Futures.makeChecked(cf, MAPPER);
125 private ListenableFuture<ASTSchemaSource> requestSource(final SourceIdentifier identifier) {
126 return repository.getSchemaSource(identifier, ASTSchemaSource.class);
130 * Return a set of de-duplicated inputs.
132 * @return set (preserving ordering) from the input collection
134 private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
135 final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
136 if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
137 // Can potentially reuse input
138 return ImmutableList.copyOf(requiredSources);
141 LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
142 Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
143 return ImmutableList.copyOf(uniqueSourceIdentifiers);
146 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
147 List<ASTSchemaSource>> {
148 private final List<SourceIdentifier> sourceIdentifiers;
150 SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
151 this.sourceIdentifiers = Preconditions.checkNotNull(sourceIdentifiers);
155 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
156 final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
158 for (int i = 0; i < input.size(); i++) {
160 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
161 final ASTSchemaSource astSchemaSource = input.get(i);
162 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
164 if (!expectedSId.equals(realSId)) {
165 LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. "
166 + "Using actual id", expectedSId.getName(), expectedSId, realSId);
169 if (filtered.containsKey(realSId)) {
170 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
173 filtered.put(realSId, astSchemaSource);
176 return ImmutableList.copyOf(filtered.values());
180 private static final class AssembleSources implements AsyncFunction<List<ASTSchemaSource>, SchemaContext> {
182 private final Optional<Set<QName>> supportedFeatures;
183 private final StatementParserMode statementParserMode;
184 private final Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
186 private AssembleSources(final Optional<Set<QName>> supportedFeatures,
187 final StatementParserMode statementParserMode) {
188 this.supportedFeatures = supportedFeatures;
189 this.statementParserMode = Preconditions.checkNotNull(statementParserMode);
190 switch (statementParserMode) {
192 this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
195 this.getIdentifier = ASTSchemaSource::getIdentifier;
200 public ListenableFuture<SchemaContext> apply(@Nonnull final List<ASTSchemaSource> sources)
201 throws SchemaResolutionException, ReactorException {
202 final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
203 final Map<SourceIdentifier, YangModelDependencyInfo> deps =
204 Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
206 LOG.debug("Resolving dependency reactor {}", deps);
208 final DependencyResolver res = this.statementParserMode == StatementParserMode.SEMVER_MODE
209 ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
210 if (!res.getUnresolvedSources().isEmpty()) {
211 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
212 res.getUnsatisfiedImports());
213 throw new SchemaResolutionException("Failed to resolve required models",
214 res.getResolvedSources(), res.getUnsatisfiedImports());
217 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(srcs, ASTSchemaSource::getAST);
218 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild(
219 statementParserMode, supportedFeatures);
221 for (final Entry<SourceIdentifier, ParserRuleContext> e : asts.entrySet()) {
222 final ParserRuleContext parserRuleCtx = e.getValue();
223 Preconditions.checkArgument(parserRuleCtx instanceof StatementContext,
224 "Unsupported context class %s for source %s", parserRuleCtx.getClass(), e.getKey());
226 reactor.addSource(new YangStatementSourceImpl(e.getKey(), (StatementContext) parserRuleCtx));
229 final SchemaContext schemaContext;
231 schemaContext = reactor.buildEffective();
232 } catch (final ReactorException ex) {
233 throw new SchemaResolutionException("Failed to resolve required models", ex.getSourceIdentifier(), ex);
236 return Futures.immediateCheckedFuture(schemaContext);