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_PRE_LINKAGE)
54 .add(ModelProcessingPhase.SOURCE_LINKAGE)
55 .add(ModelProcessingPhase.STATEMENT_DEFINITION)
56 .add(ModelProcessingPhase.FULL_DECLARATION)
57 .add(ModelProcessingPhase.EFFECTIVE_MODEL)
60 private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
61 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 for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
79 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
83 public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
84 return supports.get(currentPhase);
87 public void addSource(@Nonnull final StatementStreamSource source) {
88 sources.add(new SourceSpecificContext(this,source));
92 public StorageNodeType getStorageNodeType() {
93 return StorageNodeType.GLOBAL;
97 public NamespaceStorageNode getParentNamespaceStorage() {
102 public NamespaceBehaviour.Registry getBehaviourRegistry() {
107 public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(final Class<N> type) {
108 NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
109 if (potential == null) {
110 NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
111 if (potentialRaw != null) {
112 potential = createNamespaceContext(potentialRaw);
113 supportedNamespaces.put(type, potential);
115 throw new NamespaceNotAvailableException(
116 "Namespace " + type + " is not available in phase " + currentPhase);
120 Verify.verify(type.equals(potential.getIdentifier()));
122 * Safe cast, previous checkState checks equivalence of key from which type argument are
125 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
128 @SuppressWarnings({"unchecked", "rawtypes"})
129 private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
130 final NamespaceBehaviour<K, V, N> potentialRaw) {
131 if (potentialRaw instanceof DerivedNamespaceBehaviour) {
132 VirtualNamespaceContext derivedContext =
133 new VirtualNamespaceContext((DerivedNamespaceBehaviour) potentialRaw);
134 getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom())
135 .addDerivedNamespace(derivedContext);
136 return derivedContext;
138 return new SimpleNamespaceContext<>(potentialRaw);
141 public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
142 StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
143 if (potential == null) {
144 StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
145 if (potentialRaw != null) {
146 potential = new StatementDefinitionContext<>(potentialRaw);
147 definitions.put(name, potential);
153 public EffectiveModelContext build() throws SourceException, ReactorException {
154 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
156 loadPhaseStatements();
157 completePhaseActions();
163 private EffectiveModelContext transform() {
164 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
165 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
166 for (SourceSpecificContext source : sources) {
167 rootStatements.add(source.getRoot().buildDeclared());
169 return new EffectiveModelContext(rootStatements);
172 public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
173 for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
175 loadPhaseStatements();
176 completePhaseActions();
179 return transformEffective();
182 private EffectiveSchemaContext transformEffective() {
183 Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
184 List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
185 List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>(sources.size());
187 for (SourceSpecificContext source : sources) {
188 final RootStatementContext<?, ?, ?> root = source.getRoot();
189 rootStatements.add(root.buildDeclared());
190 rootEffectiveStatements.add(root.buildEffective());
193 return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
196 private void startPhase(final ModelProcessingPhase phase) {
197 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
198 for (SourceSpecificContext source : sources) {
199 source.startPhase(phase);
201 currentPhase = phase;
204 private void loadPhaseStatements() throws SourceException {
205 Preconditions.checkState(currentPhase != null);
206 for (SourceSpecificContext source : sources) {
207 source.loadStatements();
211 private SomeModifiersUnresolvedException addSourceExceptions(final SomeModifiersUnresolvedException buildFailure,
212 final List<SourceSpecificContext> sourcesToProgress) {
213 boolean addedCause = false;
214 for (SourceSpecificContext failedSource : sourcesToProgress) {
215 final SourceException sourceEx = failedSource.failModifiers(currentPhase);
217 // Workaround for broken logging implementations which ignore suppressed exceptions
218 Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
219 if (LOG.isDebugEnabled()) {
220 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
222 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
225 final Throwable[] suppressed = sourceEx.getSuppressed();
226 if (suppressed.length > 0) {
227 LOG.error("{} additional errors reported:", suppressed.length);
230 for (Throwable t : suppressed) {
231 // FIXME: this should be configured in the appender, really
232 if (LOG.isDebugEnabled()) {
233 LOG.error("Error {}: {}", i, t.getMessage(), t);
235 LOG.error("Error {}: {}", i, t.getMessage());
244 buildFailure.initCause(sourceEx);
246 buildFailure.addSuppressed(sourceEx);
252 private void completePhaseActions() throws ReactorException {
253 Preconditions.checkState(currentPhase != null);
254 List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
256 boolean progressing = true;
257 while (progressing) {
258 // We reset progressing to false.
260 Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
261 while(currentSource.hasNext()) {
262 SourceSpecificContext nextSourceCtx = currentSource.next();
263 PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
264 switch (sourceProgress) {
266 currentSource.remove();
267 // Fallback to progress, since we were able to make progress in computation
275 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
279 } catch (SourceException e) {
280 throw Throwables.propagate(e);
282 if (!sourcesToProgress.isEmpty()) {
283 SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
284 buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
289 private void endPhase(final ModelProcessingPhase phase) {
290 Preconditions.checkState(currentPhase == phase);
291 finishedPhase = currentPhase;
294 public Set<SourceSpecificContext> getSources() {