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