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