a4c0b4446b40dbc596e114a3ce6329b983133310
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / reactor / BuildGlobalContext.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
9
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;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Objects;
24 import java.util.Set;
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;
51
52 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
53     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
54
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)
61             .build();
62
63     private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
64     private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
65
66     private final Map<ModelProcessingPhase,StatementSupportBundle> supports;
67     private final Set<SourceSpecificContext> sources = new HashSet<>();
68
69     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
70     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
71
72     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
73                               final Predicate<QName> isFeatureSupported) {
74         super();
75         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
76
77         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
78     }
79
80     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
81                               final Map<ValidationBundleType,Collection<?>> supportedValidation,
82                               final Predicate<QName> isFeatureSupported) {
83         super();
84         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
85
86         for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
87             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
88         }
89
90         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES, isFeatureSupported);
91     }
92
93     public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
94         return supports.get(currentPhase);
95     }
96
97     public void addSource(@Nonnull final StatementStreamSource source) {
98         sources.add(new SourceSpecificContext(this,source));
99     }
100
101     @Override
102     public StorageNodeType getStorageNodeType() {
103         return StorageNodeType.GLOBAL;
104     }
105
106     @Override
107     public NamespaceStorageNode getParentNamespaceStorage() {
108         return null;
109     }
110
111     @Override
112     public NamespaceBehaviour.Registry getBehaviourRegistry() {
113         return this;
114     }
115
116     @Override
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);
124             } else {
125                 throw new NamespaceNotAvailableException(
126                         "Namespace " + type + " is not available in phase " + currentPhase);
127             }
128         }
129
130         Verify.verify(type.equals(potential.getIdentifier()));
131         /*
132          * Safe cast, previous checkState checks equivalence of key from which type argument are
133          * derived
134          */
135         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
136     }
137
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;
147         }
148         return new SimpleNamespaceContext<>(potentialRaw);
149     }
150
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);
158             }
159         }
160         return potential;
161     }
162
163     public EffectiveModelContext build() throws SourceException, ReactorException {
164         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
165             startPhase(phase);
166             loadPhaseStatements();
167             completePhaseActions();
168             endPhase(phase);
169         }
170         return transform();
171     }
172
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());
178         }
179         return new EffectiveModelContext(rootStatements);
180     }
181
182     public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
183         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
184             startPhase(phase);
185             loadPhaseStatements();
186             completePhaseActions();
187             endPhase(phase);
188         }
189         return transformEffective();
190     }
191
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());
196
197         for (SourceSpecificContext source : sources) {
198             final RootStatementContext<?, ?, ?> root = source.getRoot();
199             rootStatements.add(root.buildDeclared());
200             rootEffectiveStatements.add(root.buildEffective());
201         }
202
203         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
204     }
205
206     private void startPhase(final ModelProcessingPhase phase) {
207         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
208         for (SourceSpecificContext source : sources) {
209             source.startPhase(phase);
210         }
211         currentPhase = phase;
212     }
213
214     private  void loadPhaseStatements() throws SourceException {
215         Preconditions.checkState(currentPhase != null);
216         for (SourceSpecificContext source : sources) {
217             source.loadStatements();
218         }
219     }
220
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);
226
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);
231             } else {
232                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
233             }
234
235             final Throwable[] suppressed = sourceEx.getSuppressed();
236             if (suppressed.length > 0) {
237                 LOG.error("{} additional errors reported:", suppressed.length);
238
239                 int i = 1;
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);
244                     } else {
245                         LOG.error("Error {}: {}", i, t.getMessage());
246                     }
247
248                     i++;
249                 }
250             }
251
252             if (!addedCause) {
253                 addedCause = true;
254                 buildFailure.initCause(sourceEx);
255             } else {
256                 buildFailure.addSuppressed(sourceEx);
257             }
258         }
259         return buildFailure;
260     }
261
262     private  void completePhaseActions() throws ReactorException {
263         Preconditions.checkState(currentPhase != null);
264         List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
265         try {
266             boolean progressing = true;
267             while (progressing) {
268                 // We reset progressing to false.
269                 progressing = 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) {
275                         case FINISHED:
276                             currentSource.remove();
277                             // Fallback to progress, since we were able to make progress in computation
278                         case PROGRESS:
279                             progressing = true;
280                             break;
281                         case NO_PROGRESS:
282                             // Noop
283                             break;
284                         default:
285                            throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
286                     }
287                 }
288             }
289         } catch (SourceException e) {
290             throw Throwables.propagate(e);
291         }
292         if (!sourcesToProgress.isEmpty()) {
293             SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
294             buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
295             throw buildFailure;
296         }
297     }
298
299     private  void endPhase(final ModelProcessingPhase phase) {
300         Preconditions.checkState(currentPhase == phase);
301         finishedPhase = currentPhase;
302     }
303
304     public Set<SourceSpecificContext> getSources() {
305         return sources;
306     }
307 }