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 org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
12 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
13 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
14 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
15 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangStatementSourceImpl;
16 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
17 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
18 import com.google.common.base.Function;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Predicate;
21 import com.google.common.cache.Cache;
22 import com.google.common.cache.CacheBuilder;
23 import com.google.common.collect.Collections2;
24 import com.google.common.collect.Iterables;
25 import com.google.common.collect.Lists;
26 import com.google.common.collect.Maps;
27 import com.google.common.collect.Sets;
28 import com.google.common.util.concurrent.AsyncFunction;
29 import com.google.common.util.concurrent.CheckedFuture;
30 import com.google.common.util.concurrent.FutureCallback;
31 import com.google.common.util.concurrent.Futures;
32 import com.google.common.util.concurrent.ListenableFuture;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.List;
37 import java.util.Map.Entry;
39 import javax.annotation.Nullable;
40 import org.antlr.v4.runtime.ParserRuleContext;
41 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
42 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
46 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
47 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
48 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 final class SharedSchemaContextFactory implements SchemaContextFactory {
53 private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
54 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
56 private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
58 public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
59 return repository.getSchemaSource(input, ASTSchemaSource.class);
62 private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues().build();
64 private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
66 public ListenableFuture<SchemaContext> apply(final List<ASTSchemaSource> sources) throws SchemaResolutionException, SourceException, ReactorException {
67 final Map<SourceIdentifier, ASTSchemaSource> srcs =
68 Maps.uniqueIndex(sources, ASTSchemaSource.GET_IDENTIFIER);
69 final Map<SourceIdentifier, YangModelDependencyInfo> deps =
70 Maps.transformValues(srcs, ASTSchemaSource.GET_DEPINFO);
72 LOG.debug("Resolving dependency reactor {}", deps);
74 final DependencyResolver res = DependencyResolver.create(deps);
75 if (!res.getUnresolvedSources().isEmpty()) {
76 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(), res.getUnsatisfiedImports());
77 throw new SchemaResolutionException("Failed to resolve required models",
78 res.getResolvedSources(), res.getUnsatisfiedImports());
81 final Map<SourceIdentifier, ParserRuleContext> asts =
82 Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
84 CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
87 for (final Entry<SourceIdentifier, ParserRuleContext> entry : asts
89 ParserRuleContext parserRuleCtx = entry.getValue();
90 if (parserRuleCtx instanceof YangStatementParser.StatementContext) {
91 YangStatementSourceImpl source = new YangStatementSourceImpl(
93 (YangStatementParser.StatementContext) parserRuleCtx);
94 reactor.addSource(source);
96 throw new IllegalArgumentException("Only YangStatementParser.StatementContext is supported.");
100 SchemaContext schemaContext = reactor.buildEffective();
102 return Futures.immediateCheckedFuture(schemaContext);
106 private final SharedSchemaRepository repository;
107 // FIXME: ignored right now
108 private final SchemaSourceFilter filter;
110 // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository (final implementation)
111 public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
112 this.repository = Preconditions.checkNotNull(repository);
113 this.filter = Preconditions.checkNotNull(filter);
117 public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
118 // Make sources unique
119 final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
121 final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
122 if (existing != null) {
123 LOG.debug("Returning cached context {}", existing);
124 return Futures.immediateCheckedFuture(existing);
127 // Request all sources be loaded
128 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources));
130 // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
131 // Also remove duplicates if present
132 // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
133 sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));
135 // Assemble sources into a schema context
136 final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
138 // Populate cache when successful
139 Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
141 public void onSuccess(final SchemaContext result) {
142 cache.put(uniqueSourceIdentifiers, result);
146 public void onFailure(final Throwable t) {
147 LOG.debug("Failed to assemble sources", t);
151 return Futures.makeChecked(cf, MAPPER);
155 * @return set (preserving ordering) from the input collection
157 private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
158 final Set<SourceIdentifier> uniqueSourceIdentifiers = Collections.unmodifiableSet(Sets.newLinkedHashSet(requiredSources));
159 if(uniqueSourceIdentifiers.size() != requiredSources.size()) {
160 LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}", Collections2.filter(uniqueSourceIdentifiers, new Predicate<SourceIdentifier>() {
162 public boolean apply(@Nullable final SourceIdentifier input) {
163 return Iterables.frequency(requiredSources, input) > 1;
167 return Lists.newArrayList(uniqueSourceIdentifiers);
170 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>, List<ASTSchemaSource>> {
171 private final List<SourceIdentifier> sourceIdentifiers;
173 public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
174 this.sourceIdentifiers = sourceIdentifiers;
178 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
179 final Map<SourceIdentifier, ASTSchemaSource> filtered = Maps.newLinkedHashMap();
181 for (int i = 0; i < input.size(); i++) {
183 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
184 final ASTSchemaSource astSchemaSource = input.get(i);
185 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
187 if (!expectedSId.equals(realSId)) {
188 LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. Using actual id", expectedSId.getName(), expectedSId, realSId);
191 if (filtered.containsKey(realSId)) {
192 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
195 filtered.put(realSId, astSchemaSource);
198 return Lists.newArrayList(filtered.values());