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