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