14d450d56714d76082c7735d372e65e64200954d
[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_LINKAGE)
54             .add(ModelProcessingPhase.STATEMENT_DEFINITION)
55             .add(ModelProcessingPhase.FULL_DECLARATION)
56             .add(ModelProcessingPhase.EFFECTIVE_MODEL)
57             .build();
58
59     private final Map<QName,StatementDefinitionContext<?,?,?>> definitions = new HashMap<>();
60     private final Map<Class<?>,NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
61
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         Set<Entry<ValidationBundleType, Collection<?>>> validationBundles = supportedValidation.entrySet();
79         for (Entry<ValidationBundleType, Collection<?>> validationBundle : validationBundles) {
80             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
81         }
82     }
83
84     public StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
85         return supports.get(currentPhase);
86     }
87
88     public void addSource(@Nonnull final StatementStreamSource source) {
89         sources.add(new SourceSpecificContext(this,source));
90     }
91
92     @Override
93     public StorageNodeType getStorageNodeType() {
94         return StorageNodeType.GLOBAL;
95     }
96
97     @Override
98     public NamespaceStorageNode getParentNamespaceStorage() {
99         return null;
100     }
101
102     @Override
103     public NamespaceBehaviour.Registry getBehaviourRegistry() {
104         return this;
105     }
106
107     @Override
108     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(final Class<N> type) {
109         NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
110         if (potential == null) {
111             NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
112             if(potentialRaw != null) {
113                 potential = createNamespaceContext(potentialRaw);
114                 supportedNamespaces.put(type, potential);
115             } else {
116                 throw new NamespaceNotAvailableException(
117                         "Namespace " + type + " is not available in phase " + currentPhase);
118             }
119         }
120
121         Verify.verify(type.equals(potential.getIdentifier()));
122             /*
123          * Safe cast, previous checkState checks equivalence of key from which type argument are
124          * derived
125          */
126         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
127     }
128
129     @SuppressWarnings({"unchecked", "rawtypes"})
130     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
131             final NamespaceBehaviour<K, V, N> potentialRaw) {
132         if (potentialRaw instanceof DerivedNamespaceBehaviour) {
133             VirtualNamespaceContext derivedContext =
134                     new VirtualNamespaceContext((DerivedNamespaceBehaviour) potentialRaw);
135             getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom())
136                     .addDerivedNamespace(derivedContext);
137             return derivedContext;
138         }
139         return new SimpleNamespaceContext<>(potentialRaw);
140     }
141
142     public StatementDefinitionContext<?, ?, ?> getStatementDefinition(final QName name) {
143         StatementDefinitionContext<?, ?, ?> potential = definitions.get(name);
144         if(potential == null) {
145             StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(name);
146             if(potentialRaw != null) {
147                 potential = new StatementDefinitionContext<>(potentialRaw);
148                 definitions.put(name, potential);
149             }
150         }
151         return potential;
152     }
153
154     public EffectiveModelContext build() throws SourceException, ReactorException {
155         for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
156             startPhase(phase);
157             loadPhaseStatements();
158             completePhaseActions();
159             endPhase(phase);
160         }
161         return transform();
162     }
163
164     private EffectiveModelContext transform() {
165         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
166         List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
167         for(SourceSpecificContext source : sources) {
168             DeclaredStatement<?> root = source.getRoot().buildDeclared();
169             rootStatements.add(root);
170         }
171         return new EffectiveModelContext(rootStatements);
172     }
173
174     public EffectiveSchemaContext buildEffective() throws SourceException, ReactorException {
175         for(ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
176             startPhase(phase);
177             loadPhaseStatements();
178             completePhaseActions();
179             endPhase(phase);
180         }
181         return transformEffective();
182     }
183
184     private EffectiveSchemaContext transformEffective() {
185         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
186         List<DeclaredStatement<?>> rootStatements = new ArrayList<>();
187         List<EffectiveStatement<?,?>> rootEffectiveStatements = new ArrayList<>();
188
189         for(SourceSpecificContext source : sources) {
190             DeclaredStatement<?> root = source.getRoot().buildDeclared();
191             rootStatements.add(root);
192
193             EffectiveStatement<?,?> rootEffective = source.getRoot().buildEffective();
194             rootEffectiveStatements.add(rootEffective);
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
302 }