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