0288d7afec7ca1dbaae98c0c30087e6391f1396b
[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.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;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.Set;
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;
52
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);
57
58     private final Cache<Collection<SourceIdentifier>, SchemaContext> cache = CacheBuilder.newBuilder().weakValues()
59             .build();
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;
65
66     // FIXME SchemaRepository should be the type for repository parameter instead of SharedSchemaRepository
67     //       (final implementation)
68     public SharedSchemaContextFactory(final SharedSchemaRepository repository, final SchemaSourceFilter filter) {
69         this.repository = Preconditions.checkNotNull(repository);
70         this.filter = Preconditions.checkNotNull(filter);
71     }
72
73     @Override
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));
80     }
81
82     private ListenableFuture<ASTSchemaSource> requestSource(final SourceIdentifier identifier) {
83         return repository.getSchemaSource(identifier, ASTSchemaSource.class);
84     }
85
86     private CheckedFuture<SchemaContext, SchemaResolutionException> createSchemaContext(
87             final Collection<SourceIdentifier> requiredSources,
88             final Cache<Collection<SourceIdentifier>, SchemaContext> cache,
89             final AsyncFunction<List<ASTSchemaSource>, SchemaContext> assembleSources) {
90         // Make sources unique
91         final List<SourceIdentifier> uniqueSourceIdentifiers = deDuplicateSources(requiredSources);
92
93         final SchemaContext existing = cache.getIfPresent(uniqueSourceIdentifiers);
94         if (existing != null) {
95             LOG.debug("Returning cached context {}", existing);
96             return Futures.immediateCheckedFuture(existing);
97         }
98
99         // Request all sources be loaded
100         ListenableFuture<List<ASTSchemaSource>> sf = Futures.allAsList(Collections2.transform(uniqueSourceIdentifiers,
101             this::requestSource));
102
103         // Detect mismatch between requested Source IDs and IDs that are extracted from parsed source
104         // Also remove duplicates if present
105         // We are relying on preserved order of uniqueSourceIdentifiers as well as sf
106         sf = Futures.transform(sf, new SourceIdMismatchDetector(uniqueSourceIdentifiers),
107             MoreExecutors.directExecutor());
108
109         // Assemble sources into a schema context
110         final ListenableFuture<SchemaContext> cf = Futures.transformAsync(sf, assembleSources,
111             MoreExecutors.directExecutor());
112
113         // Populate cache when successful
114         Futures.addCallback(cf, new FutureCallback<SchemaContext>() {
115             @Override
116             public void onSuccess(final SchemaContext result) {
117                 cache.put(uniqueSourceIdentifiers, result);
118             }
119
120             @Override
121             public void onFailure(@Nonnull final Throwable t) {
122                 LOG.debug("Failed to assemble sources", t);
123             }
124         }, MoreExecutors.directExecutor());
125
126         return Futures.makeChecked(cf, MAPPER);
127     }
128
129     /**
130      * @return set (preserving ordering) from the input collection
131      */
132     private static List<SourceIdentifier> deDuplicateSources(final Collection<SourceIdentifier> requiredSources) {
133         final Set<SourceIdentifier> uniqueSourceIdentifiers = new LinkedHashSet<>(requiredSources);
134         if (uniqueSourceIdentifiers.size() == requiredSources.size()) {
135             // Can potentially reuse input
136             return ImmutableList.copyOf(requiredSources);
137         }
138
139         LOG.warn("Duplicate sources requested for schema context, removed duplicate sources: {}",
140             Collections2.filter(uniqueSourceIdentifiers, input -> Iterables.frequency(requiredSources, input) > 1));
141         return ImmutableList.copyOf(uniqueSourceIdentifiers);
142     }
143
144     private static final class SourceIdMismatchDetector implements Function<List<ASTSchemaSource>,
145             List<ASTSchemaSource>> {
146         private final List<SourceIdentifier> sourceIdentifiers;
147
148         public SourceIdMismatchDetector(final List<SourceIdentifier> sourceIdentifiers) {
149             this.sourceIdentifiers = Preconditions.checkNotNull(sourceIdentifiers);
150         }
151
152         @Override
153         public List<ASTSchemaSource> apply(final List<ASTSchemaSource> input) {
154             final Map<SourceIdentifier, ASTSchemaSource> filtered = new LinkedHashMap<>();
155
156             for (int i = 0; i < input.size(); i++) {
157
158                 final SourceIdentifier expectedSId = sourceIdentifiers.get(i);
159                 final ASTSchemaSource astSchemaSource = input.get(i);
160                 final SourceIdentifier realSId = astSchemaSource.getIdentifier();
161
162                 if (!expectedSId.equals(realSId)) {
163                     LOG.warn("Source identifier mismatch for module \"{}\", requested as {} but actually is {}. "
164                         + "Using actual id", expectedSId.getName(), expectedSId, realSId);
165                 }
166
167                 if (filtered.containsKey(realSId)) {
168                     LOG.warn("Duplicate source for module {} detected in reactor", realSId);
169                 }
170
171                 filtered.put(realSId, astSchemaSource);
172
173             }
174             return ImmutableList.copyOf(filtered.values());
175         }
176     }
177
178     private static final class AssembleSources implements AsyncFunction<List<ASTSchemaSource>, SchemaContext> {
179
180         private final Optional<Set<QName>> supportedFeatures;
181         private final StatementParserMode statementParserMode;
182         private final Function<ASTSchemaSource, SourceIdentifier> getIdentifier;
183
184         private AssembleSources(final Optional<Set<QName>> supportedFeatures,
185                 final StatementParserMode statementParserMode) {
186             this.supportedFeatures = supportedFeatures;
187             this.statementParserMode = Preconditions.checkNotNull(statementParserMode);
188             switch (statementParserMode) {
189             case SEMVER_MODE:
190                 this.getIdentifier = ASTSchemaSource::getSemVerIdentifier;
191                 break;
192             default:
193                 this.getIdentifier = ASTSchemaSource::getIdentifier;
194             }
195         }
196
197         @Override
198         public ListenableFuture<SchemaContext> apply(@Nonnull final List<ASTSchemaSource> sources)
199                 throws SchemaResolutionException, ReactorException {
200             final Map<SourceIdentifier, ASTSchemaSource> srcs = Maps.uniqueIndex(sources, getIdentifier);
201             final Map<SourceIdentifier, YangModelDependencyInfo> deps =
202                     Maps.transformValues(srcs, ASTSchemaSource::getDependencyInformation);
203
204             LOG.debug("Resolving dependency reactor {}", deps);
205
206             final DependencyResolver res = this.statementParserMode == StatementParserMode.SEMVER_MODE
207                     ? SemVerDependencyResolver.create(deps) : RevisionDependencyResolver.create(deps);
208             if (!res.getUnresolvedSources().isEmpty()) {
209                 LOG.debug("Omitting models {} due to unsatisfied imports {}", res.getUnresolvedSources(),
210                     res.getUnsatisfiedImports());
211                 throw new SchemaResolutionException("Failed to resolve required models",
212                         res.getResolvedSources(), res.getUnsatisfiedImports());
213             }
214
215             final Map<SourceIdentifier, ParserRuleContext> asts = Maps.transformValues(srcs, ASTSchemaSource::getAST);
216             final CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR.newBuild(
217                 statementParserMode, supportedFeatures);
218
219             for (final Entry<SourceIdentifier, ParserRuleContext> e : asts.entrySet()) {
220                 final ParserRuleContext parserRuleCtx = e.getValue();
221                 Preconditions.checkArgument(parserRuleCtx instanceof StatementContext,
222                         "Unsupported context class %s for source %s", parserRuleCtx.getClass(), e.getKey());
223
224                 reactor.addSource(new YangStatementSourceImpl(e.getKey(), (StatementContext) parserRuleCtx));
225             }
226
227             final SchemaContext schemaContext;
228             try {
229                 schemaContext = reactor.buildEffective();
230             } catch (final ReactorException ex) {
231                 throw new SchemaResolutionException("Failed to resolve required models", ex.getSourceIdentifier(), ex);
232             }
233
234             return Futures.immediateCheckedFuture(schemaContext);
235         }
236     }
237 }