2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.parser.stmt.reactor;
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;
26 import java.util.Map.Entry;
27 import java.util.Objects;
28 import java.util.Optional;
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;
65 class BuildGlobalContext extends NamespaceStorageSupport implements NamespaceBehaviour.Registry {
66 private static final Logger LOG = LoggerFactory.getLogger(BuildGlobalContext.class);
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();
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;
81 private Set<SourceSpecificContext> libSources = new HashSet<>();
82 private ModelProcessingPhase currentPhase = ModelProcessingPhase.INIT;
83 private ModelProcessingPhase finishedPhase = ModelProcessingPhase.INIT;
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");
90 switch (statementParserMode) {
92 enabledSemanticVersions = false;
95 enabledSemanticVersions = true;
98 throw new IllegalArgumentException("Unhandled parser mode " + statementParserMode);
101 for (final Entry<ValidationBundleType, Collection<?>> validationBundle : supportedValidation.entrySet()) {
102 addToNs(ValidationBundlesNamespace.class, validationBundle.getKey(), validationBundle.getValue());
105 if (supportedFeatures != null) {
106 addToNs(SupportedFeaturesNamespace.class, SupportedFeatures.SUPPORTED_FEATURES,
107 ImmutableSet.copyOf(supportedFeatures));
109 this.supportedVersions = ImmutableSet.copyOf(supports.get(ModelProcessingPhase.INIT).getSupportedVersions());
112 boolean isEnabledSemanticVersioning() {
113 return enabledSemanticVersions;
116 StatementSupportBundle getSupportsForPhase(final ModelProcessingPhase currentPhase) {
117 return supports.get(currentPhase);
120 void addSource(@Nonnull final StatementStreamSource source) {
121 sources.add(new SourceSpecificContext(this, source));
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));
133 public StorageNodeType getStorageNodeType() {
134 return StorageNodeType.GLOBAL;
138 public NamespaceStorageNode getParentNamespaceStorage() {
143 public NamespaceBehaviour.Registry getBehaviourRegistry() {
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);
157 throw new NamespaceNotAvailableException("Namespace " + type + " is not available in phase "
162 Verify.verify(type.equals(potential.getIdentifier()));
164 * Safe cast, previous checkState checks equivalence of key from which
165 * type argument are derived
167 return (NamespaceBehaviourWithListeners<K, V, N>) potential;
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(
178 return derivedContext;
180 return new SimpleNamespaceContext<>(potentialRaw);
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,
188 if (potentialRaw != null) {
189 potential = new StatementDefinitionContext<>(potentialRaw);
190 definitions.put(version, name, potential);
196 private void executePhases() throws ReactorException {
197 for (final ModelProcessingPhase phase : PHASE_EXECUTION_ORDER) {
199 loadPhaseStatements();
200 completePhaseActions();
205 EffectiveModelContext build() throws ReactorException {
210 EffectiveSchemaContext buildEffective() throws ReactorException {
212 return transformEffective();
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());
221 return new EffectiveModelContext(rootStatements);
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)) {
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.
233 LOG.warn("Unexpected error processing source {}. Please file an issue with this model attached.",
237 throw new SomeModifiersUnresolvedException(currentPhase, sourceId, cause);
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());
246 for (final SourceSpecificContext source : sources) {
247 final RootStatementContext<?, ?, ?> root = source.getRoot();
249 rootStatements.add(root.buildDeclared());
250 rootEffectiveStatements.add(root.buildEffective());
251 } catch (final RuntimeException ex) {
252 throw propagateException(source, ex);
256 RecursiveObjectLeaker.cleanup();
259 sealMutableStatements();
260 return new EffectiveSchemaContext(rootStatements, rootEffectiveStatements);
263 private void startPhase(final ModelProcessingPhase phase) {
264 Preconditions.checkState(Objects.equals(finishedPhase, phase.getPreviousPhase()));
265 startPhaseFor(phase, sources);
266 startPhaseFor(phase, libSources);
268 currentPhase = phase;
269 LOG.debug("Global phase {} started", phase);
272 private static void startPhaseFor(final ModelProcessingPhase phase, final Set<SourceSpecificContext> sources) {
273 for (final SourceSpecificContext source : sources) {
274 source.startPhase(phase);
278 private void loadPhaseStatements() throws ReactorException {
279 Preconditions.checkState(currentPhase != null);
280 loadPhaseStatementsFor(sources);
281 loadPhaseStatementsFor(libSources);
284 private void loadPhaseStatementsFor(final Set<SourceSpecificContext> sources) throws ReactorException {
285 for (final SourceSpecificContext source : sources) {
287 source.loadStatements();
288 } catch (final RuntimeException ex) {
289 throw propagateException(source, ex);
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()) {
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);
310 LOG.error("Failed to parse YANG from source {}: {}", failedSource, cause.getMessage());
313 final Throwable[] suppressed = sourceEx.getSuppressed();
314 if (suppressed.length > 0) {
315 LOG.error("{} additional errors reported:", suppressed.length);
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);
323 LOG.error("Error {}: {}", i, t.getMessage());
332 final SourceIdentifier sourceId = Utils.createSourceIdentifier(failedSource.getRoot());
333 buildFailure = new SomeModifiersUnresolvedException(currentPhase, sourceId, sourceEx);
335 buildFailure.addSuppressed(sourceEx);
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);
351 boolean progressing = true;
352 while (progressing) {
353 // We reset progressing to false.
355 final Iterator<SourceSpecificContext> currentSource = sourcesToProgress.iterator();
356 while (currentSource.hasNext()) {
357 final SourceSpecificContext nextSourceCtx = currentSource.next();
359 final PhaseCompletionProgress sourceProgress = nextSourceCtx.tryToCompletePhase(currentPhase);
360 switch (sourceProgress) {
362 currentSource.remove();
363 // Fallback to progress, since we were able to make
364 // progress in computation
372 throw new IllegalStateException("Unsupported phase progress " + sourceProgress);
374 } catch (final RuntimeException ex) {
375 throw propagateException(nextSourceCtx, ex);
380 if (!libSources.isEmpty()) {
381 final Set<SourceSpecificContext> requiredLibs = getRequiredSourcesFromLib();
382 sources.addAll(requiredLibs);
383 libSources = ImmutableSet.of();
385 * We want to report errors of relevant sources only, so any others can
388 sourcesToProgress.retainAll(sources);
391 if (!sourcesToProgress.isEmpty()) {
392 final SomeModifiersUnresolvedException buildFailure = addSourceExceptions(sourcesToProgress);
393 if (buildFailure != null) {
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);
409 final Set<SourceSpecificContext> requiredLibs = new HashSet<>();
410 for (final SourceSpecificContext source : sources) {
411 collectRequiredSourcesFromLib(libSourcesTable, requiredLibs, source);
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);
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());
435 private static SourceSpecificContext getLatestRevision(final SortedMap<Date, SourceSpecificContext> sourceMap) {
436 return sourceMap != null && !sourceMap.isEmpty() ? sourceMap.get(sourceMap.lastKey()) : null;
439 private void endPhase(final ModelProcessingPhase phase) {
440 Preconditions.checkState(currentPhase == phase);
441 finishedPhase = currentPhase;
442 LOG.debug("Global phase {} finished", phase);
445 Set<SourceSpecificContext> getSources() {
449 public Set<YangVersion> getSupportedVersions() {
450 return supportedVersions;
453 void addMutableStmtToSeal(final MutableStatement mutableStatement) {
454 mutableStatementsToSeal.add(mutableStatement);
457 void sealMutableStatements() {
458 for (final MutableStatement mutableStatement : mutableStatementsToSeal) {
459 mutableStatement.seal();
461 mutableStatementsToSeal.clear();