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 static com.google.common.base.Preconditions.checkState;
11 import static java.util.Objects.requireNonNull;
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;
29 import java.util.Objects;
30 import java.util.Optional;
32 import java.util.SortedMap;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.opendaylight.yangtools.util.RecursiveObjectLeaker;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.QNameModule;
37 import org.opendaylight.yangtools.yang.common.Revision;
38 import org.opendaylight.yangtools.yang.common.YangVersion;
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.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.StmtContextUtils;
57 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
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.source.SupportedFeaturesNamespace.SupportedFeatures;
63 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
65 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
69 class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
70 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
72 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER =
73 ImmutableList.<ModelProcessingPhase>builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
74 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
75 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
77 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
78 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
79 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
80 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
81 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
82 private final Set<SourceSpecificContext> sources = new HashSet<>();
83 private final ImmutableSet<YangVersion> supportedVersions;
84 private final boolean enabledSemanticVersions;
86 private Set<SourceSpecificContext> libSources = new HashSet<>();
87 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
88 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
90 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
91 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
92 final StatementParserMode statementParserMode) {
93 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
95 switch (statementParserMode) {
97 enabledSemanticVersions = false;
100 enabledSemanticVersions = true;
103 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
106 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
108 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
111 boolean isEnabledSemanticVersioning() {
112 return enabledSemanticVersions;
115 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
116 return supports.get(phase);
119 void addSource(final @NonNull StatementStreamSource source) {
120 sources.add(new SourceSpecificContext(this, source));
123 void addLibSource(final @NonNull StatementStreamSource libSource) {
124 checkState(!isEnabledSemanticVersioning(),
125 "Library sources are not supported in semantic version mode currently.");
126 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 addToNamespace(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
133 ImmutableSet.copyOf(supportedFeatures));
136 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
137 addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
138 ImmutableSetMultimap.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 ReactorDeclaredModel build() throws ReactorException {
227 EffectiveSchemaContext buildEffective() throws ReactorException {
229 return transformEffective();
232 private ReactorDeclaredModel transform() {
233 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 ReactorDeclaredModel(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 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 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 checkState(currentPhase != null);
298 loadPhaseStatementsFor(sources);
299 loadPhaseStatementsFor(libSources);
302 @SuppressWarnings("checkstyle:illegalCatch")
303 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
304 for (final SourceSpecificContext source : srcs) {
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.isEmpty()) {
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 LOG.error("Error {}: {}", count, t.getMessage());
345 final SourceIdentifier sourceId = StmtContextUtils.createSourceIdentifier(failedSource.getRoot());
346 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
348 buildFailure.addSuppressed(sourceEx);
354 @SuppressWarnings("checkstyle:illegalCatch")
355 private void completePhaseActions() throws ReactorException {
356 checkState(currentPhase != null);
357 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
358 if (!libSources.isEmpty()) {
359 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
360 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
361 + "but current phase was %s", currentPhase);
362 sourcesToProgress.addAll(libSources);
365 boolean progressing = true;
366 while (progressing) {
367 // We reset progressing to false.
369 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
370 while (currentSource.hasNext()) {
371 final SourceSpecificContext nextSourceCtx = currentSource.next();
373 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
374 switch (sourceProgress) {
376 currentSource.remove();
377 // we were able to make progress in computation
387 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
389 } catch (final RuntimeException ex) {
390 throw propagateException(nextSourceCtx, ex);
395 if (!libSources.isEmpty()) {
396 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
397 sources.addAll(requiredLibs);
398 libSources = ImmutableSet.of();
400 * We want to report errors of relevant sources only, so any others can
403 sourcesToProgress.retainAll(sources);
406 if (!sourcesToProgress.isEmpty()) {
407 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
408 if (buildFailure != null) {
414 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
415 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
416 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
417 + " but current phase was %s", currentPhase);
418 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
419 String::compareTo, Revision::compare);
420 for (final SourceSpecificContext libSource : libSources) {
421 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
422 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
425 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
426 for (final SourceSpecificContext source : sources) {
427 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
428 removeConflictingLibSources(source, requiredLibs);
433 private void collectRequiredSourcesFromLib(
434 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
435 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
436 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
437 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
438 if (libSource != null && requiredLibs.add(libSource)) {
439 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
444 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
445 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
446 return requiredSource.getRevision().isPresent()
447 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
448 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
451 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
452 SourceSpecificContext> sourceMap) {
453 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
456 // removes required library sources which would cause namespace/name conflict with one of the main sources
457 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
458 // and the same parent module or submodule is added as one of the library sources.
459 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
460 // as its argument and the same dir is specified as one of the library dirs through -p option).
461 private static void removeConflictingLibSources(final SourceSpecificContext source,
462 final Set<SourceSpecificContext> requiredLibs) {
463 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
464 while (requiredLibsIter.hasNext()) {
465 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
466 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
467 requiredLibsIter.remove();
472 private void endPhase(final ModelProcessingPhase phase) {
473 checkState(currentPhase == phase);
474 finishedPhase = currentPhase;
475 LOG.debug("Global phase {} finished", phase);
478 Set<SourceSpecificContext> getSources() {
482 public Set<YangVersion> getSupportedVersions() {
483 return supportedVersions;
486 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
487 mutableStatementsToSeal.add(mutableStatement);
490 void sealMutableStatements() {
491 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
492 mutableStatement.seal();
494 mutableStatementsToSeal.clear();