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