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 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.parser.spi.meta.DerivedNamespaceBehaviour;
31 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
32 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
33 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
36 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
40 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
41 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
42 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
43 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
44 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
45 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
50 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
52 private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList.<ModelProcessingPhase>builder()
53 .add(ModelProcessingPhase.SOURCE_LINKAGE)
54 .add(ModelProcessingPhase.STATEMENT_DEFINITION)
55 .add(ModelProcessingPhase.FULL_DECLARATION)
56 .add(ModelProcessingPhase.EFFECTIVE_MODEL)
59 private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
60 private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
63 private final Map<ModelProcessingPhase,StatementSupportBundle> supports;
64 private final Set<SourceSpecificContext> sources = new HashSet<>();
66 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
67 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
69 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports) {
71 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
74 public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports, final Map<ValidationBundleType,Collection<?>> supportedValidation) {
76 this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
78 Set<Entry<ValidationBundleType, Collection<?>>> validationBundles = supportedValidation.entrySet();
79 for (Entry<ValidationBundleType, Collection<?>> validationBundle : validationBundles) {
80 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
84 public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
85 return supports.get(currentPhase);
88 public void addSource(@Nonnull final StatementStreamSource source) {
89 sources.add(new SourceSpecificContext(this,source));
93 public StorageNodeType getStorageNodeType() {
94 return StorageNodeType.GLOBAL;
98 public NamespaceStorageNode getParentNamespaceStorage() {
103 public NamespaceBehaviour.Registry getBehaviourRegistry() {
108 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(final Class<N> type) {
109 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
110 if (potential == null) {
111 NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
112 if(potentialRaw != null) {
113 potential = createNamespaceContext(potentialRaw);
114 supportedNamespaces.put(type, potential);
116 throw new NamespaceNotAvailableException(
117 "Namespace " + type + " is not available in phase " + currentPhase);
121 Verify.verify(type.equals(potential.getIdentifier()));
123 * Safe cast, previous checkState checks equivalence of key from which type argument are
126 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
129 @SuppressWarnings({"unchecked", "rawtypes"})
130 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
131 final NamespaceBehaviour<K, V, N> potentialRaw) {
132 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
133 VirtualNamespaceContext derivedContext =
134 new VirtualNamespaceContext((DerivedNamespaceBehaviour) potentialRaw);
135 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom())
136 .addDerivedNamespace(derivedContext);
137 return derivedContext;
139 return new SimpleNamespaceContext<>(potentialRaw);
142 public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
143 StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
144 if(potential == null) {
145 StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
146 if(potentialRaw != null) {
147 potential = new StatementDefinitionContext<>(potentialRaw);
148 definitions.put(name, potential);
154 public EffectiveModelContext build() throws SourceException, ReactorException {
155 for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
157 loadPhaseStatements();
158 completePhaseActions();
164 private EffectiveModelContext transform() {
165 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
166 List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
167 for(SourceSpecificContext source : sources) {
168 DeclaredStatement<?> root = source.getRoot().buildDeclared();
169 rootStatements.add(root);
171 return new EffectiveModelContext(rootStatements);
174 public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
175 for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
177 loadPhaseStatements();
178 completePhaseActions();
181 return transformEffective();
184 private EffectiveSchemaContext transformEffective() {
185 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
186 List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
187 List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>();
189 for(SourceSpecificContext source : sources) {
190 DeclaredStatement<?> root = source.getRoot().buildDeclared();
191 rootStatements.add(root);
193 EffectiveStatement<?,?> rootEffective = source.getRoot().buildEffective();
194 rootEffectiveStatements.add(rootEffective);
197 return new EffectiveSchemaContext(rootStatements,rootEffectiveStatements);
200 private void startPhase(final ModelProcessingPhase phase) {
201 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
202 for(SourceSpecificContext source : sources) {
203 source.startPhase(phase);
205 currentPhase = phase;
208 private void loadPhaseStatements() throws SourceException {
209 Preconditions.checkState(currentPhase != null);
210 for(SourceSpecificContext source : sources) {
211 source.loadStatements();
215 private SomeModifiersUnresolvedException addSourceExceptions(final SomeModifiersUnresolvedException buildFailure,
216 final List<SourceSpecificContext> sourcesToProgress) {
217 boolean addedCause = false;
218 for (SourceSpecificContext failedSource : sourcesToProgress) {
219 final SourceException sourceEx = failedSource.failModifiers(currentPhase);
221 // Workaround for broken logging implementations which ignore suppressed exceptions
222 Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
223 if (LOG.isDebugEnabled()) {
224 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
226 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
229 final Throwable[] suppressed = sourceEx.getSuppressed();
230 if (suppressed.length > 0) {
231 LOG.error("{} additional errors reported:", suppressed.length);
234 for (Throwable t : suppressed) {
235 // FIXME: this should be configured in the appender, really
236 if (LOG.isDebugEnabled()) {
237 LOG.error("Error {}: {}", i, t.getMessage(), t);
239 LOG.error("Error {}: {}", i, t.getMessage());
248 buildFailure.initCause(sourceEx);
250 buildFailure.addSuppressed(sourceEx);
256 private void completePhaseActions() throws ReactorException {
257 Preconditions.checkState(currentPhase != null);
258 List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
260 boolean progressing = true;
262 // We reset progressing to false.
264 Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
265 while(currentSource.hasNext()) {
266 SourceSpecificContext nextSourceCtx = currentSource.next();
267 PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
268 switch (sourceProgress) {
270 currentSource.remove();
271 // Fallback to progress, since we were able to make progress in computation
279 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
283 } catch (SourceException e) {
284 throw Throwables.propagate(e);
286 if(!sourcesToProgress.isEmpty()) {
287 SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
288 buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
293 private void endPhase(final ModelProcessingPhase phase) {
294 Preconditions.checkState(currentPhase == phase);
295 finishedPhase = currentPhase;
298 public Set<SourceSpecificContext> getSources() {