ebe602d5a72c42a06fec63899b8d63a0d8b9d2ce
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / repo / SharedSchemaContextFactory.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.repo;
9
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;
26 import java.net.URI;
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;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.Set;
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;
55
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);
59
60     private final Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>> requestSources = new Function<SourceIdentifier, ListenableFuture<ASTSchemaSource>>() {
61         @Override
62         public ListenableFuture<ASTSchemaSource> apply(final SourceIdentifier input) {
63             return repository.getSchemaSource(input, ASTSchemaSource.class);
64         }
65     };
66     private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues().build();
67
68     private final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources = new AsyncFunction<List<ASTSchemaSource>, SchemaContext>() {
69         @Override
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);
75
76             LOG.debug("Resolving dependency reactor {}", deps);
77
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());
81
82                 // FIXME: push into DependencyResolver
83
84                 throw new SchemaResolutionException("Failed to resolve required models",
85                         res.getResolvedSources(), res.getUnsatisfiedImports());
86             }
87
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());
92
93             final ParseTreeWalker walker = new ParseTreeWalker();
94             final Map<SourceIdentifier, ModuleBuilder> sourceToBuilder = new LinkedHashMap<>();
95
96             for (final Entry<SourceIdentifier, ParserRuleContext> entry : asts.entrySet()) {
97                 final ModuleBuilder moduleBuilder = YangParserListenerImpl.create(namespaceContext, entry.getKey().getName(),
98                         walker, entry.getValue()).getModuleBuilder();
99
100                 moduleBuilder.setSource(srcs.get(entry.getKey()).getYangText());
101                 sourceToBuilder.put(entry.getKey(), moduleBuilder);
102             }
103             LOG.debug("Modules ready for integration");
104
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));
109         }
110     };
111
112     private final SharedSchemaRepository repository;
113     // FIXME: ignored right now
114     private final SchemaSourceFilter filter;
115
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);
120     }
121
122     @Override
123     public CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(final Collection<SourceIdentifier> requiredSources) {
124         // Make sources unique
125         final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
126
127         final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
128         if (existing != null) {
129             LOG.debug("Returning cached context {}", existing);
130             return Futures.immediateCheckedFuture(existing);
131         }
132
133         // Request all sources be loaded
134         ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers, requestSources));
135
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));
140
141         // Assemble sources into a schema context
142         final ListenableFuture<SchemaContext> cf = Futures.transform(sf, assembleSources);
143
144         // Populate cache when successful
145         Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
146             @Override
147             public void onSuccess(final SchemaContext result) {
148                 cache.put(uniqueSourceIdentifiers, result);
149             }
150
151             @Override
152             public void onFailure(final Throwable t) {
153                 LOG.debug("Failed to assemble sources", t);
154             }
155         });
156
157         return Futures.makeChecked(cf, MAPPER);
158     }
159
160     /**
161      * @return set (preserving ordering) from the input collection
162      */
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>() {
167                 @Override
168                 public boolean apply(@Nullable final SourceIdentifier input) {
169                     return Iterables.frequency(requiredSources, input) > 1;
170                 }
171             }));
172         }
173         return Lists.newArrayList(uniqueSourceIdentifiers);
174     }
175
176     private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>, List<ASTSchemaSource>> {
177         private final List<SourceIdentifier> sourceIdentifiers;
178
179         public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
180             this.sourceIdentifiers = sourceIdentifiers;
181         }
182
183         @Override
184         public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
185             final Map<SourceIdentifier, ASTSchemaSource> filtered = Maps.newLinkedHashMap();
186
187             for (int i = 0; i < input.size(); i++) {
188
189                 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
190                 final ASTSchemaSource astSchemaSource = input.get(i);
191                 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
192
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);
195                 }
196
197                 if (filtered.containsKey(realSId)) {
198                     LOG.warn("Duplicate source for module {} detected in reactor", realSId);
199                 }
200
201                 filtered.put(realSId, astSchemaSource);
202
203             }
204             return Lists.newArrayList(filtered.values());
205         }
206     }
207 }