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.ImmutableList;
13 import com.google.common.collect.Lists;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Objects;
24 import java.util.function.Predicate;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
28 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
30 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
31 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
42 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
43 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
45 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
46 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
47 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
48 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
49 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
50 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
55 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
57 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList
58 .<ModelProcessingPhase> builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
59 .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
60 .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
62 private final Map<QName, StatementDefinitionContext<?, ?, ?>> definitions = new HashMap<>();
63 private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
65 private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
66 private final Set<SourceSpecificContext> sources = new HashSet<>();
68 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
69 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
71 private final boolean enabledSemanticVersions;
73 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
74 StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
76 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
77 Preconditions.checkNotNull(statementParserMode, "Statement parser mode must not be null.");
78 this.enabledSemanticVersions = statementParserMode == StatementParserMode.SEMVER_MODE;
80 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
81 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
84 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
85 final Map<ValidationBundleType, Collection<?>> supportedValidation,
86 StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
88 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
89 Preconditions.checkNotNull(statementParserMode, "Statement parser mode must not be null.");
90 this.enabledSemanticVersions = statementParserMode == StatementParserMode.SEMVER_MODE;
92 for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
93 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
96 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
97 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
100 public boolean isEnabledSemanticVersioning() {
101 return enabledSemanticVersions;
104 public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
105 return supports.get(currentPhase);
108 public void addSource(@Nonnull final StatementStreamSource source) {
109 sources.add(new SourceSpecificContext(this, source));
113 public StorageNodeType getStorageNodeType() {
114 return StorageNodeType.GLOBAL;
118 public NamespaceStorageNode getParentNamespaceStorage() {
123 public NamespaceBehaviour.Registry getBehaviourRegistry() {
128 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
129 final Class<N> type) {
130 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
131 if (potential == null) {
132 NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
133 if (potentialRaw != null) {
134 potential = createNamespaceContext(potentialRaw);
135 supportedNamespaces.put(type, potential);
137 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
142 Verify.verify(type.equals(potential.getIdentifier()));
144 * Safe cast, previous checkState checks equivalence of key from which
145 * type argument are derived
147 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
150 @SuppressWarnings({ "unchecked", "rawtypes" })
151 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
152 final NamespaceBehaviour<K, V, N> potentialRaw) {
153 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
154 VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
155 (DerivedNamespaceBehaviour) potentialRaw);
156 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
158 return derivedContext;
160 return new SimpleNamespaceContext<>(potentialRaw);
163 public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
164 StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
165 if (potential == null) {
166 StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
167 if (potentialRaw != null) {
168 potential = new StatementDefinitionContext<>(potentialRaw);
169 definitions.put(name, potential);
175 public EffectiveModelContext build() throws SourceException, ReactorException {
176 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
178 loadPhaseStatements();
179 completePhaseActions();
185 private EffectiveModelContext transform() {
186 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
187 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
188 for (SourceSpecificContext source : sources) {
189 rootStatements.add(source.getRoot().buildDeclared());
191 return new EffectiveModelContext(rootStatements);
194 public EffectiveSchemaContext buildEffective() throws ReactorException {
195 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
197 loadPhaseStatements();
198 completePhaseActions();
201 return transformEffective();
204 private EffectiveSchemaContext transformEffective() throws ReactorException {
205 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
206 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
207 List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
208 SourceIdentifier sourceId = null;
211 for (SourceSpecificContext source : sources) {
212 final RootStatementContext<?, ?, ?> root = source.getRoot();
213 sourceId = Utils.createSourceIdentifier(root);
214 rootStatements.add(root.buildDeclared());
215 rootEffectiveStatements.add(root.buildEffective());
217 } catch (SourceException ex) {
218 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, ex);
221 return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
224 private void startPhase(final ModelProcessingPhase phase) {
225 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
226 for (SourceSpecificContext source : sources) {
227 source.startPhase(phase);
229 currentPhase = phase;
232 private void loadPhaseStatements() throws ReactorException {
233 Preconditions.checkState(currentPhase != null);
234 for (SourceSpecificContext source : sources) {
236 source.loadStatements();
237 } catch (SourceException ex) {
238 final SourceIdentifier sourceId = Utils.createSourceIdentifier(source.getRoot());
239 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, ex);
244 private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
245 boolean addedCause = false;
246 SomeModifiersUnresolvedException buildFailure = null;
247 for (SourceSpecificContext failedSource : sourcesToProgress) {
248 final SourceException sourceEx = failedSource.failModifiers(currentPhase);
250 // Workaround for broken logging implementations which ignore
251 // suppressed exceptions
252 Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
253 if (LOG.isDebugEnabled()) {
254 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
256 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
259 final Throwable[] suppressed = sourceEx.getSuppressed();
260 if (suppressed.length > 0) {
261 LOG.error("{} additional errors reported:", suppressed.length);
264 for (Throwable t : suppressed) {
265 // FIXME: this should be configured in the appender, really
266 if (LOG.isDebugEnabled()) {
267 LOG.error("Error {}: {}", i, t.getMessage(), t);
269 LOG.error("Error {}: {}", i, t.getMessage());
278 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
279 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
281 buildFailure.addSuppressed(sourceEx);
287 private void completePhaseActions() throws ReactorException {
288 Preconditions.checkState(currentPhase != null);
289 List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
290 SourceIdentifier sourceId = null;
292 boolean progressing = true;
293 while (progressing) {
294 // We reset progressing to false.
296 Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
297 while (currentSource.hasNext()) {
298 SourceSpecificContext nextSourceCtx = currentSource.next();
299 sourceId = Utils.createSourceIdentifier(nextSourceCtx.getRoot());
300 PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
301 switch (sourceProgress) {
303 currentSource.remove();
304 // Fallback to progress, since we were able to make
305 // progress in computation
313 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
317 } catch (SourceException e) {
318 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, e);
320 if (!sourcesToProgress.isEmpty()) {
321 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
326 private void endPhase(final ModelProcessingPhase phase) {
327 Preconditions.checkState(currentPhase == phase);
328 finishedPhase = currentPhase;
331 public Set<SourceSpecificContext> getSources() {