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