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.Throwables;
12 import com.google.common.base.Verify;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.Lists;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.List;
22 import java.util.Map.Entry;
23 import java.util.Objects;
25 import java.util.function.Predicate;
26 import javax.annotation.Nonnull;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
29 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
42 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
43 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
44 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
45 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
46 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
47 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
48 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
53 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
55 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList.<ModelProcessingPhase>builder()
56 .add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
57 .add(ModelProcessingPhase.SOURCE_LINKAGE)
58 .add(ModelProcessingPhase.STATEMENT_DEFINITION)
59 .add(ModelProcessingPhase.FULL_DECLARATION)
60 .add(ModelProcessingPhase.EFFECTIVE_MODEL)
63 private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
64 private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
66 private final Map<ModelProcessingPhase,StatementSupportBundle> supports;
67 private final Set<SourceSpecificContext> sources = new HashSet<>();
69 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
70 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
72 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
73 final Predicate<QName> isFeatureSupported) {
75 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
77 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
80 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
81 final Map<ValidationBundleType,Collection<?>> supportedValidation,
82 final Predicate<QName> isFeatureSupported) {
84 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
86 for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
87 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
90 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
93 public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
94 return supports.get(currentPhase);
97 public void addSource(@Nonnull final StatementStreamSource source) {
98 sources.add(new SourceSpecificContext(this,source));
102 public StorageNodeType getStorageNodeType() {
103 return StorageNodeType.GLOBAL;
107 public NamespaceStorageNode getParentNamespaceStorage() {
112 public NamespaceBehaviour.Registry getBehaviourRegistry() {
117 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(final Class<N> type) {
118 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
119 if (potential == null) {
120 NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
121 if (potentialRaw != null) {
122 potential = createNamespaceContext(potentialRaw);
123 supportedNamespaces.put(type, potential);
125 throw new NamespaceNotAvailableException(
126 "Namespace " + type + " is not available in phase " + currentPhase);
130 Verify.verify(type.equals(potential.getIdentifier()));
132 * Safe cast, previous checkState checks equivalence of key from which type argument are
135 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
138 @SuppressWarnings({"unchecked", "rawtypes"})
139 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
140 final NamespaceBehaviour<K, V, N> potentialRaw) {
141 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
142 VirtualNamespaceContext derivedContext =
143 new VirtualNamespaceContext((DerivedNamespaceBehaviour) potentialRaw);
144 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom())
145 .addDerivedNamespace(derivedContext);
146 return derivedContext;
148 return new SimpleNamespaceContext<>(potentialRaw);
151 public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
152 StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
153 if (potential == null) {
154 StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
155 if (potentialRaw != null) {
156 potential = new StatementDefinitionContext<>(potentialRaw);
157 definitions.put(name, potential);
163 public EffectiveModelContext build() throws SourceException, ReactorException {
164 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
166 loadPhaseStatements();
167 completePhaseActions();
173 private EffectiveModelContext transform() {
174 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
175 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
176 for (SourceSpecificContext source : sources) {
177 rootStatements.add(source.getRoot().buildDeclared());
179 return new EffectiveModelContext(rootStatements);
182 public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
183 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
185 loadPhaseStatements();
186 completePhaseActions();
189 return transformEffective();
192 private EffectiveSchemaContext transformEffective() {
193 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
194 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
195 List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>(sources.size());
197 for (SourceSpecificContext source : sources) {
198 final RootStatementContext<?, ?, ?> root = source.getRoot();
199 rootStatements.add(root.buildDeclared());
200 rootEffectiveStatements.add(root.buildEffective());
203 return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
206 private void startPhase(final ModelProcessingPhase phase) {
207 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
208 for (SourceSpecificContext source : sources) {
209 source.startPhase(phase);
211 currentPhase = phase;
214 private void loadPhaseStatements() throws SourceException {
215 Preconditions.checkState(currentPhase != null);
216 for (SourceSpecificContext source : sources) {
217 source.loadStatements();
221 private SomeModifiersUnresolvedException addSourceExceptions(final SomeModifiersUnresolvedException buildFailure,
222 final List<SourceSpecificContext> sourcesToProgress) {
223 boolean addedCause = false;
224 for (SourceSpecificContext failedSource : sourcesToProgress) {
225 final SourceException sourceEx = failedSource.failModifiers(currentPhase);
227 // Workaround for broken logging implementations which ignore suppressed exceptions
228 Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
229 if (LOG.isDebugEnabled()) {
230 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
232 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
235 final Throwable[] suppressed = sourceEx.getSuppressed();
236 if (suppressed.length > 0) {
237 LOG.error("{} additional errors reported:", suppressed.length);
240 for (Throwable t : suppressed) {
241 // FIXME: this should be configured in the appender, really
242 if (LOG.isDebugEnabled()) {
243 LOG.error("Error {}: {}", i, t.getMessage(), t);
245 LOG.error("Error {}: {}", i, t.getMessage());
254 buildFailure.initCause(sourceEx);
256 buildFailure.addSuppressed(sourceEx);
262 private void completePhaseActions() throws ReactorException {
263 Preconditions.checkState(currentPhase != null);
264 List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
266 boolean progressing = true;
267 while (progressing) {
268 // We reset progressing to false.
270 Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
271 while (currentSource.hasNext()) {
272 SourceSpecificContext nextSourceCtx = currentSource.next();
273 PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
274 switch (sourceProgress) {
276 currentSource.remove();
277 // Fallback to progress, since we were able to make progress in computation
285 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
289 } catch (SourceException e) {
290 throw Throwables.propagate(e);
292 if (!sourcesToProgress.isEmpty()) {
293 SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
294 buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
299 private void endPhase(final ModelProcessingPhase phase) {
300 Preconditions.checkState(currentPhase == phase);
301 finishedPhase = currentPhase;
304 public Set<SourceSpecificContext> getSources() {