BUG-4456: add RecursiveExtensionResolver
[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.RecursiveObjectLeaker;
46 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
51     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
52
53     private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList.<ModelProcessingPhase>builder()
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         try {
188             for (SourceSpecificContext source : sources) {
189                 final RootStatementContext<?, ?, ?> root = source.getRoot();
190                 rootStatements.add(root.buildDeclared());
191                 rootEffectiveStatements.add(root.buildEffective());
192             }
193         } finally {
194             RecursiveObjectLeaker.cleanup();
195         }
196
197         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
198     }
199
200     private void startPhase(final ModelProcessingPhase phase) {
201         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
202         for (SourceSpecificContext source : sources) {
203             source.startPhase(phase);
204         }
205         currentPhase = phase;
206     }
207
208     private  void loadPhaseStatements() throws SourceException {
209         Preconditions.checkState(currentPhase != null);
210         for (SourceSpecificContext source : sources) {
211             source.loadStatements();
212         }
213     }
214
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);
220
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);
225             } else {
226                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
227             }
228
229             final Throwable[] suppressed = sourceEx.getSuppressed();
230             if (suppressed.length > 0) {
231                 LOG.error("{} additional errors reported:", suppressed.length);
232
233                 int i = 1;
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);
238                     } else {
239                         LOG.error("Error {}: {}", i, t.getMessage());
240                     }
241
242                     i++;
243                 }
244             }
245
246             if (!addedCause) {
247                 addedCause = true;
248                 buildFailure.initCause(sourceEx);
249             } else {
250                 buildFailure.addSuppressed(sourceEx);
251             }
252         }
253         return buildFailure;
254     }
255
256     private  void completePhaseActions() throws ReactorException {
257         Preconditions.checkState(currentPhase != null);
258         List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
259         try {
260             boolean progressing = true;
261             while (progressing) {
262                 // We reset progressing to false.
263                 progressing = 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) {
269                         case FINISHED:
270                             currentSource.remove();
271                             // Fallback to progress, since we were able to make progress in computation
272                         case PROGRESS:
273                             progressing = true;
274                             break;
275                         case NO_PROGRESS:
276                             // Noop
277                             break;
278                         default:
279                            throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
280                     }
281                 }
282             }
283         } catch (SourceException e) {
284             throw Throwables.propagate(e);
285         }
286         if (!sourcesToProgress.isEmpty()) {
287             SomeModifiersUnresolvedException buildFailure = new SomeModifiersUnresolvedException(currentPhase);
288             buildFailure = addSourceExceptions(buildFailure, sourcesToProgress);
289             throw buildFailure;
290         }
291     }
292
293     private  void endPhase(final ModelProcessingPhase phase) {
294         Preconditions.checkState(currentPhase == phase);
295         finishedPhase = currentPhase;
296     }
297
298     public Set<SourceSpecificContext> getSources() {
299         return sources;
300     }
301 }