b55e6b1dc42961013b020e840e9902a70609f91d
[yangtools.git] / parser / yang-parser-reactor / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / BuildGlobalContext.java
1 /*
2  * Copyright (c) 2015 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.stmt.reactor;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.base.Verify;
15 import com.google.common.collect.HashBasedTable;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.ImmutableSet;
18 import com.google.common.collect.ImmutableSetMultimap;
19 import com.google.common.collect.SetMultimap;
20 import com.google.common.collect.Table;
21 import com.google.common.collect.TreeBasedTable;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Objects;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.SortedMap;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.yang.common.Empty;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.common.Revision;
38 import org.opendaylight.yangtools.yang.common.UnresolvedQName.Unqualified;
39 import org.opendaylight.yangtools.yang.common.YangVersion;
40 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
42 import org.opendaylight.yangtools.yang.model.repo.api.FeatureSet;
43 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
44 import org.opendaylight.yangtools.yang.parser.spi.ParserNamespaces;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
56 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
57 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
59 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles;
60 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundles.ValidationBundleType;
61 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
66     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
67
68     private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
69         ModelProcessingPhase.SOURCE_PRE_LINKAGE,
70         ModelProcessingPhase.SOURCE_LINKAGE,
71         ModelProcessingPhase.STATEMENT_DEFINITION,
72         ModelProcessingPhase.FULL_DECLARATION,
73         ModelProcessingPhase.EFFECTIVE_MODEL
74     };
75
76     private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
77     private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
78     private final Map<ParserNamespace<?, ?>, NamespaceBehaviourWithListeners<?, ?>> supportedNamespaces =
79         new HashMap<>();
80     private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
81     private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
82     private final Set<SourceSpecificContext> sources = new HashSet<>();
83     private final ImmutableSet<YangVersion> supportedVersions;
84
85     private Set<SourceSpecificContext> libSources = new HashSet<>();
86     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
87     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
88
89     BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
90             final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation) {
91         this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
92
93         final var behavior = getNamespaceBehaviour(ValidationBundles.NAMESPACE);
94         for (var validationBundle : supportedValidation.entrySet()) {
95             behavior.addTo(this, validationBundle.getKey(), validationBundle.getValue());
96         }
97
98         supportedVersions = ImmutableSet.copyOf(
99             verifyNotNull(supports.get(ModelProcessingPhase.INIT)).getSupportedVersions());
100     }
101
102     StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
103         return supports.get(phase);
104     }
105
106     void addSource(final @NonNull StatementStreamSource source) {
107         sources.add(new SourceSpecificContext(this, source));
108     }
109
110     void addLibSource(final @NonNull StatementStreamSource libSource) {
111         checkState(currentPhase == ModelProcessingPhase.INIT,
112                 "Add library source is allowed in ModelProcessingPhase.INIT only");
113         libSources.add(new SourceSpecificContext(this, libSource));
114     }
115
116     void setSupportedFeatures(final Set<QName> supportedFeatures) {
117         if (supportedFeatures instanceof FeatureSet) {
118             addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), supportedFeatures);
119         } else {
120             addToNamespace(ParserNamespaces.SUPPORTED_FEATURES, Empty.value(), ImmutableSet.copyOf(supportedFeatures));
121         }
122     }
123
124     void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
125         addToNamespace(ParserNamespaces.MODULES_DEVIATED_BY, Empty.value(),
126             ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
127     }
128
129     @Override
130     public StorageNodeType getStorageNodeType() {
131         return StorageNodeType.GLOBAL;
132     }
133
134     @Override
135     public NamespaceStorageNode getParentNamespaceStorage() {
136         return null;
137     }
138
139     @Override
140     Registry getBehaviourRegistry() {
141         return this;
142     }
143
144     @Override
145     public <K, V> NamespaceBehaviourWithListeners<K, V> getNamespaceBehaviour(final ParserNamespace<K, V> type) {
146         NamespaceBehaviourWithListeners<?, ?> potential = supportedNamespaces.get(type);
147         if (potential == null) {
148             final var potentialRaw = verifyNotNull(supports.get(currentPhase)).namespaceBehaviourOf(type);
149             if (potentialRaw != null) {
150                 potential = createNamespaceContext(potentialRaw);
151                 supportedNamespaces.put(type, potential);
152             } else {
153                 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
154                         + currentPhase);
155             }
156         }
157
158         Verify.verify(type.equals(potential.getIdentifier()));
159         /*
160          * Safe cast, previous checkState checks equivalence of key from which
161          * type argument are derived
162          */
163         return (NamespaceBehaviourWithListeners<K, V>) potential;
164     }
165
166     @SuppressWarnings({ "unchecked", "rawtypes" })
167     private <K, V> NamespaceBehaviourWithListeners<K, V> createNamespaceContext(
168             final NamespaceBehaviour<K, V> potentialRaw) {
169         if (potentialRaw instanceof DerivedNamespaceBehaviour derived) {
170             final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(derived);
171             getNamespaceBehaviour(derived.getDerivedFrom()).addDerivedNamespace(derivedContext);
172             return derivedContext;
173         }
174         return new SimpleNamespaceContext<>(potentialRaw);
175     }
176
177     StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
178         StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
179         if (potential == null) {
180             final var potentialRaw = verifyNotNull(supports.get(currentPhase)).getStatementDefinition(version, name);
181             if (potentialRaw != null) {
182                 potential = new StatementDefinitionContext<>(potentialRaw);
183                 definitions.put(version, name, potential);
184             }
185         }
186         return potential;
187     }
188
189     StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
190         return modelDefinedStmtDefs.get(name);
191     }
192
193     void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
194         modelDefinedStmtDefs.put(name, def);
195     }
196
197     private void executePhases() throws ReactorException {
198         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
199             startPhase(phase);
200             loadPhaseStatements();
201             completePhaseActions();
202             endPhase(phase);
203         }
204     }
205
206     ReactorDeclaredModel build() throws ReactorException {
207         executePhases();
208         return transform();
209     }
210
211     EffectiveSchemaContext buildEffective() throws ReactorException {
212         executePhases();
213         return transformEffective();
214     }
215
216     private ReactorDeclaredModel transform() {
217         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
218         final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
219         for (var source : sources) {
220             rootStatements.add(source.declaredRoot());
221         }
222         return new ReactorDeclaredModel(rootStatements);
223     }
224
225     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
226             final RuntimeException cause) throws SomeModifiersUnresolvedException {
227         final SourceIdentifier sourceId = source.identifySource();
228         if (!(cause instanceof SourceException)) {
229             /*
230              * This should not be happening as all our processing should provide SourceExceptions.
231              * We will wrap the exception to provide enough information to identify the problematic model,
232              * but also emit a warning so the offending codepath will get fixed.
233              */
234             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
235                 sourceId, cause);
236         }
237
238         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
239     }
240
241     @SuppressWarnings("checkstyle:illegalCatch")
242     private EffectiveSchemaContext transformEffective() throws ReactorException {
243         checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
244         final var rootStatements = new ArrayList<DeclaredStatement<?>>(sources.size());
245         final var rootEffectiveStatements = new ArrayList<EffectiveStatement<?, ?>>(sources.size());
246
247         for (var source : sources) {
248             try {
249                 rootStatements.add(source.declaredRoot());
250                 rootEffectiveStatements.add(source.effectiveRoot());
251             } catch (final RuntimeException ex) {
252                 throw propagateException(source, ex);
253             }
254         }
255
256         sealMutableStatements();
257         return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
258     }
259
260     private void startPhase(final ModelProcessingPhase phase) {
261         checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
262         startPhaseFor(phase, sources);
263         startPhaseFor(phase, libSources);
264
265         currentPhase = phase;
266         LOG.debug("Global phase {} started", phase);
267     }
268
269     private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
270         for (final SourceSpecificContext source : sources) {
271             source.startPhase(phase);
272         }
273     }
274
275     private void loadPhaseStatements() throws ReactorException {
276         checkState(currentPhase != null);
277         loadPhaseStatementsFor(sources);
278         loadPhaseStatementsFor(libSources);
279     }
280
281     @SuppressWarnings("checkstyle:illegalCatch")
282     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
283         for (final SourceSpecificContext source : srcs) {
284             try {
285                 source.loadStatements();
286             } catch (final RuntimeException ex) {
287                 throw propagateException(source, ex);
288             }
289         }
290     }
291
292     private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
293         boolean addedCause = false;
294         SomeModifiersUnresolvedException buildFailure = null;
295         for (final SourceSpecificContext failedSource : sourcesToProgress) {
296             final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
297             if (optSourceEx.isEmpty()) {
298                 continue;
299             }
300
301             final SourceException sourceEx = optSourceEx.get();
302             // Workaround for broken logging implementations which ignore
303             // suppressed exceptions
304             final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
305             if (LOG.isDebugEnabled()) {
306                 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
307             } else {
308                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
309             }
310
311             final Throwable[] suppressed = sourceEx.getSuppressed();
312             if (suppressed.length > 0) {
313                 LOG.error("{} additional errors reported:", suppressed.length);
314
315                 int count = 1;
316                 for (final Throwable t : suppressed) {
317                     LOG.error("Error {}: {}", count, t.getMessage());
318                     count++;
319                 }
320             }
321
322             if (!addedCause) {
323                 addedCause = true;
324                 final SourceIdentifier sourceId = failedSource.identifySource();
325                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
326             } else {
327                 buildFailure.addSuppressed(sourceEx);
328             }
329         }
330         return buildFailure;
331     }
332
333     @SuppressWarnings("checkstyle:illegalCatch")
334     private void completePhaseActions() throws ReactorException {
335         checkState(currentPhase != null);
336         final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
337         if (!libSources.isEmpty()) {
338             checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
339                     "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
340                             + "but current phase was %s", currentPhase);
341             sourcesToProgress.addAll(libSources);
342         }
343
344         boolean progressing = true;
345         while (progressing) {
346             // We reset progressing to false.
347             progressing = false;
348             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
349             while (currentSource.hasNext()) {
350                 final SourceSpecificContext nextSourceCtx = currentSource.next();
351                 try {
352                     final PhaseCompletionProgress sourceProgress =
353                         nextSourceCtx.tryToCompletePhase(currentPhase.executionOrder());
354                     switch (sourceProgress) {
355                         case FINISHED:
356                             currentSource.remove();
357                             // we were able to make progress in computation
358                             progressing = true;
359                             break;
360                         case PROGRESS:
361                             progressing = true;
362                             break;
363                         case NO_PROGRESS:
364                             // Noop
365                             break;
366                         default:
367                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
368                     }
369                 } catch (final RuntimeException ex) {
370                     throw propagateException(nextSourceCtx, ex);
371                 }
372             }
373         }
374
375         if (!libSources.isEmpty()) {
376             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
377             sources.addAll(requiredLibs);
378             libSources = ImmutableSet.of();
379             /*
380              * We want to report errors of relevant sources only, so any others can
381              * be removed.
382              */
383             sourcesToProgress.retainAll(sources);
384         }
385
386         if (!sourcesToProgress.isEmpty()) {
387             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
388             if (buildFailure != null) {
389                 throw buildFailure;
390             }
391         }
392     }
393
394     private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
395         checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
396                 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
397                         + " but current phase was %s", currentPhase);
398         final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable =
399             TreeBasedTable.create(Unqualified::compareTo, Revision::compare);
400         for (final SourceSpecificContext libSource : libSources) {
401             final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
402             libSourcesTable.put(libSourceIdentifier.name(),
403                 Optional.ofNullable(libSourceIdentifier.revision()), libSource);
404         }
405
406         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
407         for (final SourceSpecificContext source : sources) {
408             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
409             removeConflictingLibSources(source, requiredLibs);
410         }
411         return requiredLibs;
412     }
413
414     private void collectRequiredSourcesFromLib(
415             final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable,
416             final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
417         for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
418             final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
419             if (libSource != null && requiredLibs.add(libSource)) {
420                 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
421             }
422         }
423     }
424
425     private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
426             final TreeBasedTable<Unqualified, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
427         final var revision = requiredSource.revision();
428         return revision != null ? libSourcesTable.get(requiredSource.name(), Optional.of(revision))
429             : getLatestRevision(libSourcesTable.row(requiredSource.name()));
430     }
431
432     private static SourceSpecificContext getLatestRevision(
433             final SortedMap<Optional<Revision>, SourceSpecificContext> sourceMap) {
434         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
435     }
436
437     // removes required library sources which would cause namespace/name conflict with one of the main sources
438     // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
439     // and the same parent module or submodule is added as one of the library sources.
440     // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
441     // as its argument and the same dir is specified as one of the library dirs through -p option).
442     private static void removeConflictingLibSources(final SourceSpecificContext source,
443             final Set<SourceSpecificContext> requiredLibs) {
444         final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
445         while (requiredLibsIter.hasNext()) {
446             final SourceSpecificContext currentReqSource = requiredLibsIter.next();
447             if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
448                 requiredLibsIter.remove();
449             }
450         }
451     }
452
453     private void endPhase(final ModelProcessingPhase phase) {
454         checkState(currentPhase == phase);
455         finishedPhase = currentPhase;
456         LOG.debug("Global phase {} finished", phase);
457     }
458
459     Set<SourceSpecificContext> getSources() {
460         return sources;
461     }
462
463     public Set<YangVersion> getSupportedVersions() {
464         return supportedVersions;
465     }
466
467     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
468         mutableStatementsToSeal.add(mutableStatement);
469     }
470
471     void sealMutableStatements() {
472         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
473             mutableStatement.seal();
474         }
475         mutableStatementsToSeal.clear();
476     }
477 }