2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.collect.HashBasedTable;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Table;
17 import com.google.common.collect.TreeBasedTable;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.Optional;
29 import java.util.SortedMap;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yangtools.util.RecursiveObjectLeaker;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.common.Revision;
35 import org.opendaylight.yangtools.yang.common.YangVersion;
36 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
39 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
40 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
41 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.Registry;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
55 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
56 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
57 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
58 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
59 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
61 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
62 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
63 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
68 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
70 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER =
71 ImmutableList.<ModelProcessingPhase>builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
72 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
73 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
75 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
76 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
77 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
78 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
79 private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
80 private final Set<SourceSpecificContext> sources = new HashSet<>();
81 private final Set<YangVersion> supportedVersions;
82 private final boolean enabledSemanticVersions;
84 private Set<SourceSpecificContext> libSources = new HashSet<>();
85 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
86 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
88 BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
89 final Map<ValidationBundleType, Collection<?>> supportedValidation,
90 final StatementParserMode statementParserMode) {
91 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
93 switch (statementParserMode) {
95 enabledSemanticVersions = false;
98 enabledSemanticVersions = true;
101 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
104 for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
105 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
108 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
111 boolean isEnabledSemanticVersioning() {
112 return enabledSemanticVersions;
115 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
116 return supports.get(currentPhase);
119 void addSource(@Nonnull final StatementStreamSource source) {
120 sources.add(new SourceSpecificContext(this, source));
123 void addLibSource(@Nonnull final StatementStreamSource libSource) {
124 Preconditions.checkState(!isEnabledSemanticVersioning(),
125 "Library sources are not supported in semantic version mode currently.");
126 Preconditions.checkState(currentPhase == ModelProcessingPhase.INIT,
127 "Add library source is allowed in ModelProcessingPhase.INIT only");
128 libSources.add(new SourceSpecificContext(this, libSource));
131 void setSupportedFeatures(final Set<QName> supportedFeatures) {
132 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
133 ImmutableSet.copyOf(supportedFeatures));
136 void setModulesDeviatedByModules(final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules) {
137 addToNs(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
138 ImmutableMap.copyOf(modulesDeviatedByModules));
142 public StorageNodeType getStorageNodeType() {
143 return StorageNodeType.GLOBAL;
147 public NamespaceStorageNode getParentNamespaceStorage() {
152 public NamespaceBehaviour.Registry getBehaviourRegistry() {
157 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
158 final Class<N> type) {
159 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
160 if (potential == null) {
161 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
162 if (potentialRaw != null) {
163 potential = createNamespaceContext(potentialRaw);
164 supportedNamespaces.put(type, potential);
166 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
171 Verify.verify(type.equals(potential.getIdentifier()));
173 * Safe cast, previous checkState checks equivalence of key from which
174 * type argument are derived
176 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
179 @SuppressWarnings({ "unchecked", "rawtypes" })
180 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
181 final NamespaceBehaviour<K, V, N> potentialRaw) {
182 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
183 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
184 (DerivedNamespaceBehaviour) potentialRaw);
185 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
187 return derivedContext;
189 return new SimpleNamespaceContext<>(potentialRaw);
192 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
193 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
194 if (potential == null) {
195 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
197 if (potentialRaw != null) {
198 potential = new StatementDefinitionContext<>(potentialRaw);
199 definitions.put(version, name, potential);
205 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
206 return modelDefinedStmtDefs.get(name);
209 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
210 modelDefinedStmtDefs.put(name, def);
213 private void executePhases() throws ReactorException {
214 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
216 loadPhaseStatements();
217 completePhaseActions();
222 EffectiveModelContext build() throws ReactorException {
227 EffectiveSchemaContext buildEffective() throws ReactorException {
229 return transformEffective();
232 private EffectiveModelContext transform() {
233 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
234 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
235 for (final SourceSpecificContext source : sources) {
236 rootStatements.add(source.getRoot().buildDeclared());
238 return new EffectiveModelContext(rootStatements);
241 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
242 final RuntimeException cause) throws SomeModifiersUnresolvedException {
243 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(source.getRoot());
244 if (!(cause instanceof SourceException)) {
246 * This should not be happening as all our processing should provide SourceExceptions.
247 * We will wrap the exception to provide enough information to identify the problematic model,
248 * but also emit a warning so the offending codepath will get fixed.
250 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
254 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
257 @SuppressWarnings("checkstyle:illegalCatch")
258 private EffectiveSchemaContext transformEffective() throws ReactorException {
259 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
260 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
261 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
264 for (final SourceSpecificContext source : sources) {
265 final RootStatementContext<?, ?, ?> root = source.getRoot();
267 rootStatements.add(root.buildDeclared());
268 rootEffectiveStatements.add(root.buildEffective());
269 } catch (final RuntimeException ex) {
270 throw propagateException(source, ex);
274 RecursiveObjectLeaker.cleanup();
277 sealMutableStatements();
278 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
281 private void startPhase(final ModelProcessingPhase phase) {
282 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
283 startPhaseFor(phase, sources);
284 startPhaseFor(phase, libSources);
286 currentPhase = phase;
287 LOG.debug("Global phase {} started", phase);
290 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
291 for (final SourceSpecificContext source : sources) {
292 source.startPhase(phase);
296 private void loadPhaseStatements() throws ReactorException {
297 Preconditions.checkState(currentPhase != null);
298 loadPhaseStatementsFor(sources);
299 loadPhaseStatementsFor(libSources);
302 @SuppressWarnings("checkstyle:illegalCatch")
303 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> sources) throws ReactorException {
304 for (final SourceSpecificContext source : sources) {
306 source.loadStatements();
307 } catch (final RuntimeException ex) {
308 throw propagateException(source, ex);
313 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
314 boolean addedCause = false;
315 SomeModifiersUnresolvedException buildFailure = null;
316 for (final SourceSpecificContext failedSource : sourcesToProgress) {
317 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
318 if (!optSourceEx.isPresent()) {
322 final SourceException sourceEx = optSourceEx.get();
323 // Workaround for broken logging implementations which ignore
324 // suppressed exceptions
325 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
326 if (LOG.isDebugEnabled()) {
327 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
329 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
332 final Throwable[] suppressed = sourceEx.getSuppressed();
333 if (suppressed.length > 0) {
334 LOG.error("{} additional errors reported:", suppressed.length);
337 for (final Throwable t : suppressed) {
338 // FIXME: this should be configured in the appender, really
339 if (LOG.isDebugEnabled()) {
340 LOG.error("Error {}: {}", count, t.getMessage(), t);
342 LOG.error("Error {}: {}", count, t.getMessage());
351 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(failedSource.getRoot());
352 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
354 buildFailure.addSuppressed(sourceEx);
360 @SuppressWarnings("checkstyle:illegalCatch")
361 private void completePhaseActions() throws ReactorException {
362 Preconditions.checkState(currentPhase != null);
363 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
364 if (!libSources.isEmpty()) {
365 Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
366 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
367 + "but current phase was %s", currentPhase);
368 sourcesToProgress.addAll(libSources);
371 boolean progressing = true;
372 while (progressing) {
373 // We reset progressing to false.
375 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
376 while (currentSource.hasNext()) {
377 final SourceSpecificContext nextSourceCtx = currentSource.next();
379 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
380 switch (sourceProgress) {
382 currentSource.remove();
383 // we were able to make progress in computation
393 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
395 } catch (final RuntimeException ex) {
396 throw propagateException(nextSourceCtx, ex);
401 if (!libSources.isEmpty()) {
402 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
403 sources.addAll(requiredLibs);
404 libSources = ImmutableSet.of();
406 * We want to report errors of relevant sources only, so any others can
409 sourcesToProgress.retainAll(sources);
412 if (!sourcesToProgress.isEmpty()) {
413 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
414 if (buildFailure != null) {
420 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
421 Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
422 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
423 + " but current phase was %s", currentPhase);
424 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
425 String::compareTo, Revision::compare);
426 for (final SourceSpecificContext libSource : libSources) {
427 final ModuleIdentifier libSourceIdentifier = Preconditions.checkNotNull(libSource.getRootIdentifier());
428 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
431 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
432 for (final SourceSpecificContext source : sources) {
433 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
434 removeConflictingLibSources(source, requiredLibs);
439 private void collectRequiredSourcesFromLib(
440 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
441 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
442 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
443 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
444 if (libSource != null && requiredLibs.add(libSource)) {
445 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
450 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
451 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
452 return requiredSource.getRevision() == null ? getLatestRevision(libSourcesTable.row(requiredSource.getName()))
453 : libSourcesTable.get(requiredSource.getName(),
454 Optional.of(Revision.valueOf(requiredSource.getRevision())));
457 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
458 SourceSpecificContext> sourceMap) {
459 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
462 // removes required library sources which would cause namespace/name conflict with one of the main sources
463 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
464 // and the same parent module or submodule is added as one of the library sources.
465 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
466 // as its argument and the same dir is specified as one of the library dirs through -p option).
467 private static void removeConflictingLibSources(final SourceSpecificContext source,
468 final Set<SourceSpecificContext> requiredLibs) {
469 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
470 while (requiredLibsIter.hasNext()) {
471 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
472 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
473 requiredLibsIter.remove();
478 private void endPhase(final ModelProcessingPhase phase) {
479 Preconditions.checkState(currentPhase == phase);
480 finishedPhase = currentPhase;
481 LOG.debug("Global phase {} finished", phase);
484 Set<SourceSpecificContext> getSources() {
488 public Set<YangVersion> getSupportedVersions() {
489 return supportedVersions;
492 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
493 mutableStatementsToSeal.add(mutableStatement);
496 void sealMutableStatements() {
497 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
498 mutableStatement.seal();
500 mutableStatementsToSeal.clear();