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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.cache.Cache;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.collect.Collections2;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Maps;
20 import com.google.common.collect.Sets;
21 import com.google.common.util.concurrent.AsyncFunction;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.FutureCallback;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Date;
30 import java.util.LinkedHashMap;
31 import java.util.List;
33 import java.util.Map.Entry;
35 import java.util.TreeMap;
36 import javax.annotation.Nullable;
37 import org.antlr.v4.runtime.ParserRuleContext;
38 import org.antlr.v4.runtime.tree.ParseTreeWalker;
39 import org.opendaylight.yangtools.util.concurrent.ExceptionMapper;
40 import org.opendaylight.yangtools.util.concurrent.ReflectiveExceptionMapper;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
44 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
45 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
46 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
47 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
48 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
49 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
50 import org.opendaylight.yangtools.yang.parser.impl.YangParserListenerImpl;
51 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
52 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 final class SharedSchemaContextFactory implements SchemaContextFactory {
57 private static final ExceptionMapper<SchemaResolutionException> MAPPER = ReflectiveExceptionMapper.create("resolve sources", SchemaResolutionException.class);
58 private static final Logger LOG = LoggerFactory.getLogger(SharedSchemaContextFactory.class);
60 private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
62 public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
63 return repository.getSchemaSource(input, ASTSchemaSource.class);
66 private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues().build();
68 private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
70 public ListenableFuture<SchemaContext> apply(final List<ASTSchemaSource> sources) throws SchemaResolutionException {
71 final Map<SourceIdentifier, ASTSchemaSource> srcs =
72 Maps.uniqueIndex(sources, ASTSchemaSource.GET_IDENTIFIER);
73 final Map<SourceIdentifier, YangModelDependencyInfo> deps =
74 Maps.transformValues(srcs, ASTSchemaSource.GET_DEPINFO);
76 LOG.debug("Resolving dependency reactor {}", deps);
78 final DependencyResolver res = DependencyResolver.create(deps);
79 if (!res.getUnresolvedSources().isEmpty()) {
80 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(), res.getUnsatisfiedImports());
82 // FIXME: push into DependencyResolver
84 throw new SchemaResolutionException("Failed to resolve required models",
85 res.getResolvedSources(), res.getUnsatisfiedImports());
88 final Map<SourceIdentifier, ParserRuleContext> asts =
89 Maps.transformValues(srcs, ASTSchemaSource.GET_AST);
90 final Map<String, TreeMap<Date, URI>> namespaceContext = BuilderUtils.createYangNamespaceContext(
91 asts.values(), Optional.<SchemaContext>absent());
93 final ParseTreeWalker walker = new ParseTreeWalker();
94 final Map<SourceIdentifier, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
96 for (final Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
97 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
98 walker, entry.getValue()).getModuleBuilder();
100 moduleBuilder.setSource(srcs.get(entry.getKey()).getYangText());
101 sourceToBuilder.put(entry.getKey(), moduleBuilder);
103 LOG.debug("Modules ready for integration");
105 final YangParserImpl parser = YangParserImpl.getInstance();
106 final Collection<Module> modules = parser.buildModules(sourceToBuilder.values());
107 LOG.debug("Integrated cross-references modules");
108 return Futures.immediateCheckedFuture(parser.assembleContext(modules));
112 private final SharedSchemaRepository repository;
113 // FIXME: ignored right now
114 private final SchemaSourceFilter filter;
116 // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository (final implementation)
117 public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
118 this.repository = Preconditions.checkNotNull(repository);
119 this.filter = Preconditions.checkNotNull(filter);
123 public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
124 // Make sources unique
125 final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
127 final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
128 if (existing != null) {
129 LOG.debug("Returning cached context {}", existing);
130 return Futures.immediateCheckedFuture(existing);
133 // Request all sources be loaded
134 ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources));
136 // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
137 // Also remove duplicates if present
138 // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
139 sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers));
141 // Assemble sources into a schema context
142 final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
144 // Populate cache when successful
145 Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
147 public void onSuccess(final SchemaContext result) {
148 cache.put(uniqueSourceIdentifiers, result);
152 public void onFailure(final Throwable t) {
153 LOG.debug("Failed to assemble sources", t);
157 return Futures.makeChecked(cf, MAPPER);
161 * @return set (preserving ordering) from the input collection
163 private List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
164 final Set<SourceIdentifier> uniqueSourceIdentifiers = Collections.unmodifiableSet(Sets.newLinkedHashSet(requiredSources));
165 if(uniqueSourceIdentifiers.size() != requiredSources.size()) {
166 LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}", Collections2.filter(uniqueSourceIdentifiers, new Predicate<SourceIdentifier>() {
168 public boolean apply(@Nullable final SourceIdentifier input) {
169 return Iterables.frequency(requiredSources, input) > 1;
173 return Lists.newArrayList(uniqueSourceIdentifiers);
176 private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>, List<ASTSchemaSource>> {
177 private final List<SourceIdentifier> sourceIdentifiers;
179 public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
180 this.sourceIdentifiers = sourceIdentifiers;
184 public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
185 final Map<SourceIdentifier, ASTSchemaSource> filtered = Maps.newLinkedHashMap();
187 for (int i = 0; i < input.size(); i++) {
189 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
190 final ASTSchemaSource astSchemaSource = input.get(i);
191 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
193 if (!expectedSId.equals(realSId)) {
194 LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. Using actual id", expectedSId.getName(), expectedSId, realSId);
197 if (filtered.containsKey(realSId)) {
198 LOG.warn("Duplicate source for module {} detected in reactor", realSId);
201 filtered.put(realSId, astSchemaSource);
204 return Lists.newArrayList(filtered.values());