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