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.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;
28 import java.util.Objects;
29 import java.util.Optional;
31 import java.util.SortedMap;
32 import org.eclipse.jdt.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.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.api.meta.IdentifierNamespace;
41 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
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.StmtContext;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
58 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
59 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules;
60 import org.opendaylight.yangtools.yang.parser.spi.source.ModulesDeviatedByModules.SupportedModules;
61 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
62 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
63 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
65 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
66 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
67 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 final class BuildGlobalContext extends NamespaceStorageSupport implements Registry {
72 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
74 private static final ModelProcessingPhase[] PHASE_EXECUTION_ORDER = {
75 ModelProcessingPhase.SOURCE_PRE_LINKAGE,
76 ModelProcessingPhase.SOURCE_LINKAGE,
77 ModelProcessingPhase.STATEMENT_DEFINITION,
78 ModelProcessingPhase.FULL_DECLARATION,
79 ModelProcessingPhase.EFFECTIVE_MODEL
82 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
83 private final Map<QName, StatementDefinitionContext<?, ?, ?>> modelDefinedStmtDefs = new HashMap<>();
84 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
85 private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
86 private final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports;
87 private final Set<SourceSpecificContext> sources = new HashSet<>();
88 private final ImmutableSet<YangVersion> supportedVersions;
89 private final boolean enabledSemanticVersions;
91 private Set<SourceSpecificContext> libSources = new HashSet<>();
92 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
93 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
95 BuildGlobalContext(final ImmutableMap<ModelProcessingPhase, StatementSupportBundle> supports,
96 final ImmutableMap<ValidationBundleType, Collection<?>> supportedValidation,
97 final StatementParserMode statementParserMode) {
98 this.supports = requireNonNull(supports, "BuildGlobalContext#supports cannot be null");
100 switch (statementParserMode) {
102 enabledSemanticVersions = false;
105 enabledSemanticVersions = true;
108 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
111 addToNamespace(ValidationBundlesNamespace.class, supportedValidation);
113 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
116 boolean isEnabledSemanticVersioning() {
117 return enabledSemanticVersions;
120 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase phase) {
121 return supports.get(phase);
124 void addSource(final @NonNull StatementStreamSource source) {
125 sources.add(new SourceSpecificContext(this, source));
128 void addLibSource(final @NonNull StatementStreamSource libSource) {
129 checkState(!isEnabledSemanticVersioning(),
130 "Library sources are not supported in semantic version mode currently.");
131 checkState(currentPhase == ModelProcessingPhase.INIT,
132 "Add library source is allowed in ModelProcessingPhase.INIT only");
133 libSources.add(new SourceSpecificContext(this, libSource));
136 void setSupportedFeatures(final Set<QName> supportedFeatures) {
137 addToNamespace(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
138 ImmutableSet.copyOf(supportedFeatures));
141 void setModulesDeviatedByModules(final SetMultimap<QNameModule, QNameModule> modulesDeviatedByModules) {
142 addToNamespace(ModulesDeviatedByModules.class, SupportedModules.SUPPORTED_MODULES,
143 ImmutableSetMultimap.copyOf(modulesDeviatedByModules));
147 public StorageNodeType getStorageNodeType() {
148 return StorageNodeType.GLOBAL;
152 public NamespaceStorageNode getParentNamespaceStorage() {
157 public NamespaceBehaviour.Registry getBehaviourRegistry() {
162 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
163 final Class<N> type) {
164 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
165 if (potential == null) {
166 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
167 if (potentialRaw != null) {
168 potential = createNamespaceContext(potentialRaw);
169 supportedNamespaces.put(type, potential);
171 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
176 Verify.verify(type.equals(potential.getIdentifier()));
178 * Safe cast, previous checkState checks equivalence of key from which
179 * type argument are derived
181 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
184 @SuppressWarnings({ "unchecked", "rawtypes" })
185 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
186 final NamespaceBehaviour<K, V, N> potentialRaw) {
187 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
188 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
189 (DerivedNamespaceBehaviour) potentialRaw);
190 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
192 return derivedContext;
194 return new SimpleNamespaceContext<>(potentialRaw);
197 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
198 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
199 if (potential == null) {
200 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
202 if (potentialRaw != null) {
203 potential = new StatementDefinitionContext<>(potentialRaw);
204 definitions.put(version, name, potential);
210 StatementDefinitionContext<?, ?, ?> getModelDefinedStatementDefinition(final QName name) {
211 return modelDefinedStmtDefs.get(name);
214 void putModelDefinedStatementDefinition(final QName name, final StatementDefinitionContext<?, ?, ?> def) {
215 modelDefinedStmtDefs.put(name, def);
218 private void executePhases() throws ReactorException {
219 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
221 loadPhaseStatements();
222 completePhaseActions();
227 ReactorDeclaredModel build() throws ReactorException {
232 EffectiveSchemaContext buildEffective() throws ReactorException {
234 return transformEffective();
237 private ReactorDeclaredModel transform() {
238 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
239 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
240 for (final SourceSpecificContext source : sources) {
241 rootStatements.add(source.getRoot().buildDeclared());
243 return new ReactorDeclaredModel(rootStatements);
246 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
247 final RuntimeException cause) throws SomeModifiersUnresolvedException {
248 final SourceIdentifier sourceId = createSourceIdentifier(source.getRoot());
249 if (!(cause instanceof SourceException)) {
251 * This should not be happening as all our processing should provide SourceExceptions.
252 * We will wrap the exception to provide enough information to identify the problematic model,
253 * but also emit a warning so the offending codepath will get fixed.
255 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
259 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
262 private static SourceIdentifier createSourceIdentifier(final StmtContext<?, ?, ?> root) {
263 final QNameModule qNameModule = root.getFromNamespace(ModuleCtxToModuleQName.class, root);
264 final String arg = root.coerceRawStatementArgument();
265 if (qNameModule != null) {
266 // creates SourceIdentifier for a module
267 return RevisionSourceIdentifier.create(arg, qNameModule.getRevision());
270 // creates SourceIdentifier for a submodule
271 return RevisionSourceIdentifier.create(arg, StmtContextUtils.getLatestRevision(root.declaredSubstatements()));
274 @SuppressWarnings("checkstyle:illegalCatch")
275 private EffectiveSchemaContext transformEffective() throws ReactorException {
276 checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
277 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
278 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
281 for (final SourceSpecificContext source : sources) {
282 final RootStatementContext<?, ?, ?> root = source.getRoot();
284 rootStatements.add(root.buildDeclared());
285 rootEffectiveStatements.add(root.buildEffective());
286 } catch (final RuntimeException ex) {
287 throw propagateException(source, ex);
291 RecursiveObjectLeaker.cleanup();
294 sealMutableStatements();
295 return EffectiveSchemaContext.create(rootStatements, rootEffectiveStatements);
298 private void startPhase(final ModelProcessingPhase phase) {
299 checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
300 startPhaseFor(phase, sources);
301 startPhaseFor(phase, libSources);
303 currentPhase = phase;
304 LOG.debug("Global phase {} started", phase);
307 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
308 for (final SourceSpecificContext source : sources) {
309 source.startPhase(phase);
313 private void loadPhaseStatements() throws ReactorException {
314 checkState(currentPhase != null);
315 loadPhaseStatementsFor(sources);
316 loadPhaseStatementsFor(libSources);
319 @SuppressWarnings("checkstyle:illegalCatch")
320 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> srcs) throws ReactorException {
321 for (final SourceSpecificContext source : srcs) {
323 source.loadStatements();
324 } catch (final RuntimeException ex) {
325 throw propagateException(source, ex);
330 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
331 boolean addedCause = false;
332 SomeModifiersUnresolvedException buildFailure = null;
333 for (final SourceSpecificContext failedSource : sourcesToProgress) {
334 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
335 if (optSourceEx.isEmpty()) {
339 final SourceException sourceEx = optSourceEx.get();
340 // Workaround for broken logging implementations which ignore
341 // suppressed exceptions
342 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
343 if (LOG.isDebugEnabled()) {
344 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
346 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
349 final Throwable[] suppressed = sourceEx.getSuppressed();
350 if (suppressed.length > 0) {
351 LOG.error("{} additional errors reported:", suppressed.length);
354 for (final Throwable t : suppressed) {
355 LOG.error("Error {}: {}", count, t.getMessage());
362 final SourceIdentifier sourceId = createSourceIdentifier(failedSource.getRoot());
363 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
365 buildFailure.addSuppressed(sourceEx);
371 @SuppressWarnings("checkstyle:illegalCatch")
372 private void completePhaseActions() throws ReactorException {
373 checkState(currentPhase != null);
374 final List<SourceSpecificContext> sourcesToProgress = new ArrayList<>(sources);
375 if (!libSources.isEmpty()) {
376 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
377 "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
378 + "but current phase was %s", currentPhase);
379 sourcesToProgress.addAll(libSources);
382 boolean progressing = true;
383 while (progressing) {
384 // We reset progressing to false.
386 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
387 while (currentSource.hasNext()) {
388 final SourceSpecificContext nextSourceCtx = currentSource.next();
390 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
391 switch (sourceProgress) {
393 currentSource.remove();
394 // we were able to make progress in computation
404 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
406 } catch (final RuntimeException ex) {
407 throw propagateException(nextSourceCtx, ex);
412 if (!libSources.isEmpty()) {
413 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
414 sources.addAll(requiredLibs);
415 libSources = ImmutableSet.of();
417 * We want to report errors of relevant sources only, so any others can
420 sourcesToProgress.retainAll(sources);
423 if (!sourcesToProgress.isEmpty()) {
424 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
425 if (buildFailure != null) {
431 private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
432 checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
433 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
434 + " but current phase was %s", currentPhase);
435 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable = TreeBasedTable.create(
436 String::compareTo, Revision::compare);
437 for (final SourceSpecificContext libSource : libSources) {
438 final SourceIdentifier libSourceIdentifier = requireNonNull(libSource.getRootIdentifier());
439 libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
442 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
443 for (final SourceSpecificContext source : sources) {
444 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
445 removeConflictingLibSources(source, requiredLibs);
450 private void collectRequiredSourcesFromLib(
451 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable,
452 final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
453 for (final SourceIdentifier requiredSource : source.getRequiredSources()) {
454 final SourceSpecificContext libSource = getRequiredLibSource(requiredSource, libSourcesTable);
455 if (libSource != null && requiredLibs.add(libSource)) {
456 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
461 private static SourceSpecificContext getRequiredLibSource(final SourceIdentifier requiredSource,
462 final TreeBasedTable<String, Optional<Revision>, SourceSpecificContext> libSourcesTable) {
463 return requiredSource.getRevision().isPresent()
464 ? libSourcesTable.get(requiredSource.getName(), requiredSource.getRevision())
465 : getLatestRevision(libSourcesTable.row(requiredSource.getName()));
468 private static SourceSpecificContext getLatestRevision(final SortedMap<Optional<Revision>,
469 SourceSpecificContext> sourceMap) {
470 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
473 // removes required library sources which would cause namespace/name conflict with one of the main sources
474 // later in the parsing process. this can happen if we add a parent module or a submodule as a main source
475 // and the same parent module or submodule is added as one of the library sources.
476 // such situation may occur when using the yang-system-test artifact - if a parent module/submodule is specified
477 // as its argument and the same dir is specified as one of the library dirs through -p option).
478 private static void removeConflictingLibSources(final SourceSpecificContext source,
479 final Set<SourceSpecificContext> requiredLibs) {
480 final Iterator<SourceSpecificContext> requiredLibsIter = requiredLibs.iterator();
481 while (requiredLibsIter.hasNext()) {
482 final SourceSpecificContext currentReqSource = requiredLibsIter.next();
483 if (source.getRootIdentifier().equals(currentReqSource.getRootIdentifier())) {
484 requiredLibsIter.remove();
489 private void endPhase(final ModelProcessingPhase phase) {
490 checkState(currentPhase == phase);
491 finishedPhase = currentPhase;
492 LOG.debug("Global phase {} finished", phase);
495 Set<SourceSpecificContext> getSources() {
499 public Set<YangVersion> getSupportedVersions() {
500 return supportedVersions;
503 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
504 mutableStatementsToSeal.add(mutableStatement);
507 void sealMutableStatements() {
508 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
509 mutableStatement.seal();
511 mutableStatementsToSeal.clear();