BUG-6757: revert fix for BUG-4456
[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.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;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Objects;
23 import java.util.Set;
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;
53
54 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
55     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
56
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();
61
62     private final Map<QName, StatementDefinitionContext<?, ?, ?>> definitions = new HashMap<>();
63     private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
64
65     private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
66     private final Set<SourceSpecificContext> sources = new HashSet<>();
67
68     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
69     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
70
71     private final boolean enabledSemanticVersions;
72
73     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
74             StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
75         super();
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;
79
80         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
81                 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
82     }
83
84     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
85             final Map<ValidationBundleType, Collection<?>> supportedValidation,
86             StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
87         super();
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;
91
92         for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
93             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
94         }
95
96         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
97                 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
98     }
99
100     public boolean isEnabledSemanticVersioning() {
101         return enabledSemanticVersions;
102     }
103
104     public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
105         return supports.get(currentPhase);
106     }
107
108     public void addSource(@Nonnull final StatementStreamSource source) {
109         sources.add(new SourceSpecificContext(this, source));
110     }
111
112     @Override
113     public StorageNodeType getStorageNodeType() {
114         return StorageNodeType.GLOBAL;
115     }
116
117     @Override
118     public NamespaceStorageNode getParentNamespaceStorage() {
119         return null;
120     }
121
122     @Override
123     public NamespaceBehaviour.Registry getBehaviourRegistry() {
124         return this;
125     }
126
127     @Override
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);
136             } else {
137                 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
138                         + currentPhase);
139             }
140         }
141
142         Verify.verify(type.equals(potential.getIdentifier()));
143         /*
144          * Safe cast, previous checkState checks equivalence of key from which
145          * type argument are derived
146          */
147         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
148     }
149
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(
157                     derivedContext);
158             return derivedContext;
159         }
160         return new SimpleNamespaceContext<>(potentialRaw);
161     }
162
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);
170             }
171         }
172         return potential;
173     }
174
175     public EffectiveModelContext build() throws SourceException, ReactorException {
176         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
177             startPhase(phase);
178             loadPhaseStatements();
179             completePhaseActions();
180             endPhase(phase);
181         }
182         return transform();
183     }
184
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());
190         }
191         return new EffectiveModelContext(rootStatements);
192     }
193
194     public EffectiveSchemaContext buildEffective() throws ReactorException {
195         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
196             startPhase(phase);
197             loadPhaseStatements();
198             completePhaseActions();
199             endPhase(phase);
200         }
201         return transformEffective();
202     }
203
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;
209
210         try {
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());
216             }
217         } catch (SourceException ex) {
218             throw new SomeModifiersUnresolvedException(currentPhase, sourceId, ex);
219         }
220
221         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
222     }
223
224     private void startPhase(final ModelProcessingPhase phase) {
225         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
226         for (SourceSpecificContext source : sources) {
227             source.startPhase(phase);
228         }
229         currentPhase = phase;
230     }
231
232     private void loadPhaseStatements() throws ReactorException {
233         Preconditions.checkState(currentPhase != null);
234         for (SourceSpecificContext source : sources) {
235             try {
236                 source.loadStatements();
237             } catch (SourceException ex) {
238                 final SourceIdentifier sourceId = Utils.createSourceIdentifier(source.getRoot());
239                 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, ex);
240             }
241         }
242     }
243
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);
249
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);
255             } else {
256                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
257             }
258
259             final Throwable[] suppressed = sourceEx.getSuppressed();
260             if (suppressed.length > 0) {
261                 LOG.error("{} additional errors reported:", suppressed.length);
262
263                 int i = 1;
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);
268                     } else {
269                         LOG.error("Error {}: {}", i, t.getMessage());
270                     }
271
272                     i++;
273                 }
274             }
275
276             if (!addedCause) {
277                 addedCause = true;
278                 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
279                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
280             } else {
281                 buildFailure.addSuppressed(sourceEx);
282             }
283         }
284         return buildFailure;
285     }
286
287     private void completePhaseActions() throws ReactorException {
288         Preconditions.checkState(currentPhase != null);
289         List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
290         SourceIdentifier sourceId = null;
291         try {
292             boolean progressing = true;
293             while (progressing) {
294                 // We reset progressing to false.
295                 progressing = 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) {
302                     case FINISHED:
303                         currentSource.remove();
304                         // Fallback to progress, since we were able to make
305                         // progress in computation
306                     case PROGRESS:
307                         progressing = true;
308                         break;
309                     case NO_PROGRESS:
310                         // Noop
311                         break;
312                     default:
313                         throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
314                     }
315                 }
316             }
317         } catch (SourceException e) {
318             throw new SomeModifiersUnresolvedException(currentPhase, sourceId, e);
319         }
320         if (!sourcesToProgress.isEmpty()) {
321             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
322             throw buildFailure;
323         }
324     }
325
326     private void endPhase(final ModelProcessingPhase phase) {
327         Preconditions.checkState(currentPhase == phase);
328         finishedPhase = currentPhase;
329     }
330
331     public Set<SourceSpecificContext> getSources() {
332         return sources;
333     }
334 }