Augments should get disabled if target is unsupported
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / augment / AbstractAugmentStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.rfc7950.stmt.augment;
9
10 import static com.google.common.base.Verify.verify;
11
12 import com.google.common.base.Verify;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Lists;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.List;
19 import java.util.Objects;
20 import java.util.Optional;
21 import java.util.regex.Pattern;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.YangVersion;
24 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.Status;
26 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
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.stmt.AugmentEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.AugmentStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.DataDefinitionStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.api.stmt.StatusEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.UsesStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.WhenEffectiveStatement;
36 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.ArgumentUtils;
37 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
38 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.EffectiveStatementWithFlags.FlagsBuilder;
39 import org.opendaylight.yangtools.yang.parser.spi.SchemaTreeNamespace;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
41 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
42 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
43 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
44 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
45 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
48 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
49 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
50 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
51 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace;
52 import org.opendaylight.yangtools.yang.parser.spi.validation.ValidationBundlesNamespace.ValidationBundleType;
53 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 abstract class AbstractAugmentStatementSupport
58         extends BaseStatementSupport<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> {
59     private static final Logger LOG = LoggerFactory.getLogger(AbstractAugmentStatementSupport.class);
60     private static final Pattern PATH_REL_PATTERN1 = Pattern.compile("\\.\\.?\\s*/(.+)");
61     private static final Pattern PATH_REL_PATTERN2 = Pattern.compile("//.*");
62
63     AbstractAugmentStatementSupport() {
64         super(YangStmtMapping.AUGMENT);
65     }
66
67     @Override
68     public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
69         SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
70             || PATH_REL_PATTERN2.matcher(value).matches(), ctx.getStatementSourceReference(),
71             "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
72             value);
73
74         return ArgumentUtils.nodeIdentifierFromPath(ctx, value);
75     }
76
77     @Override
78     public final void onFullDefinitionDeclared(
79             final Mutable<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> augmentNode) {
80         if (!augmentNode.isSupportedByFeatures()) {
81             // We need this augment node to be present, but it should not escape to effective world
82             augmentNode.setIsSupportedToBuildEffective(false);
83         }
84
85         super.onFullDefinitionDeclared(augmentNode);
86
87         if (StmtContextUtils.isInExtensionBody(augmentNode)) {
88             return;
89         }
90
91         final ModelActionBuilder augmentAction = augmentNode.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
92         augmentAction.requiresCtx(augmentNode, ModelProcessingPhase.EFFECTIVE_MODEL);
93         final Prerequisite<Mutable<?, ?, EffectiveStatement<?, ?>>> target = augmentAction.mutatesEffectiveCtxPath(
94             getSearchRoot(augmentNode), SchemaTreeNamespace.class,
95             augmentNode.coerceStatementArgument().getNodeIdentifiers());
96
97         augmentAction.apply(new InferenceAction() {
98             @Override
99             public void apply(final InferenceContext ctx) {
100                 if (!augmentNode.isSupportedToBuildEffective()) {
101                     // We are not building effective model, hence we should not be performing any effects
102                     return;
103                 }
104
105                 final StatementContextBase<?, ?, ?> augmentTargetCtx =
106                         (StatementContextBase<?, ?, ?>) target.resolve(ctx);
107                 if (!isSupportedAugmentTarget(augmentTargetCtx)
108                         || StmtContextUtils.isInExtensionBody(augmentTargetCtx)) {
109                     augmentNode.setIsSupportedToBuildEffective(false);
110                     return;
111                 }
112
113                 // We are targeting a context which is creating implicit nodes. In order to keep things consistent,
114                 // we will need to circle back when creating effective statements.
115                 if (augmentTargetCtx.hasImplicitParentSupport()) {
116                     augmentNode.addToNs(AugmentImplicitHandlingNamespace.class, augmentNode, augmentTargetCtx);
117                 }
118
119                 final StatementContextBase<?, ?, ?> augmentSourceCtx = (StatementContextBase<?, ?, ?>) augmentNode;
120                 // FIXME: this is a workaround for models which augment a node which is added via an extension
121                 //        which we do not handle. This needs to be reworked in terms of unknown schema nodes.
122                 try {
123                     copyFromSourceToTarget(augmentSourceCtx, augmentTargetCtx);
124                     augmentTargetCtx.addEffectiveSubstatement(augmentSourceCtx);
125                 } catch (final SourceException e) {
126                     LOG.warn("Failed to add augmentation {} defined at {}",
127                         augmentTargetCtx.getStatementSourceReference(),
128                             augmentSourceCtx.getStatementSourceReference(), e);
129                 }
130             }
131
132             @Override
133             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
134                 /*
135                  * Do not fail, if it is an uses-augment to an unknown node.
136                  */
137                 if (YangStmtMapping.USES == augmentNode.coerceParentContext().getPublicDefinition()) {
138                     final SchemaNodeIdentifier augmentArg = augmentNode.coerceStatementArgument();
139                     final Optional<StmtContext<?, ?, ?>> targetNode = SchemaTreeNamespace.findNode(
140                         getSearchRoot(augmentNode), augmentArg);
141                     if (targetNode.isPresent() && StmtContextUtils.isUnknownStatement(targetNode.get())) {
142                         augmentNode.setIsSupportedToBuildEffective(false);
143                         LOG.warn("Uses-augment to unknown node {}. Augmentation has not been performed. At line: {}",
144                             augmentArg, augmentNode.getStatementSourceReference());
145                         return;
146                     }
147                 }
148
149                 throw new InferenceException(augmentNode.getStatementSourceReference(),
150                         "Augment target '%s' not found", augmentNode.getStatementArgument());
151             }
152
153             @Override
154             public void prerequisiteUnavailable(final Prerequisite<?> unavail) {
155                 if (target.equals(unavail)) {
156                     augmentNode.setIsSupportedToBuildEffective(false);
157                 } else {
158                     prerequisiteFailed(List.of(unavail));
159                 }
160             }
161         });
162     }
163
164     @Override
165     protected final AugmentStatement createDeclared(final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx,
166             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
167         return new RegularAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument(),
168             substatements);
169     }
170
171     @Override
172     protected final AugmentStatement createEmptyDeclared(
173             final StmtContext<SchemaNodeIdentifier, AugmentStatement, ?> ctx) {
174         return new EmptyAugmentStatement(ctx.coerceRawStatementArgument(), ctx.coerceStatementArgument());
175     }
176
177     @Override
178     protected final List<? extends StmtContext<?, ?, ?>> statementsToBuild(
179             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
180             final List<? extends StmtContext<?, ?, ?>> substatements) {
181         final StatementContextBase<?, ?, ?> implicitDef = ctx.getFromNamespace(AugmentImplicitHandlingNamespace.class,
182             ctx);
183         return implicitDef == null ? substatements : Lists.transform(substatements, subCtx -> {
184             verify(subCtx instanceof StatementContextBase);
185             return implicitDef.wrapWithImplicit((StatementContextBase<?, ?, ?>) subCtx);
186         });
187     }
188
189     @Override
190     protected final AugmentEffectiveStatement createEffective(
191             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
192             final AugmentStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
193         final int flags = new FlagsBuilder()
194                 .setStatus(findFirstArgument(substatements, StatusEffectiveStatement.class, Status.CURRENT))
195                 .toFlags();
196
197         return new AugmentEffectiveStatementImpl(declared, ctx.coerceStatementArgument(), flags,
198             StmtContextUtils.getRootModuleQName(ctx), substatements, ctx.getStatementSourceReference(),
199             (AugmentationSchemaNode) ctx.getOriginalCtx().map(StmtContext::buildEffective).orElse(null));
200     }
201
202     @Override
203     protected final AugmentEffectiveStatement createEmptyEffective(
204             final StmtContext<SchemaNodeIdentifier, AugmentStatement, AugmentEffectiveStatement> ctx,
205             final AugmentStatement declared) {
206         return createEffective(ctx, declared, ImmutableList.of());
207     }
208
209     private static StmtContext<?, ?, ?> getSearchRoot(final StmtContext<?, ?, ?> augmentContext) {
210         // Augment is in uses - we need to augment instantiated nodes in parent.
211         final StmtContext<?, ?, ?> parent = augmentContext.coerceParentContext();
212         if (YangStmtMapping.USES == parent.getPublicDefinition()) {
213             return parent.getParentContext();
214         }
215         return parent;
216     }
217
218     static void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
219             final StatementContextBase<?, ?, ?> targetCtx) {
220         final CopyType typeOfCopy = sourceCtx.coerceParentContext().producesDeclared(UsesStatement.class)
221                 ? CopyType.ADDED_BY_USES_AUGMENTATION : CopyType.ADDED_BY_AUGMENTATION;
222         /*
223          * Since Yang 1.1, if an augmentation is made conditional with a
224          * "when" statement, it is allowed to add mandatory nodes.
225          */
226         final boolean skipCheckOfMandatoryNodes = YangVersion.VERSION_1_1.equals(sourceCtx.getRootVersion())
227                 && isConditionalAugmentStmt(sourceCtx);
228         final boolean unsupported = !sourceCtx.isSupportedByFeatures();
229
230         final Collection<? extends Mutable<?, ?, ?>> declared = sourceCtx.mutableDeclaredSubstatements();
231         final Collection<? extends Mutable<?, ?, ?>> effective = sourceCtx.mutableEffectiveSubstatements();
232         final Collection<Mutable<?, ?, ?>> buffer = new ArrayList<>(declared.size() + effective.size());
233
234         for (final Mutable<?, ?, ?> originalStmtCtx : declared) {
235             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes,
236                 unsupported || !originalStmtCtx.isSupportedByFeatures());
237         }
238         for (final Mutable<?, ?, ?> originalStmtCtx : effective) {
239             copyStatement(originalStmtCtx, targetCtx, typeOfCopy, buffer, skipCheckOfMandatoryNodes, unsupported);
240         }
241
242         targetCtx.addEffectiveSubstatements(buffer);
243     }
244
245     /**
246      * Checks whether supplied statement context is conditional augment
247      * statement.
248      *
249      * @param ctx
250      *            statement context to be checked
251      *
252      * @return true if supplied statement context is conditional augment
253      *         statement, otherwise false
254      */
255     private static boolean isConditionalAugmentStmt(final StmtContext<?, ?, ?> ctx) {
256         return ctx.getPublicDefinition() == YangStmtMapping.AUGMENT && hasWhenSubstatement(ctx);
257     }
258
259     private static boolean hasWhenSubstatement(final StmtContext<?, ?, ?> ctx) {
260         return ctx.hasSubstatement(WhenEffectiveStatement.class);
261     }
262
263     private static void copyStatement(final Mutable<?, ?, ?> original, final StatementContextBase<?, ?, ?> target,
264             final CopyType typeOfCopy, final Collection<Mutable<?, ?, ?>> buffer,
265             final boolean skipCheckOfMandatoryNodes, final boolean unsupported) {
266         // We always copy statements, but if either the source statement or the augmentation which causes it are not
267         // supported to build we also mark the target as such.
268         if (needToCopyByAugment(original)) {
269             validateNodeCanBeCopiedByAugment(original, target, typeOfCopy, skipCheckOfMandatoryNodes);
270
271             final Mutable<?, ?, ?> copy = target.childCopyOf(original, typeOfCopy);
272             if (unsupported) {
273                 copy.setIsSupportedToBuildEffective(false);
274             }
275             buffer.add(copy);
276         } else if (isReusedByAugment(original) && !unsupported) {
277             buffer.add(original);
278         }
279     }
280
281     private static void validateNodeCanBeCopiedByAugment(final StmtContext<?, ?, ?> sourceCtx,
282             final StatementContextBase<?, ?, ?> targetCtx, final CopyType typeOfCopy,
283             final boolean skipCheckOfMandatoryNodes) {
284         if (!skipCheckOfMandatoryNodes && typeOfCopy == CopyType.ADDED_BY_AUGMENTATION
285                 && requireCheckOfMandatoryNodes(sourceCtx, targetCtx)) {
286             checkForMandatoryNodes(sourceCtx);
287         }
288
289         // Data definition statements must not collide on their namespace
290         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
291             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
292                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
293                     InferenceException.throwIf(
294                         Objects.equals(sourceCtx.getStatementArgument(), subStatement.getStatementArgument()),
295                         sourceCtx.getStatementSourceReference(),
296                         "An augment cannot add node named '%s' because this name is already used in target",
297                         sourceCtx.rawStatementArgument());
298                 }
299             }
300         }
301     }
302
303     private static void checkForMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx) {
304         if (StmtContextUtils.isNonPresenceContainer(sourceCtx)) {
305             /*
306              * We need to iterate over both declared and effective sub-statements,
307              * because a mandatory node can be:
308              * a) declared in augment body
309              * b) added to augment body also via uses of a grouping and
310              * such sub-statements are stored in effective sub-statements collection.
311              */
312             sourceCtx.allSubstatementsStream().forEach(AbstractAugmentStatementSupport::checkForMandatoryNodes);
313         }
314
315         InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx),
316                 sourceCtx.getStatementSourceReference(),
317                 "An augment cannot add node '%s' because it is mandatory and in module different than target",
318                 sourceCtx.rawStatementArgument());
319     }
320
321     private static boolean requireCheckOfMandatoryNodes(final StmtContext<?, ?, ?> sourceCtx,
322             Mutable<?, ?, ?> targetCtx) {
323         /*
324          * If the statement argument is not QName, it cannot be mandatory
325          * statement, therefore return false and skip mandatory nodes validation
326          */
327         final Object arg = sourceCtx.getStatementArgument();
328         if (!(arg instanceof QName)) {
329             return false;
330         }
331         final QName sourceStmtQName = (QName) arg;
332
333         // RootStatementContext, for example
334         final Mutable<?, ?, ?> root = targetCtx.getRoot();
335         do {
336             final Object targetArg = targetCtx.getStatementArgument();
337             Verify.verify(targetArg instanceof QName, "Argument of augment target statement must be QName, not %s",
338                 targetArg);
339             final QName targetStmtQName = (QName) targetArg;
340             /*
341              * If target is from another module, return true and perform mandatory nodes validation
342              */
343             if (!targetStmtQName.getModule().equals(sourceStmtQName.getModule())) {
344                 return true;
345             }
346
347             /*
348              * If target or one of the target's ancestors from the same namespace
349              * is a presence container
350              * or is non-mandatory choice
351              * or is non-mandatory list
352              * return false and skip mandatory nodes validation, because these nodes
353              * are not mandatory node containers according to RFC 6020 section 3.1.
354              */
355             if (StmtContextUtils.isPresenceContainer(targetCtx)
356                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.CHOICE)
357                     || StmtContextUtils.isNotMandatoryNodeOfType(targetCtx, YangStmtMapping.LIST)) {
358                 return false;
359             }
360
361             // This could be an augmentation stacked on top of a previous augmentation from the same module, which is
362             // conditional -- in which case we do not run further checks
363             if (targetCtx.getCopyHistory().getLastOperation() == CopyType.ADDED_BY_AUGMENTATION) {
364                 final Optional<? extends StmtContext<?, ?, ?>> optPrevCopy = targetCtx.getPreviousCopyCtx();
365                 if (optPrevCopy.isPresent()) {
366                     final StmtContext<?, ?, ?> original = optPrevCopy.get();
367                     final Object origArg = original.coerceStatementArgument();
368                     Verify.verify(origArg instanceof QName, "Unexpected statement argument %s", origArg);
369
370                     if (sourceStmtQName.getModule().equals(((QName) origArg).getModule())
371                             && hasWhenSubstatement(getParentAugmentation(original))) {
372                         return false;
373                     }
374                 }
375             }
376         } while ((targetCtx = targetCtx.getParentContext()) != root);
377
378         /*
379          * All target node's parents belong to the same module as source node,
380          * therefore return false and skip mandatory nodes validation.
381          */
382         return false;
383     }
384
385     private static StmtContext<?, ?, ?> getParentAugmentation(final StmtContext<?, ?, ?> child) {
386         StmtContext<?, ?, ?> parent = Verify.verifyNotNull(child.getParentContext(), "Child %s has not parent", child);
387         while (parent.getPublicDefinition() != YangStmtMapping.AUGMENT) {
388             parent = Verify.verifyNotNull(parent.getParentContext(), "Failed to find augmentation parent of %s", child);
389         }
390         return parent;
391     }
392
393     private static final ImmutableSet<YangStmtMapping> NOCOPY_DEF_SET = ImmutableSet.of(YangStmtMapping.USES,
394         YangStmtMapping.WHEN, YangStmtMapping.DESCRIPTION, YangStmtMapping.REFERENCE, YangStmtMapping.STATUS);
395
396     private static boolean needToCopyByAugment(final StmtContext<?, ?, ?> stmtContext) {
397         return !NOCOPY_DEF_SET.contains(stmtContext.getPublicDefinition());
398     }
399
400     private static final ImmutableSet<YangStmtMapping> REUSED_DEF_SET = ImmutableSet.of(YangStmtMapping.TYPEDEF);
401
402     private static boolean isReusedByAugment(final StmtContext<?, ?, ?> stmtContext) {
403         return REUSED_DEF_SET.contains(stmtContext.getPublicDefinition());
404     }
405
406     static boolean isSupportedAugmentTarget(final StmtContext<?, ?, ?> substatementCtx) {
407         /*
408          * :TODO Substatement must be allowed augment target type e.g.
409          * Container, etc... and must not be for example grouping, identity etc.
410          * It is problem in case when more than one substatements have the same
411          * QName, for example Grouping and Container are siblings and they have
412          * the same QName. We must find the Container and the Grouping must be
413          * ignored as disallowed augment target.
414          */
415         final Collection<?> allowedAugmentTargets = substatementCtx.getFromNamespace(
416             ValidationBundlesNamespace.class, ValidationBundleType.SUPPORTED_AUGMENT_TARGETS);
417
418         // if no allowed target is returned we consider all targets allowed
419         return allowedAugmentTargets == null || allowedAugmentTargets.isEmpty()
420                 || allowedAugmentTargets.contains(substatementCtx.getPublicDefinition());
421     }
422 }