BUG-4688: Make SourceIdentifier use Revision
[yangtools.git] / yang / yang-parser-impl / 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 com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.HashBasedTable;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Table;
17 import com.google.common.collect.TreeBasedTable;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.SortedMap;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yangtools.util.RecursiveObjectLeaker;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.common.Revision;
35 import org.opendaylight.yangtools.yang.common.YangVersion;
36 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
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.spi.meta.DerivedNamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
56 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
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.source.SupportedFeaturesNamespace;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
61 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
62 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
63 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
68     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
69
70     private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER =
71             ImmutableList.<ModelProcessingPhase>builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
72             .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
73             .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
74
75     private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
76     private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
77     private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
78     private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
79     private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
80     private final Set<SourceSpecificContext> sources = new HashSet<>();
81     private final Set<YangVersion> supportedVersions;
82     private final boolean enabledSemanticVersions;
83
84     private Set<SourceSpecificContext> libSources = new HashSet<>();
85     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
86     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
87
88     BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
89             final Map<ValidationBundleType, Collection<?>> supportedValidation,
90             final StatementParserMode statementParserMode) {
91         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
92
93         switch (statementParserMode) {
94             case DEFAULT_MODE:
95                 enabledSemanticVersions = false;
96                 break;
97             case SEMVER_MODE:
98                 enabledSemanticVersions = true;
99                 break;
100             default:
101                 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
102         }
103
104         for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
105             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
106         }
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 currentPhase) {
116         return supports.get(currentPhase);
117     }
118
119     void addSource(@Nonnull final StatementStreamSource source) {
120         sources.add(new SourceSpecificContext(this, source));
121     }
122
123     void addLibSource(@Nonnull final StatementStreamSource libSource) {
124         Preconditions.checkState(!isEnabledSemanticVersioning(),
125                 "Library sources are not supported in semantic version mode currently.");
126         Preconditions.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         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
133                     ImmutableSet.copyOf(supportedFeatures));
134     }
135
136     void setModulesDeviatedByModules(final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules) {
137         addToNs(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
138                     ImmutableMap.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     EffectiveModelContext build() throws ReactorException {
223         executePhases();
224         return transform();
225     }
226
227     EffectiveSchemaContext buildEffective() throws ReactorException {
228         executePhases();
229         return transformEffective();
230     }
231
232     private EffectiveModelContext transform() {
233         Preconditions.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 EffectiveModelContext(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         Preconditions.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         Preconditions.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         Preconditions.checkState(currentPhase != null);
298         loadPhaseStatementsFor(sources);
299         loadPhaseStatementsFor(libSources);
300     }
301
302     @SuppressWarnings("checkstyle:illegalCatch")
303     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> sources) throws ReactorException {
304         for (final SourceSpecificContext source : sources) {
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.isPresent()) {
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                     // FIXME: this should be configured in the appender, really
339                     if (LOG.isDebugEnabled()) {
340                         LOG.error("Error {}: {}", count, t.getMessage(), t);
341                     } else {
342                         LOG.error("Error {}: {}", count, t.getMessage());
343                     }
344
345                     count++;
346                 }
347             }
348
349             if (!addedCause) {
350                 addedCause = true;
351                 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(failedSource.getRoot());
352                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
353             } else {
354                 buildFailure.addSuppressed(sourceEx);
355             }
356         }
357         return buildFailure;
358     }
359
360     @SuppressWarnings("checkstyle:illegalCatch")
361     private void completePhaseActions() throws ReactorException {
362         Preconditions.checkState(currentPhase != null);
363         final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
364         if (!libSources.isEmpty()) {
365             Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
366                     "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
367                             + "but current phase was %s", currentPhase);
368             sourcesToProgress.addAll(libSources);
369         }
370
371         boolean progressing = true;
372         while (progressing) {
373             // We reset progressing to false.
374             progressing = false;
375             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
376             while (currentSource.hasNext()) {
377                 final SourceSpecificContext nextSourceCtx = currentSource.next();
378                 try {
379                     final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
380                     switch (sourceProgress) {
381                         case FINISHED:
382                             currentSource.remove();
383                             // we were able to make progress in computation
384                             progressing = true;
385                             break;
386                         case PROGRESS:
387                             progressing = true;
388                             break;
389                         case NO_PROGRESS:
390                             // Noop
391                             break;
392                         default:
393                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
394                     }
395                 } catch (final RuntimeException ex) {
396                     throw propagateException(nextSourceCtx, ex);
397                 }
398             }
399         }
400
401         if (!libSources.isEmpty()) {
402             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
403             sources.addAll(requiredLibs);
404             libSources = ImmutableSet.of();
405             /*
406              * We want to report errors of relevant sources only, so any others can
407              * be removed.
408              */
409             sourcesToProgress.retainAll(sources);
410         }
411
412         if (!sourcesToProgress.isEmpty()) {
413             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
414             if (buildFailure != null) {
415                 throw buildFailure;
416             }
417         }
418     }
419
420     private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
421         Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
422                 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
423                         + " but current phase was %s", currentPhase);
424         final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
425             String::compareTo, Revision::compare);
426         for (final SourceSpecificContext libSource : libSources) {
427             final ModuleIdentifier libSourceIdentifier = Preconditions.checkNotNull(libSource.getRootIdentifier());
428             libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
429         }
430
431         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
432         for (final SourceSpecificContext source : sources) {
433             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
434             removeConflictingLibSources(source, requiredLibs);
435         }
436         return requiredLibs;
437     }
438
439     private void collectRequiredSourcesFromLib(
440             final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
441             final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
442         for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
443             final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
444             if (libSource != null && requiredLibs.add(libSource)) {
445                 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
446             }
447         }
448     }
449
450     private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
451             final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
452         return requiredSource.getRevision().isPresent()
453                 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
454                         : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
455     }
456
457     private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
458             SourceSpecificContext> sourceMap) {
459         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
460     }
461
462     // removes required library sources which would cause namespace/name conflict with one of the main sources
463     // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
464     // and the same parent module or submodule is added as one of the library sources.
465     // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
466     // as its argument and the same dir is specified as one of the library dirs through -p option).
467     private static void removeConflictingLibSources(final SourceSpecificContext source,
468             final Set<SourceSpecificContext> requiredLibs) {
469         final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
470         while (requiredLibsIter.hasNext()) {
471             final SourceSpecificContext currentReqSource = requiredLibsIter.next();
472             if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
473                 requiredLibsIter.remove();
474             }
475         }
476     }
477
478     private void endPhase(final ModelProcessingPhase phase) {
479         Preconditions.checkState(currentPhase == phase);
480         finishedPhase = currentPhase;
481         LOG.debug("Global phase {} finished", phase);
482     }
483
484     Set<SourceSpecificContext> getSources() {
485         return sources;
486     }
487
488     public Set<YangVersion> getSupportedVersions() {
489         return supportedVersions;
490     }
491
492     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
493         mutableStatementsToSeal.add(mutableStatement);
494     }
495
496     void sealMutableStatements() {
497         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
498             mutableStatement.seal();
499         }
500         mutableStatementsToSeal.clear();
501     }
502 }