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