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 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.function.Predicate;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.YangVersion;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
52 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
53 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
54 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.RecursiveObjectLeaker;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
62 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
64 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList
65 .<ModelProcessingPhase> builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
66 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
67 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
69 private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
70 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
72 private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
73 private final Set<SourceSpecificContext> sources = new HashSet<>();
75 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
76 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
78 private final boolean enabledSemanticVersions;
79 private final Set<YangVersion> supportedVersions;
81 BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
82 final StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
83 this(supports, ImmutableMap.of(), statementParserMode, isFeatureSupported);
86 BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
87 final Map<ValidationBundleType, Collection<?>> supportedValidation,
88 final StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
90 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
91 Preconditions.checkNotNull(statementParserMode, "Statement parser mode must not be null.");
92 this.enabledSemanticVersions = statementParserMode == StatementParserMode.SEMVER_MODE;
94 for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
95 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
98 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
99 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
100 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
103 boolean isEnabledSemanticVersioning() {
104 return enabledSemanticVersions;
107 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
108 return supports.get(currentPhase);
111 void addSource(@Nonnull final StatementStreamSource source) {
112 sources.add(new SourceSpecificContext(this, source));
116 public StorageNodeType getStorageNodeType() {
117 return StorageNodeType.GLOBAL;
121 public NamespaceStorageNode getParentNamespaceStorage() {
126 public NamespaceBehaviour.Registry getBehaviourRegistry() {
131 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
132 final Class<N> type) {
133 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
134 if (potential == null) {
135 final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
136 if (potentialRaw != null) {
137 potential = createNamespaceContext(potentialRaw);
138 supportedNamespaces.put(type, potential);
140 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
145 Verify.verify(type.equals(potential.getIdentifier()));
147 * Safe cast, previous checkState checks equivalence of key from which
148 * type argument are derived
150 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
153 @SuppressWarnings({ "unchecked", "rawtypes" })
154 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
155 final NamespaceBehaviour<K, V, N> potentialRaw) {
156 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
157 final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
158 (DerivedNamespaceBehaviour) potentialRaw);
159 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
161 return derivedContext;
163 return new SimpleNamespaceContext<>(potentialRaw);
166 StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
167 StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
168 if (potential == null) {
169 final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
171 if (potentialRaw != null) {
172 potential = new StatementDefinitionContext<>(potentialRaw);
173 definitions.put(version, name, potential);
179 EffectiveModelContext build() throws SourceException, ReactorException {
180 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
182 loadPhaseStatements();
183 completePhaseActions();
189 private EffectiveModelContext transform() {
190 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
191 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
192 for (final SourceSpecificContext source : sources) {
193 rootStatements.add(source.getRoot().buildDeclared());
195 return new EffectiveModelContext(rootStatements);
198 EffectiveSchemaContext buildEffective() throws ReactorException {
199 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
201 loadPhaseStatements();
202 completePhaseActions();
205 return transformEffective();
208 private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
209 final RuntimeException cause) throws SomeModifiersUnresolvedException {
210 final SourceIdentifier sourceId = Utils.createSourceIdentifier(source.getRoot());
211 if (!(cause instanceof SourceException)) {
213 * This should not be happening as all our processing should provide SourceExceptions.
214 * We will wrap the exception to provide enough information to identify the problematic model,
215 * but also emit a warning so the offending codepath will get fixed.
217 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
221 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
224 private EffectiveSchemaContext transformEffective() throws ReactorException {
225 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
226 final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
227 final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
230 for (final SourceSpecificContext source : sources) {
231 final RootStatementContext<?, ?, ?> root = source.getRoot();
233 rootStatements.add(root.buildDeclared());
234 rootEffectiveStatements.add(root.buildEffective());
235 } catch (final RuntimeException ex) {
236 throw propagateException(source, ex);
240 RecursiveObjectLeaker.cleanup();
243 return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
246 private void startPhase(final ModelProcessingPhase phase) {
247 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
248 for (final SourceSpecificContext source : sources) {
249 source.startPhase(phase);
251 currentPhase = phase;
252 LOG.debug("Global phase {} started", phase);
255 private void loadPhaseStatements() throws ReactorException {
256 Preconditions.checkState(currentPhase != null);
257 for (final SourceSpecificContext source : sources) {
259 source.loadStatements();
260 } catch (final RuntimeException ex) {
261 throw propagateException(source, ex);
266 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
267 boolean addedCause = false;
268 SomeModifiersUnresolvedException buildFailure = null;
269 for (final SourceSpecificContext failedSource : sourcesToProgress) {
270 final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
271 if (!optSourceEx.isPresent()) {
275 final SourceException sourceEx = optSourceEx.get();
276 // Workaround for broken logging implementations which ignore
277 // suppressed exceptions
278 final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
279 if (LOG.isDebugEnabled()) {
280 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
282 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
285 final Throwable[] suppressed = sourceEx.getSuppressed();
286 if (suppressed.length > 0) {
287 LOG.error("{} additional errors reported:", suppressed.length);
290 for (final Throwable t : suppressed) {
291 // FIXME: this should be configured in the appender, really
292 if (LOG.isDebugEnabled()) {
293 LOG.error("Error {}: {}", i, t.getMessage(), t);
295 LOG.error("Error {}: {}", i, t.getMessage());
304 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
305 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
307 buildFailure.addSuppressed(sourceEx);
313 private void completePhaseActions() throws ReactorException {
314 Preconditions.checkState(currentPhase != null);
315 final List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
316 boolean progressing = true;
317 while (progressing) {
318 // We reset progressing to false.
320 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
321 while (currentSource.hasNext()) {
322 final SourceSpecificContext nextSourceCtx = currentSource.next();
324 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
325 switch (sourceProgress) {
327 currentSource.remove();
328 // Fallback to progress, since we were able to make
329 // progress in computation
337 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
339 } catch (RuntimeException ex) {
340 throw propagateException(nextSourceCtx, ex);
344 if (!sourcesToProgress.isEmpty()) {
345 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
346 if (buildFailure != null) {
352 private void endPhase(final ModelProcessingPhase phase) {
353 Preconditions.checkState(currentPhase == phase);
354 finishedPhase = currentPhase;
355 LOG.debug("Global phase {} finished", phase);
358 Set<SourceSpecificContext> getSources() {
362 public Set<YangVersion> getSupportedVersions() {
363 return supportedVersions;