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