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