Bug 4662: Introduce a SemanticVersion concept - pre-linkage phase
[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 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;
48
49 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
50     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
51
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)
58             .build();
59
60     private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
61     private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
62
63     private final Map<ModelProcessingPhase,StatementSupportBundle> supports;
64     private final Set<SourceSpecificContext> sources = new HashSet<>();
65
66     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
67     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
68
69     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports) {
70         super();
71         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
72     }
73
74     public BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports, final Map<ValidationBundleType,Collection<?>> supportedValidation) {
75         super();
76         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
77
78         for (Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
79             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
80         }
81     }
82
83     public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
84         return supports.get(currentPhase);
85     }
86
87     public void addSource(@Nonnull final StatementStreamSource source) {
88         sources.add(new SourceSpecificContext(this,source));
89     }
90
91     @Override
92     public StorageNodeType getStorageNodeType() {
93         return StorageNodeType.GLOBAL;
94     }
95
96     @Override
97     public NamespaceStorageNode getParentNamespaceStorage() {
98         return null;
99     }
100
101     @Override
102     public NamespaceBehaviour.Registry getBehaviourRegistry() {
103         return this;
104     }
105
106     @Override
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);
114             } else {
115                 throw new NamespaceNotAvailableException(
116                         "Namespace " + type + " is not available in phase " + currentPhase);
117             }
118         }
119
120         Verify.verify(type.equals(potential.getIdentifier()));
121         /*
122          * Safe cast, previous checkState checks equivalence of key from which type argument are
123          * derived
124          */
125         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
126     }
127
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;
137         }
138         return new SimpleNamespaceContext<>(potentialRaw);
139     }
140
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);
148             }
149         }
150         return potential;
151     }
152
153     public EffectiveModelContext build() throws SourceException, ReactorException {
154         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
155             startPhase(phase);
156             loadPhaseStatements();
157             completePhaseActions();
158             endPhase(phase);
159         }
160         return transform();
161     }
162
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());
168         }
169         return new EffectiveModelContext(rootStatements);
170     }
171
172     public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
173         for (ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
174             startPhase(phase);
175             loadPhaseStatements();
176             completePhaseActions();
177             endPhase(phase);
178         }
179         return transformEffective();
180     }
181
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());
186
187         for (SourceSpecificContext source : sources) {
188             final RootStatementContext<?, ?, ?> root = source.getRoot();
189             rootStatements.add(root.buildDeclared());
190             rootEffectiveStatements.add(root.buildEffective());
191         }
192
193         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
194     }
195
196     private void startPhase(final ModelProcessingPhase phase) {
197         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
198         for (SourceSpecificContext source : sources) {
199             source.startPhase(phase);
200         }
201         currentPhase = phase;
202     }
203
204     private  void loadPhaseStatements() throws SourceException {
205         Preconditions.checkState(currentPhase != null);
206         for (SourceSpecificContext source : sources) {
207             source.loadStatements();
208         }
209     }
210
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);
216
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);
221             } else {
222                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
223             }
224
225             final Throwable[] suppressed = sourceEx.getSuppressed();
226             if (suppressed.length > 0) {
227                 LOG.error("{} additional errors reported:", suppressed.length);
228
229                 int i = 1;
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);
234                     } else {
235                         LOG.error("Error {}: {}", i, t.getMessage());
236                     }
237
238                     i++;
239                 }
240             }
241
242             if (!addedCause) {
243                 addedCause = true;
244                 buildFailure.initCause(sourceEx);
245             } else {
246                 buildFailure.addSuppressed(sourceEx);
247             }
248         }
249         return buildFailure;
250     }
251
252     private  void completePhaseActions() throws ReactorException {
253         Preconditions.checkState(currentPhase != null);
254         List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
255         try {
256             boolean progressing = true;
257             while (progressing) {
258                 // We reset progressing to false.
259                 progressing = 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) {
265                         case FINISHED:
266                             currentSource.remove();
267                             // Fallback to progress, since we were able to make progress in computation
268                         case PROGRESS:
269                             progressing = true;
270                             break;
271                         case NO_PROGRESS:
272                             // Noop
273                             break;
274                         default:
275                            throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
276                     }
277                 }
278             }
279         } catch (SourceException e) {
280             throw Throwables.propagate(e);
281         }
282         if (!sourcesToProgress.isEmpty()) {
283             SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
284             buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
285             throw buildFailure;
286         }
287     }
288
289     private  void endPhase(final ModelProcessingPhase phase) {
290         Preconditions.checkState(currentPhase == phase);
291         finishedPhase = currentPhase;
292     }
293
294     public Set<SourceSpecificContext> getSources() {
295         return sources;
296     }
297 }