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