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.base.Predicate;
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.collect.Collections2;
16 import com.google.common.collect.ImmutableList;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Maps;
19 import com.google.common.util.concurrent.AsyncFunction;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
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;
31 import javax.annotation.Nullable;
32 import org.antlr.v4.runtime.ParserRuleContext;
33 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser.StatementContext;
34 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
35 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
36 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
38 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
39 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
44 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
45 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
46 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
47 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 final class SharedSchemaContextFactory implements SchemaContextFactory {
52 private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
53 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
55 private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
57 public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
58 return repository.getSchemaSource(input, ASTSchemaSource.class);
61 private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues().build();
63 private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
65 public ListenableFuture<SchemaContext> apply(final List<ASTSchemaSource> sources) throws SchemaResolutionException, SourceException, ReactorException {
66 final Map<SourceIdentifier, ASTSchemaSource> srcs =
67 Maps.uniqueIndex(sources, ASTSchemaSource.GET_IDENTIFIER);
68 final Map<SourceIdentifier, YangModelDependencyInfo> deps =
69 Maps.transformValues(srcs, ASTSchemaSource.GET_DEPINFO);
71 LOG.debug("Resolving dependency reactor {}", deps);
73 final DependencyResolver res = DependencyResolver.create(deps);
74 if (!res.getUnresolvedSources().isEmpty()) {
75 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(), res.getUnsatisfiedImports());
76 throw new SchemaResolutionException("Failed to resolve required models",
77 res.getResolvedSources(), res.getUnsatisfiedImports());
80 final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
81 final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild();
83 for (final Entry<SourceIdentifier, ParserRuleContext> e : asts.entrySet()) {
84 final ParserRuleContext parserRuleCtx = e.getValue();
85 Preconditions.checkArgument(parserRuleCtx instanceof StatementContext,
86 "Unsupported context class %s for source %s", parserRuleCtx.getClass(), e.getKey());
88 reactor.addSource(new YangStatementSourceImpl(e.getKey(), (StatementContext) parserRuleCtx));
91 SchemaContext schemaContext = reactor.buildEffective();
93 return Futures.immediateCheckedFuture(schemaContext);
97 private final SharedSchemaRepository repository;
98 // FIXME: ignored right now
99 private final SchemaSourceFilter filter;
101 // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository (final implementation)
102 public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
103 this.repository = Preconditions.checkNotNull(repository);
104 this.filter = Preconditions.checkNotNull(filter);
108 public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
109 // Make sources unique
110 final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
112 final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
113 if (existing != null) {
114 LOG.debug("Returning cached context {}", existing);
115 return Futures.immediateCheckedFuture(existing);
118 // Request all sources be loaded
119 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources));
121 // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
122 // Also remove duplicates if present
123 // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
124 sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));
126 // Assemble sources into a schema context
127 final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
129 // Populate cache when successful
130 Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
132 public void onSuccess(final SchemaContext result) {
133 cache.put(uniqueSourceIdentifiers, result);
137 public void onFailure(final Throwable t) {
138 LOG.debug("Failed to assemble sources", t);
142 return Futures.makeChecked(cf, MAPPER);
146 * @return set (preserving ordering) from the input collection
148 private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
149 final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
150 if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
151 // Can potentially reuse input
152 return ImmutableList.copyOf(requiredSources);
155 LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
156 Collections2.filter(uniqueSourceIdentifiers, new Predicate<SourceIdentifier>() {
158 public boolean apply(@Nullable final SourceIdentifier input) {
159 return Iterables.frequency(requiredSources, input) > 1;
162 return ImmutableList.copyOf(uniqueSourceIdentifiers);
165 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>, List<ASTSchemaSource>> {
166 private final List<SourceIdentifier> sourceIdentifiers;
168 public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
169 this.sourceIdentifiers = Preconditions.checkNotNull(sourceIdentifiers);
173 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
174 final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
176 for (int i = 0; i < input.size(); i++) {
178 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
179 final ASTSchemaSource astSchemaSource = input.get(i);
180 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
182 if (!expectedSId.equals(realSId)) {
183 LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. Using actual id",
184 expectedSId.getName(), expectedSId, realSId);
187 if (filtered.containsKey(realSId)) {
188 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
191 filtered.put(realSId, astSchemaSource);
194 return ImmutableList.copyOf(filtered.values());