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