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