Correct mandatory leaf enforcement
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractNodeContainerModificationStrategy.java
1 /*
2  * Copyright (c) 2014 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.data.impl.schema.tree;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Verify;
16 import java.util.Collection;
17 import java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
32 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
33 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
34
35 abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
36         extends SchemaAwareApplyOperation<T> {
37     abstract static class Invisible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
38         private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
39
40         Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
41                 final SchemaAwareApplyOperation<T> entryStrategy) {
42             super(support, treeConfig);
43             this.entryStrategy = requireNonNull(entryStrategy);
44         }
45
46         @Override
47         final T getSchema() {
48             return entryStrategy.getSchema();
49         }
50
51         final Optional<ModificationApplyOperation> entryStrategy() {
52             return Optional.of(entryStrategy);
53         }
54
55         @Override
56         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
57             return super.addToStringAttributes(helper).add("entry", entryStrategy);
58         }
59     }
60
61     abstract static class Visible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
62         private final @NonNull T schema;
63
64         Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
65             final T schema) {
66             super(support, treeConfig);
67             this.schema = requireNonNull(schema);
68         }
69
70         @Override
71         final T getSchema() {
72             return schema;
73         }
74
75         @Override
76         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
77             return super.addToStringAttributes(helper).add("schema", schema);
78         }
79     }
80
81     private final NormalizedNodeContainerSupport<?, ?> support;
82     private final boolean verifyChildrenStructure;
83
84     AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
85             final DataTreeConfiguration treeConfig) {
86         this.support = requireNonNull(support);
87         this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
88     }
89
90     @Override
91     protected final ChildTrackingPolicy getChildPolicy() {
92         return support.childPolicy;
93     }
94
95     @Override
96     final void verifyValue(final NormalizedNode<?, ?> writtenValue) {
97         final Class<?> nodeClass = support.requiredClass;
98         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
99         checkArgument(writtenValue instanceof NormalizedNodeContainer);
100     }
101
102     @Override
103     final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
104         if (verifyChildrenStructure) {
105             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
106             for (final Object child : container.getValue()) {
107                 checkArgument(child instanceof NormalizedNode);
108                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
109                 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
110                 if (childOp.isPresent()) {
111                     childOp.get().fullVerifyStructure(castedChild);
112                 } else {
113                     throw new SchemaValidationFailedException(String.format(
114                             "Node %s is not a valid child of %s according to the schema.",
115                             castedChild.getIdentifier(), container.getIdentifier()));
116                 }
117             }
118
119             optionalVerifyValueChildren(writtenValue);
120         }
121         mandatoryVerifyValueChildren(writtenValue);
122     }
123
124     /**
125      * Perform additional verification on written value's child structure, like presence of mandatory children and
126      * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
127      *
128      * @param writtenValue Effective written value
129      */
130     void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
131         // Defaults to no-op
132     }
133
134     /**
135      * Perform additional verification on written value's child structure, like presence of mandatory children.
136      * The default implementation does nothing.
137      *
138      * @param writtenValue Effective written value
139      */
140     void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
141         // Defaults to no-op
142     }
143
144     @Override
145     protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
146         final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
147         for (final Object child : container.getValue()) {
148             checkArgument(child instanceof NormalizedNode);
149             final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
150             final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
151             if (!childOp.isPresent()) {
152                 throw new SchemaValidationFailedException(
153                     String.format("Node %s is not a valid child of %s according to the schema.",
154                         castedChild.getIdentifier(), container.getIdentifier()));
155             }
156
157             childOp.get().recursivelyVerifyStructure(castedChild);
158         }
159     }
160
161     @Override
162     protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
163             final Optional<TreeNode> currentMeta, final Version version) {
164         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
165
166         if (modification.getChildren().isEmpty()) {
167             return newValueMeta;
168         }
169
170         /*
171          * This is where things get interesting. The user has performed a write and
172          * then she applied some more modifications to it. So we need to make sense
173          * of that an apply the operations on top of the written value. We could have
174          * done it during the write, but this operation is potentially expensive, so
175          * we have left it out of the fast path.
176          *
177          * As it turns out, once we materialize the written data, we can share the
178          * code path with the subtree change. So let's create an unsealed TreeNode
179          * and run the common parts on it -- which end with the node being sealed.
180          *
181          * FIXME: this code needs to be moved out from the prepare() path and into
182          *        the read() and seal() paths. Merging of writes needs to be charged
183          *        to the code which originated this, not to the code which is
184          *        attempting to make it visible.
185          */
186         final MutableTreeNode mutable = newValueMeta.mutable();
187         mutable.setSubtreeVersion(version);
188
189         @SuppressWarnings("rawtypes")
190         final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
191         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
192
193         // We are good to go except one detail: this is a single logical write, but
194         // we have a result TreeNode which has been forced to materialized, e.g. it
195         // is larger than it needs to be. Create a new TreeNode to host the data.
196         return TreeNodeFactory.createTreeNode(result.getData(), version);
197     }
198
199     /**
200      * Applies write/remove diff operation for each modification child in modification subtree.
201      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
202      *
203      * @param meta MutableTreeNode (IndexTreeNode)
204      * @param data DataBuilder
205      * @param nodeVersion Version of TreeNode
206      * @param modifications modification operations to apply
207      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
208      */
209     @SuppressWarnings({ "rawtypes", "unchecked" })
210     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
211             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
212
213         for (final ModifiedNode mod : modifications) {
214             final PathArgument id = mod.getIdentifier();
215             final Optional<TreeNode> cm = meta.getChild(id);
216
217             final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
218             if (result.isPresent()) {
219                 final TreeNode tn = result.get();
220                 meta.addChild(tn);
221                 data.addChild(tn.getData());
222             } else {
223                 meta.removeChild(id);
224                 data.removeChild(id);
225             }
226         }
227
228         meta.setData(data.build());
229         return meta.seal();
230     }
231
232     @Override
233     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
234         /*
235          * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
236          * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
237          * heavy lifting of applying the children recursively (either through here or through applyWrite().
238          */
239         final NormalizedNode<?, ?> value = modification.getWrittenValue();
240
241         Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
242         @SuppressWarnings({"unchecked", "rawtypes"})
243         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
244         for (final NormalizedNode<?, ?> c : children) {
245             final PathArgument id = c.getIdentifier();
246             modification.modifyChild(id, resolveChildOperation(id), version);
247         }
248         return applyTouch(modification, currentMeta, version);
249     }
250
251     private void mergeChildrenIntoModification(final ModifiedNode modification,
252             final Collection<NormalizedNode<?, ?>> children, final Version version) {
253         for (final NormalizedNode<?, ?> c : children) {
254             final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
255             final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
256             childOp.mergeIntoModifiedNode(childNode, c, version);
257         }
258     }
259
260     @Override
261     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
262             final Version version) {
263         @SuppressWarnings({ "unchecked", "rawtypes" })
264         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
265
266         switch (modification.getOperation()) {
267             case NONE:
268                 // Fresh node, just record a MERGE with a value
269                 recursivelyVerifyStructure(value);
270                 modification.updateValue(LogicalOperation.MERGE, value);
271                 return;
272             case TOUCH:
273
274                 mergeChildrenIntoModification(modification, children, version);
275                 // We record empty merge value, since real children merges
276                 // are already expanded. This is needed to satisfy non-null for merge
277                 // original merge value can not be used since it mean different
278                 // order of operation - parent changes are always resolved before
279                 // children ones, and having node in TOUCH means children was modified
280                 // before.
281                 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
282                 return;
283             case MERGE:
284                 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
285                 // as MERGE, invalidating cached snapshot
286                 mergeChildrenIntoModification(modification, children, version);
287                 modification.updateOperationType(LogicalOperation.MERGE);
288                 return;
289             case DELETE:
290                 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
291                 // we are really performing a write. One thing that ruins that are any child modifications. If there
292                 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
293                 // and then append any child entries.
294                 if (!modification.getChildren().isEmpty()) {
295                     // Version does not matter here as we'll throw it out
296                     final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
297                         Version.initial());
298                     if (current.isPresent()) {
299                         modification.updateValue(LogicalOperation.WRITE, current.get().getData());
300                         mergeChildrenIntoModification(modification, children, version);
301                         return;
302                     }
303                 }
304
305                 modification.updateValue(LogicalOperation.WRITE, value);
306                 return;
307             case WRITE:
308                 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
309                 // ModifiedNode and run recursively on it
310                 mergeChildrenIntoModification(modification, children, version);
311                 modification.updateOperationType(LogicalOperation.WRITE);
312                 return;
313             default:
314                 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
315         }
316     }
317
318     @Override
319     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
320         /*
321          * The user may have issued an empty merge operation. In this case we do not perform
322          * a data tree mutation, do not pass GO, and do not collect useless garbage. It
323          * also means the ModificationType is UNMODIFIED.
324          */
325         final Collection<ModifiedNode> children = modification.getChildren();
326         if (!children.isEmpty()) {
327             @SuppressWarnings("rawtypes")
328             final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
329             final MutableTreeNode newMeta = currentMeta.mutable();
330             newMeta.setSubtreeVersion(version);
331             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
332
333             /*
334              * It is possible that the only modifications under this node were empty merges,
335              * which were turned into UNMODIFIED. If that is the case, we can turn this operation
336              * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
337              * of speeding up any users, who can skip processing child nodes.
338              *
339              * In order to do that, though, we have to check all child operations are UNMODIFIED.
340              * Let's do precisely that, stopping as soon we find a different result.
341              */
342             for (final ModifiedNode child : children) {
343                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
344                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
345                     return ret;
346                 }
347             }
348         }
349
350         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
351         // replace the metadata node.
352         modification.resolveModificationType(ModificationType.UNMODIFIED);
353         return currentMeta;
354     }
355
356     @Override
357     protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
358             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
359         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
360             final YangInstanceIdentifier id = path.toInstanceIdentifier();
361             throw new ModifiedNodeDoesNotExistException(id,
362                 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
363         }
364
365         checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
366         checkChildPreconditions(path, modification, current.get(), version);
367     }
368
369     @Override
370     protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
371             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
372         if (current.isPresent()) {
373             checkChildPreconditions(path, modification, current.get(), version);
374         }
375     }
376
377     /**
378      * Recursively check child preconditions.
379      *
380      * @param path current node path
381      * @param modification current modification
382      * @param current Current data tree node.
383      */
384     private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
385             final TreeNode current, final Version version) throws DataValidationFailedException {
386         for (final NodeModification childMod : modification.getChildren()) {
387             final PathArgument childId = childMod.getIdentifier();
388             final Optional<TreeNode> childMeta = current.getChild(childId);
389
390             path.push(childId);
391             try {
392                 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
393             } finally {
394                 path.pop();
395             }
396         }
397     }
398
399     @Override
400     public final String toString() {
401         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
402     }
403
404     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
405         return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);
406     }
407 }