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.Lists;
17 import com.google.common.collect.Table;
18 import com.google.common.collect.TreeBasedTable;
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.Date;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import java.util.Objects;
29 import java.util.Optional;
31 import java.util.SortedMap;
32 import javax.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.SimpleDateFormatUtil;
37 import org.opendaylight.yangtools.yang.common.YangVersion;
38 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
39 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
40 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
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.StorageNodeType;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
52 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
53 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
54 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
55 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
56 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
57 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
58 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
59 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
60 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
61 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
62 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
63 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
64 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
69 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
71 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList
72 .<ModelProcessingPhase> builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
73 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
74 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
76 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
77 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
78 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
79 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
80 private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
81 private final Set<SourceSpecificContext> sources = new HashSet<>();
82 private final Set<YangVersion> supportedVersions;
83 private final boolean enabledSemanticVersions;
85 private Set<SourceSpecificContext> libSources = new HashSet<>();
86 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
87 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
89 BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
90 final Map<ValidationBundleType, Collection<?>> supportedValidation,
91 final StatementParserMode statementParserMode) {
92 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
94 switch (statementParserMode) {
96 enabledSemanticVersions = false;
99 enabledSemanticVersions = true;
102 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
105 for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
106 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
109 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
112 boolean isEnabledSemanticVersioning() {
113 return enabledSemanticVersions;
116 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
117 return supports.get(currentPhase);
120 void addSource(@Nonnull final StatementStreamSource source) {
121 sources.add(new SourceSpecificContext(this, source));
124 void addLibSource(@Nonnull final StatementStreamSource libSource) {
125 Preconditions.checkState(!isEnabledSemanticVersioning(),
126 "Library sources are not supported in semantic version mode currently.");
127 Preconditions.checkState(currentPhase == ModelProcessingPhase.INIT,
128 "Add library source is allowed in ModelProcessingPhase.INIT only");
129 libSources.add(new SourceSpecificContext(this, libSource));
132 void setSupportedFeatures(final Set<QName> supportedFeatures) {
133 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
134 ImmutableSet.copyOf(supportedFeatures));
137 void setModulesDeviatedByModules(final Map<QNameModule, Set<QNameModule>> modulesDeviatedByModules) {
138 addToNs(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
139 ImmutableMap.copyOf(modulesDeviatedByModules));
143 public StorageNodeType getStorageNodeType() {
144 return StorageNodeType.GLOBAL;
148 public NamespaceStorageNode getParentNamespaceStorage() {
153 public NamespaceBehaviour.Registry getBehaviourRegistry() {
158 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
159 final Class<N> type) {
160 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
161 if (potential == null) {
162 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
163 if (potentialRaw != null) {
164 potential = createNamespaceContext(potentialRaw);
165 supportedNamespaces.put(type, potential);
167 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
172 Verify.verify(type.equals(potential.getIdentifier()));
174 * Safe cast, previous checkState checks equivalence of key from which
175 * type argument are derived
177 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
180 @SuppressWarnings({ "unchecked", "rawtypes" })
181 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
182 final NamespaceBehaviour<K, V, N> potentialRaw) {
183 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
184 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
185 (DerivedNamespaceBehaviour) potentialRaw);
186 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
188 return derivedContext;
190 return new SimpleNamespaceContext<>(potentialRaw);
193 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
194 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
195 if (potential == null) {
196 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
198 if (potentialRaw != null) {
199 potential = new StatementDefinitionContext<>(potentialRaw);
200 definitions.put(version, name, potential);
206 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
207 return modelDefinedStmtDefs.get(name);
210 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
211 modelDefinedStmtDefs.put(name, def);
214 private void executePhases() throws ReactorException {
215 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
217 loadPhaseStatements();
218 completePhaseActions();
223 EffectiveModelContext build() throws ReactorException {
228 EffectiveSchemaContext buildEffective() throws ReactorException {
230 return transformEffective();
233 private EffectiveModelContext transform() {
234 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
235 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
236 for (final SourceSpecificContext source : sources) {
237 rootStatements.add(source.getRoot().buildDeclared());
239 return new EffectiveModelContext(rootStatements);
242 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
243 final RuntimeException cause) throws SomeModifiersUnresolvedException {
244 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(source.getRoot());
245 if (!(cause instanceof SourceException)) {
247 * This should not be happening as all our processing should provide SourceExceptions.
248 * We will wrap the exception to provide enough information to identify the problematic model,
249 * but also emit a warning so the offending codepath will get fixed.
251 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
255 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
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 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> sources) throws ReactorException {
303 for (final SourceSpecificContext source : sources) {
305 source.loadStatements();
306 } catch (final RuntimeException ex) {
307 throw propagateException(source, ex);
312 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
313 boolean addedCause = false;
314 SomeModifiersUnresolvedException buildFailure = null;
315 for (final SourceSpecificContext failedSource : sourcesToProgress) {
316 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
317 if (!optSourceEx.isPresent()) {
321 final SourceException sourceEx = optSourceEx.get();
322 // Workaround for broken logging implementations which ignore
323 // suppressed exceptions
324 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
325 if (LOG.isDebugEnabled()) {
326 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
328 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
331 final Throwable[] suppressed = sourceEx.getSuppressed();
332 if (suppressed.length > 0) {
333 LOG.error("{} additional errors reported:", suppressed.length);
336 for (final Throwable t : suppressed) {
337 // FIXME: this should be configured in the appender, really
338 if (LOG.isDebugEnabled()) {
339 LOG.error("Error {}: {}", i, t.getMessage(), t);
341 LOG.error("Error {}: {}", i, t.getMessage());
350 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(failedSource.getRoot());
351 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
353 buildFailure.addSuppressed(sourceEx);
359 private void completePhaseActions() throws ReactorException {
360 Preconditions.checkState(currentPhase != null);
361 final List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
362 if (!libSources.isEmpty()) {
363 Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
364 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
365 + "but current phase was %s", currentPhase);
366 sourcesToProgress.addAll(libSources);
369 boolean progressing = true;
370 while (progressing) {
371 // We reset progressing to false.
373 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
374 while (currentSource.hasNext()) {
375 final SourceSpecificContext nextSourceCtx = currentSource.next();
377 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
378 switch (sourceProgress) {
380 currentSource.remove();
381 // Fallback to progress, since we were able to make
382 // progress in computation
390 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
392 } catch (final RuntimeException ex) {
393 throw propagateException(nextSourceCtx, ex);
398 if (!libSources.isEmpty()) {
399 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
400 sources.addAll(requiredLibs);
401 libSources = ImmutableSet.of();
403 * We want to report errors of relevant sources only, so any others can
406 sourcesToProgress.retainAll(sources);
409 if (!sourcesToProgress.isEmpty()) {
410 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
411 if (buildFailure != null) {
417 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
418 Preconditions.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, Date, SourceSpecificContext> libSourcesTable = TreeBasedTable.create();
422 for (final SourceSpecificContext libSource : libSources) {
423 final ModuleIdentifier libSourceIdentifier = Preconditions.checkNotNull(libSource.getRootIdentifier());
424 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
427 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
428 for (final SourceSpecificContext source : sources) {
429 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
430 removeConflictingLibSources(source, requiredLibs);
435 private void collectRequiredSourcesFromLib(
436 final TreeBasedTable<String, Date, SourceSpecificContext> libSourcesTable,
437 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
438 final Collection<ModuleIdentifier> requiredModules = source.getRequiredModules();
439 for (final ModuleIdentifier requiredModule : requiredModules) {
440 final SourceSpecificContext libSource = getRequiredLibSource(requiredModule, libSourcesTable);
441 if (libSource != null && requiredLibs.add(libSource)) {
442 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
447 private static SourceSpecificContext getRequiredLibSource(final ModuleIdentifier requiredModule,
448 final TreeBasedTable<String, Date, SourceSpecificContext> libSourcesTable) {
449 return requiredModule.getRevision() == SimpleDateFormatUtil.DEFAULT_DATE_IMP
450 || requiredModule.getRevision() == SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE ? getLatestRevision(
451 libSourcesTable.row(requiredModule.getName())) : libSourcesTable.get(requiredModule.getName(),
452 requiredModule.getRevision());
455 private static SourceSpecificContext getLatestRevision(final SortedMap<Date, SourceSpecificContext> sourceMap) {
456 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
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();
475 private void endPhase(final ModelProcessingPhase phase) {
476 Preconditions.checkState(currentPhase == phase);
477 finishedPhase = currentPhase;
478 LOG.debug("Global phase {} finished", phase);
481 Set<SourceSpecificContext> getSources() {
485 public Set<YangVersion> getSupportedVersions() {
486 return supportedVersions;
489 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
490 mutableStatementsToSeal.add(mutableStatement);
493 void sealMutableStatements() {
494 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
495 mutableStatement.seal();
497 mutableStatementsToSeal.clear();