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