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