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