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