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