BUG-7267: catch RuntimeExceptions when processing sources
[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.HashBasedTable;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.ImmutableSet;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.Table;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Objects;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.function.Predicate;
30 import javax.annotation.Nonnull;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.YangVersion;
33 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
34 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
36 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
37 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
48 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
49 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
51 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
52 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
53 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
54 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
55 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.RecursiveObjectLeaker;
56 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
57 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
62     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
63
64     private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList
65             .<ModelProcessingPhase> builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
66             .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
67             .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
68
69     private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
70     private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
71
72     private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
73     private final Set<SourceSpecificContext> sources = new HashSet<>();
74
75     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
76     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
77
78     private final boolean enabledSemanticVersions;
79     private final Set<YangVersion> supportedVersions;
80
81     BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
82             final StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
83         this(supports, ImmutableMap.of(), statementParserMode, isFeatureSupported);
84     }
85
86     BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
87             final Map<ValidationBundleType, Collection<?>> supportedValidation,
88             final StatementParserMode statementParserMode, final Predicate<QName> isFeatureSupported) {
89         super();
90         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
91         Preconditions.checkNotNull(statementParserMode, "Statement parser mode must not be null.");
92         this.enabledSemanticVersions = statementParserMode == StatementParserMode.SEMVER_MODE;
93
94         for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
95             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
96         }
97
98         addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
99                 Preconditions.checkNotNull(isFeatureSupported, "Supported feature predicate must not be null."));
100         this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
101     }
102
103     boolean isEnabledSemanticVersioning() {
104         return enabledSemanticVersions;
105     }
106
107     StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
108         return supports.get(currentPhase);
109     }
110
111     void addSource(@Nonnull final StatementStreamSource source) {
112         sources.add(new SourceSpecificContext(this, source));
113     }
114
115     @Override
116     public StorageNodeType getStorageNodeType() {
117         return StorageNodeType.GLOBAL;
118     }
119
120     @Override
121     public NamespaceStorageNode getParentNamespaceStorage() {
122         return null;
123     }
124
125     @Override
126     public NamespaceBehaviour.Registry getBehaviourRegistry() {
127         return this;
128     }
129
130     @Override
131     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
132             final Class<N> type) {
133         NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
134         if (potential == null) {
135             final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
136             if (potentialRaw != null) {
137                 potential = createNamespaceContext(potentialRaw);
138                 supportedNamespaces.put(type, potential);
139             } else {
140                 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
141                         + currentPhase);
142             }
143         }
144
145         Verify.verify(type.equals(potential.getIdentifier()));
146         /*
147          * Safe cast, previous checkState checks equivalence of key from which
148          * type argument are derived
149          */
150         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
151     }
152
153     @SuppressWarnings({ "unchecked", "rawtypes" })
154     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
155             final NamespaceBehaviour<K, V, N> potentialRaw) {
156         if (potentialRaw instanceof DerivedNamespaceBehaviour) {
157             final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
158                     (DerivedNamespaceBehaviour) potentialRaw);
159             getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
160                     derivedContext);
161             return derivedContext;
162         }
163         return new SimpleNamespaceContext<>(potentialRaw);
164     }
165
166     StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
167         StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
168         if (potential == null) {
169             final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
170                     name);
171             if (potentialRaw != null) {
172                 potential = new StatementDefinitionContext<>(potentialRaw);
173                 definitions.put(version, name, potential);
174             }
175         }
176         return potential;
177     }
178
179     EffectiveModelContext build() throws SourceException, ReactorException {
180         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
181             startPhase(phase);
182             loadPhaseStatements();
183             completePhaseActions();
184             endPhase(phase);
185         }
186         return transform();
187     }
188
189     private EffectiveModelContext transform() {
190         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
191         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
192         for (final SourceSpecificContext source : sources) {
193             rootStatements.add(source.getRoot().buildDeclared());
194         }
195         return new EffectiveModelContext(rootStatements);
196     }
197
198     EffectiveSchemaContext buildEffective() throws ReactorException {
199         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
200             startPhase(phase);
201             loadPhaseStatements();
202             completePhaseActions();
203             endPhase(phase);
204         }
205         return transformEffective();
206     }
207
208     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
209             final RuntimeException cause) throws SomeModifiersUnresolvedException {
210         final SourceIdentifier sourceId = Utils.createSourceIdentifier(source.getRoot());
211         if (!(cause instanceof SourceException)) {
212             /*
213              * This should not be happening as all our processing should provide SourceExceptions.
214              * We will wrap the exception to provide enough information to identify the problematic model,
215              * but also emit a warning so the offending codepath will get fixed.
216              */
217             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
218                 sourceId, cause);
219         }
220
221         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
222     }
223
224     private EffectiveSchemaContext transformEffective() throws ReactorException {
225         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
226         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
227         final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
228
229         try {
230             for (final SourceSpecificContext source : sources) {
231                 final RootStatementContext<?, ?, ?> root = source.getRoot();
232                 try {
233                     rootStatements.add(root.buildDeclared());
234                     rootEffectiveStatements.add(root.buildEffective());
235                 } catch (final RuntimeException ex) {
236                     throw propagateException(source, ex);
237                 }
238             }
239         } finally {
240             RecursiveObjectLeaker.cleanup();
241         }
242
243         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
244     }
245
246     private void startPhase(final ModelProcessingPhase phase) {
247         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
248         for (final SourceSpecificContext source : sources) {
249             source.startPhase(phase);
250         }
251         currentPhase = phase;
252         LOG.debug("Global phase {} started", phase);
253     }
254
255     private void loadPhaseStatements() throws ReactorException {
256         Preconditions.checkState(currentPhase != null);
257         for (final SourceSpecificContext source : sources) {
258             try {
259                 source.loadStatements();
260             } catch (final RuntimeException ex) {
261                 throw propagateException(source, ex);
262             }
263         }
264     }
265
266     private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
267         boolean addedCause = false;
268         SomeModifiersUnresolvedException buildFailure = null;
269         for (final SourceSpecificContext failedSource : sourcesToProgress) {
270             final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
271             if (!optSourceEx.isPresent()) {
272                 continue;
273             }
274
275             final SourceException sourceEx = optSourceEx.get();
276             // Workaround for broken logging implementations which ignore
277             // suppressed exceptions
278             final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
279             if (LOG.isDebugEnabled()) {
280                 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
281             } else {
282                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
283             }
284
285             final Throwable[] suppressed = sourceEx.getSuppressed();
286             if (suppressed.length > 0) {
287                 LOG.error("{} additional errors reported:", suppressed.length);
288
289                 int i = 1;
290                 for (final Throwable t : suppressed) {
291                     // FIXME: this should be configured in the appender, really
292                     if (LOG.isDebugEnabled()) {
293                         LOG.error("Error {}: {}", i, t.getMessage(), t);
294                     } else {
295                         LOG.error("Error {}: {}", i, t.getMessage());
296                     }
297
298                     i++;
299                 }
300             }
301
302             if (!addedCause) {
303                 addedCause = true;
304                 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
305                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
306             } else {
307                 buildFailure.addSuppressed(sourceEx);
308             }
309         }
310         return buildFailure;
311     }
312
313     private void completePhaseActions() throws ReactorException {
314         Preconditions.checkState(currentPhase != null);
315         final List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
316         boolean progressing = true;
317         while (progressing) {
318             // We reset progressing to false.
319             progressing = false;
320             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
321             while (currentSource.hasNext()) {
322                 final SourceSpecificContext nextSourceCtx = currentSource.next();
323                 try {
324                     final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
325                     switch (sourceProgress) {
326                         case FINISHED:
327                             currentSource.remove();
328                             // Fallback to progress, since we were able to make
329                             // progress in computation
330                         case PROGRESS:
331                             progressing = true;
332                             break;
333                         case NO_PROGRESS:
334                             // Noop
335                             break;
336                         default:
337                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
338                     }
339                 } catch (RuntimeException ex) {
340                     throw propagateException(nextSourceCtx, ex);
341                 }
342             }
343         }
344         if (!sourcesToProgress.isEmpty()) {
345             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
346             if (buildFailure != null) {
347                 throw buildFailure;
348             }
349         }
350     }
351
352     private void endPhase(final ModelProcessingPhase phase) {
353         Preconditions.checkState(currentPhase == phase);
354         finishedPhase = currentPhase;
355         LOG.debug("Global phase {} finished", phase);
356     }
357
358     Set<SourceSpecificContext> getSources() {
359         return sources;
360     }
361
362     public Set<YangVersion> getSupportedVersions() {
363         return supportedVersions;
364     }
365 }