5fc5db2061aeedd89c0a82bba01b468b56630549
[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.ImmutableSet;
15 import com.google.common.collect.Lists;
16 import com.google.common.collect.Table;
17 import com.google.common.collect.TreeBasedTable;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.SortedMap;
31 import javax.annotation.Nonnull;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
34 import org.opendaylight.yangtools.yang.common.YangVersion;
35 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
36 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
37 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.meta.IdentifierNamespace;
39 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
40 import org.opendaylight.yangtools.yang.model.repo.api.StatementParserMode;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.DerivedNamespaceBehaviour;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.MutableStatement;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.NamespaceStorageNode;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceNotAvailableException;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.SomeModifiersUnresolvedException;
50 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
51 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupportBundle;
52 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
53 import org.opendaylight.yangtools.yang.parser.spi.source.StatementStreamSource;
54 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace;
55 import org.opendaylight.yangtools.yang.parser.spi.source.SupportedFeaturesNamespace.SupportedFeatures;
56 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
57 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
58 import org.opendaylight.yangtools.yang.parser.stmt.reactor.SourceSpecificContext.PhaseCompletionProgress;
59 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.RecursiveObjectLeaker;
60 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.Utils;
61 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.EffectiveSchemaContext;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
66     private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
67
68     private static final List<ModelProcessingPhase> PHASE_EXECUTION_ORDER = ImmutableList
69             .<ModelProcessingPhase> builder().add(ModelProcessingPhase.SOURCE_PRE_LINKAGE)
70             .add(ModelProcessingPhase.SOURCE_LINKAGE).add(ModelProcessingPhase.STATEMENT_DEFINITION)
71             .add(ModelProcessingPhase.FULL_DECLARATION).add(ModelProcessingPhase.EFFECTIVE_MODEL).build();
72
73     private final Table<YangVersion, QName, StatementDefinitionContext<?, ?, ?>> definitions = HashBasedTable.create();
74     private final Map<Class<?>, NamespaceBehaviourWithListeners<?, ?, ?>> supportedNamespaces = new HashMap<>();
75     private final List<MutableStatement> mutableStatementsToSeal = new ArrayList<>();
76     private final Map<ModelProcessingPhase, StatementSupportBundle> supports;
77     private final Set<SourceSpecificContext> sources = new HashSet<>();
78     private final Set<YangVersion> supportedVersions;
79     private final boolean enabledSemanticVersions;
80
81     private Set<SourceSpecificContext> libSources = new HashSet<>();
82     private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
83     private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
84
85     BuildGlobalContext(final Map<ModelProcessingPhase, StatementSupportBundle> supports,
86             final Map<ValidationBundleType, Collection<?>> supportedValidation,
87             final StatementParserMode statementParserMode, final Set<QName> supportedFeatures) {
88         this.supports = Preconditions.checkNotNull(supports, "BuildGlobalContext#supports cannot be null");
89
90         switch (statementParserMode) {
91             case DEFAULT_MODE:
92                 enabledSemanticVersions = false;
93                 break;
94             case SEMVER_MODE:
95                 enabledSemanticVersions = true;
96                 break;
97             default:
98                 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
99         }
100
101         for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
102             addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
103         }
104
105         if (supportedFeatures != null) {
106             addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
107                     ImmutableSet.copyOf(supportedFeatures));
108         }
109         this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
110     }
111
112     boolean isEnabledSemanticVersioning() {
113         return enabledSemanticVersions;
114     }
115
116     StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
117         return supports.get(currentPhase);
118     }
119
120     void addSource(@Nonnull final StatementStreamSource source) {
121         sources.add(new SourceSpecificContext(this, source));
122     }
123
124     void addLibSource(@Nonnull final StatementStreamSource libSource) {
125         Preconditions.checkState(!isEnabledSemanticVersioning(),
126                 "Library sources are not supported in semantic version mode currently.");
127         Preconditions.checkState(currentPhase == ModelProcessingPhase.INIT,
128                 "Add library source is allowed in ModelProcessingPhase.INIT only");
129         libSources.add(new SourceSpecificContext(this, libSource));
130     }
131
132     @Override
133     public StorageNodeType getStorageNodeType() {
134         return StorageNodeType.GLOBAL;
135     }
136
137     @Override
138     public NamespaceStorageNode getParentNamespaceStorage() {
139         return null;
140     }
141
142     @Override
143     public NamespaceBehaviour.Registry getBehaviourRegistry() {
144         return this;
145     }
146
147     @Override
148     public <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> getNamespaceBehaviour(
149             final Class<N> type) {
150         NamespaceBehaviourWithListeners<?, ?, ?> potential = supportedNamespaces.get(type);
151         if (potential == null) {
152             final NamespaceBehaviour<K, V, N> potentialRaw = supports.get(currentPhase).getNamespaceBehaviour(type);
153             if (potentialRaw != null) {
154                 potential = createNamespaceContext(potentialRaw);
155                 supportedNamespaces.put(type, potential);
156             } else {
157                 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
158                         + currentPhase);
159             }
160         }
161
162         Verify.verify(type.equals(potential.getIdentifier()));
163         /*
164          * Safe cast, previous checkState checks equivalence of key from which
165          * type argument are derived
166          */
167         return (NamespaceBehaviourWithListeners<K, V, N>) potential;
168     }
169
170     @SuppressWarnings({ "unchecked", "rawtypes" })
171     private <K, V, N extends IdentifierNamespace<K, V>> NamespaceBehaviourWithListeners<K, V, N> createNamespaceContext(
172             final NamespaceBehaviour<K, V, N> potentialRaw) {
173         if (potentialRaw instanceof DerivedNamespaceBehaviour) {
174             final VirtualNamespaceContext derivedContext = new VirtualNamespaceContext(
175                     (DerivedNamespaceBehaviour) potentialRaw);
176             getNamespaceBehaviour(((DerivedNamespaceBehaviour) potentialRaw).getDerivedFrom()).addDerivedNamespace(
177                     derivedContext);
178             return derivedContext;
179         }
180         return new SimpleNamespaceContext<>(potentialRaw);
181     }
182
183     StatementDefinitionContext<?, ?, ?> getStatementDefinition(final YangVersion version, final QName name) {
184         StatementDefinitionContext<?, ?, ?> potential = definitions.get(version, name);
185         if (potential == null) {
186             final StatementSupport<?, ?, ?> potentialRaw = supports.get(currentPhase).getStatementDefinition(version,
187                     name);
188             if (potentialRaw != null) {
189                 potential = new StatementDefinitionContext<>(potentialRaw);
190                 definitions.put(version, name, potential);
191             }
192         }
193         return potential;
194     }
195
196     private void executePhases() throws ReactorException {
197         for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
198             startPhase(phase);
199             loadPhaseStatements();
200             completePhaseActions();
201             endPhase(phase);
202         }
203     }
204
205     EffectiveModelContext build() throws ReactorException {
206         executePhases();
207         return transform();
208     }
209
210     EffectiveSchemaContext buildEffective() throws ReactorException {
211         executePhases();
212         return transformEffective();
213     }
214
215     private EffectiveModelContext transform() {
216         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
217         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
218         for (final SourceSpecificContext source : sources) {
219             rootStatements.add(source.getRoot().buildDeclared());
220         }
221         return new EffectiveModelContext(rootStatements);
222     }
223
224     private SomeModifiersUnresolvedException propagateException(final SourceSpecificContext source,
225             final RuntimeException cause) throws SomeModifiersUnresolvedException {
226         final SourceIdentifier sourceId = Utils.createSourceIdentifier(source.getRoot());
227         if (!(cause instanceof SourceException)) {
228             /*
229              * This should not be happening as all our processing should provide SourceExceptions.
230              * We will wrap the exception to provide enough information to identify the problematic model,
231              * but also emit a warning so the offending codepath will get fixed.
232              */
233             LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
234                 sourceId, cause);
235         }
236
237         throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
238     }
239
240     private EffectiveSchemaContext transformEffective() throws ReactorException {
241         Preconditions.checkState(finishedPhase == ModelProcessingPhase.EFFECTIVE_MODEL);
242         final List<DeclaredStatement<?>> rootStatements = new ArrayList<>(sources.size());
243         final List<EffectiveStatement<?, ?>> rootEffectiveStatements = new ArrayList<>(sources.size());
244
245         try {
246             for (final SourceSpecificContext source : sources) {
247                 final RootStatementContext<?, ?, ?> root = source.getRoot();
248                 try {
249                     rootStatements.add(root.buildDeclared());
250                     rootEffectiveStatements.add(root.buildEffective());
251                 } catch (final RuntimeException ex) {
252                     throw propagateException(source, ex);
253                 }
254             }
255         } finally {
256             RecursiveObjectLeaker.cleanup();
257         }
258
259         sealMutableStatements();
260         return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
261     }
262
263     private void startPhase(final ModelProcessingPhase phase) {
264         Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
265         startPhaseFor(phase, sources);
266         startPhaseFor(phase, libSources);
267
268         currentPhase = phase;
269         LOG.debug("Global phase {} started", phase);
270     }
271
272     private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
273         for (final SourceSpecificContext source : sources) {
274             source.startPhase(phase);
275         }
276     }
277
278     private void loadPhaseStatements() throws ReactorException {
279         Preconditions.checkState(currentPhase != null);
280         loadPhaseStatementsFor(sources);
281         loadPhaseStatementsFor(libSources);
282     }
283
284     private void loadPhaseStatementsFor(final Set<SourceSpecificContext> sources) throws ReactorException {
285         for (final SourceSpecificContext source : sources) {
286             try {
287                 source.loadStatements();
288             } catch (final RuntimeException ex) {
289                 throw propagateException(source, ex);
290             }
291         }
292     }
293
294     private SomeModifiersUnresolvedException addSourceExceptions(final List<SourceSpecificContext> sourcesToProgress) {
295         boolean addedCause = false;
296         SomeModifiersUnresolvedException buildFailure = null;
297         for (final SourceSpecificContext failedSource : sourcesToProgress) {
298             final Optional<SourceException> optSourceEx = failedSource.failModifiers(currentPhase);
299             if (!optSourceEx.isPresent()) {
300                 continue;
301             }
302
303             final SourceException sourceEx = optSourceEx.get();
304             // Workaround for broken logging implementations which ignore
305             // suppressed exceptions
306             final Throwable cause = sourceEx.getCause() != null ? sourceEx.getCause() : sourceEx;
307             if (LOG.isDebugEnabled()) {
308                 LOG.error("Failed to parse YANG from source {}", failedSource, sourceEx);
309             } else {
310                 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
311             }
312
313             final Throwable[] suppressed = sourceEx.getSuppressed();
314             if (suppressed.length > 0) {
315                 LOG.error("{} additional errors reported:", suppressed.length);
316
317                 int i = 1;
318                 for (final Throwable t : suppressed) {
319                     // FIXME: this should be configured in the appender, really
320                     if (LOG.isDebugEnabled()) {
321                         LOG.error("Error {}: {}", i, t.getMessage(), t);
322                     } else {
323                         LOG.error("Error {}: {}", i, t.getMessage());
324                     }
325
326                     i++;
327                 }
328             }
329
330             if (!addedCause) {
331                 addedCause = true;
332                 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
333                 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
334             } else {
335                 buildFailure.addSuppressed(sourceEx);
336             }
337         }
338         return buildFailure;
339     }
340
341     private void completePhaseActions() throws ReactorException {
342         Preconditions.checkState(currentPhase != null);
343         final List<SourceSpecificContext> sourcesToProgress = Lists.newArrayList(sources);
344         if (!libSources.isEmpty()) {
345             Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
346                     "Yang library sources should be empty after ModelProcessingPhase.SOURCE_PRE_LINKAGE, "
347                             + "but current phase was %s", currentPhase);
348             sourcesToProgress.addAll(libSources);
349         }
350
351         boolean progressing = true;
352         while (progressing) {
353             // We reset progressing to false.
354             progressing = false;
355             final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
356             while (currentSource.hasNext()) {
357                 final SourceSpecificContext nextSourceCtx = currentSource.next();
358                 try {
359                     final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
360                     switch (sourceProgress) {
361                         case FINISHED:
362                             currentSource.remove();
363                             // Fallback to progress, since we were able to make
364                             // progress in computation
365                         case PROGRESS:
366                             progressing = true;
367                             break;
368                         case NO_PROGRESS:
369                             // Noop
370                             break;
371                         default:
372                             throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
373                     }
374                 } catch (final RuntimeException ex) {
375                     throw propagateException(nextSourceCtx, ex);
376                 }
377             }
378         }
379
380         if (!libSources.isEmpty()) {
381             final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
382             sources.addAll(requiredLibs);
383             libSources = ImmutableSet.of();
384             /*
385              * We want to report errors of relevant sources only, so any others can
386              * be removed.
387              */
388             sourcesToProgress.retainAll(sources);
389         }
390
391         if (!sourcesToProgress.isEmpty()) {
392             final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
393             if (buildFailure != null) {
394                 throw buildFailure;
395             }
396         }
397     }
398
399     private Set<SourceSpecificContext> getRequiredSourcesFromLib() {
400         Preconditions.checkState(currentPhase == ModelProcessingPhase.SOURCE_PRE_LINKAGE,
401                 "Required library sources can be collected only in ModelProcessingPhase.SOURCE_PRE_LINKAGE phase,"
402                         + " but current phase was %s", currentPhase);
403         final TreeBasedTable<String, Date, SourceSpecificContext> libSourcesTable = TreeBasedTable.create();
404         for (final SourceSpecificContext libSource : libSources) {
405             final ModuleIdentifier libSourceIdentifier = Preconditions.checkNotNull(libSource.getRootIdentifier());
406             libSourcesTable.put(libSourceIdentifier.getName(), libSourceIdentifier.getRevision(), libSource);
407         }
408
409         final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
410         for (final SourceSpecificContext source : sources) {
411             collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
412         }
413         return requiredLibs;
414     }
415
416     private void collectRequiredSourcesFromLib(
417             final TreeBasedTable<String, Date, SourceSpecificContext> libSourcesTable,
418             final Set<SourceSpecificContext> requiredLibs, final SourceSpecificContext source) {
419         final Collection<ModuleIdentifier> requiredModules = source.getRequiredModules();
420         for (final ModuleIdentifier requiredModule : requiredModules) {
421             final SourceSpecificContext libSource = getRequiredLibSource(requiredModule, libSourcesTable);
422             if (libSource != null && requiredLibs.add(libSource)) {
423                 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, libSource);
424             }
425         }
426     }
427
428     private static SourceSpecificContext getRequiredLibSource(final ModuleIdentifier requiredModule,
429             final TreeBasedTable<String, Date, SourceSpecificContext> libSourcesTable) {
430         return requiredModule.getRevision() == SimpleDateFormatUtil.DEFAULT_DATE_IMP ? getLatestRevision(libSourcesTable
431                 .row(requiredModule.getName())) : libSourcesTable.get(requiredModule.getName(),
432                 requiredModule.getRevision());
433     }
434
435     private static SourceSpecificContext getLatestRevision(final SortedMap<Date, SourceSpecificContext> sourceMap) {
436         return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
437     }
438
439     private void endPhase(final ModelProcessingPhase phase) {
440         Preconditions.checkState(currentPhase == phase);
441         finishedPhase = currentPhase;
442         LOG.debug("Global phase {} finished", phase);
443     }
444
445     Set<SourceSpecificContext> getSources() {
446         return sources;
447     }
448
449     public Set<YangVersion> getSupportedVersions() {
450         return supportedVersions;
451     }
452
453     void addMutableStmtToSeal(final MutableStatement mutableStatement) {
454         mutableStatementsToSeal.add(mutableStatement);
455     }
456
457     void sealMutableStatements() {
458         for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
459             mutableStatement.seal();
460         }
461         mutableStatementsToSeal.clear();
462     }
463 }