a875c3d55f318c1501e2ba26cf7df60909862ad6
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / SchemaAwareApplyOperation.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 com.google.common.base.Verify.verifyNotNull;
12
13 import java.util.List;
14 import java.util.Optional;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
24 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
25 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
26 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
28 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
29 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
30 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
31 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
40 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
48     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
49
50     static ModificationApplyOperation from(final DataSchemaNode schemaNode,
51             final DataTreeConfiguration treeConfig) throws ExcludedDataSchemaNodeException {
52         if (!belongsToTree(treeConfig.getTreeType(), schemaNode)) {
53             throw new ExcludedDataSchemaNodeException(schemaNode + " does not belong to configuration tree");
54         }
55         if (schemaNode instanceof ContainerSchemaNode container) {
56             return ContainerModificationStrategy.of(container, treeConfig);
57         } else if (schemaNode instanceof ListSchemaNode list) {
58             return fromListSchemaNode(list, treeConfig);
59         } else if (schemaNode instanceof ChoiceSchemaNode choice) {
60             return new ChoiceModificationStrategy(choice, treeConfig);
61         } else if (schemaNode instanceof LeafListSchemaNode leafList) {
62             return MinMaxElementsValidation.from(new LeafSetModificationStrategy(leafList, treeConfig));
63         } else if (schemaNode instanceof LeafSchemaNode leaf) {
64             return new ValueNodeModificationStrategy<>(LeafNode.class, leaf);
65         } else if (schemaNode instanceof AnydataSchemaNode anydata) {
66             return new ValueNodeModificationStrategy<>(AnydataNode.class, anydata);
67         } else if (schemaNode instanceof AnyxmlSchemaNode anyxml) {
68             return new ValueNodeModificationStrategy<>(AnyxmlNode.class, anyxml);
69         } else if (schemaNode instanceof SchemaContext context) {
70             return new StructuralContainerModificationStrategy(context, treeConfig);
71         } else {
72             throw new IllegalStateException("Unsupported schema " + schemaNode);
73         }
74     }
75
76     static @Nullable AugmentationModificationStrategy from(final DataNodeContainer resolvedTree,
77             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
78             final DataTreeConfiguration treeConfig) {
79         for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
80             for (final DataSchemaNode child : potential.getChildNodes()) {
81                 if (identifier.getPossibleChildNames().contains(child.getQName())) {
82                     return new AugmentationModificationStrategy(potential, resolvedTree, treeConfig);
83                 }
84             }
85         }
86
87         return null;
88     }
89
90     static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
91             throws ConflictingModificationAppliedException {
92         if (!condition) {
93             throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
94         }
95     }
96
97     private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
98             final DataTreeConfiguration treeConfig) {
99         final List<QName> keyDefinition = schemaNode.getKeyDefinition();
100         final SchemaAwareApplyOperation<ListSchemaNode> op;
101         if (keyDefinition == null || keyDefinition.isEmpty()) {
102             op = new ListModificationStrategy(schemaNode, treeConfig);
103         } else {
104             op = MapModificationStrategy.of(schemaNode, treeConfig);
105         }
106
107         return UniqueValidation.of(schemaNode, treeConfig, MinMaxElementsValidation.from(op));
108     }
109
110     protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
111             final TreeNode current) throws ConflictingModificationAppliedException {
112         checkConflicting(path, original.getVersion().equals(current.getVersion()),
113                 "Node was replaced by other transaction.");
114         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
115                 "Node children was modified by other transaction");
116     }
117
118     protected final @NonNull ModificationApplyOperation resolveChildOperation(final PathArgument child) {
119         final ModificationApplyOperation potential = childByArg(child);
120         checkArgument(potential != null, "Operation for child %s is not defined.", child);
121         return potential;
122     }
123
124     @Override
125     final void checkApplicable(final ModificationPath path, final NodeModification modification,
126             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
127         switch (modification.getOperation()) {
128             case DELETE -> checkDeleteApplicable(modification, current);
129             case TOUCH -> checkTouchApplicable(path, modification, current, version);
130             case WRITE -> checkWriteApplicable(path, modification, current, version);
131             case MERGE -> checkMergeApplicable(path, modification, current, version);
132             case NONE -> {
133                 // No-op
134             }
135             default -> throw new UnsupportedOperationException(
136                 "Suplied modification type " + modification.getOperation() + " is not supported.");
137         }
138     }
139
140     @Override
141     final void quickVerifyStructure(final NormalizedNode writtenValue) {
142         verifyValue(writtenValue);
143     }
144
145     @Override
146     final void fullVerifyStructure(final NormalizedNode writtenValue) {
147         verifyValue(writtenValue);
148         verifyValueChildren(writtenValue);
149     }
150
151     /**
152      * Verify the a written value, without performing deeper tree validation.
153      *
154      * @param writtenValue Written value
155      */
156     abstract void verifyValue(NormalizedNode writtenValue);
157
158     /**
159      * Verify the children implied by a written value after the value itself has been verified by
160      * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
161      *
162      * @param writtenValue Written value
163      */
164     void verifyValueChildren(final NormalizedNode writtenValue) {
165         // Defaults to no-op
166     }
167
168     protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
169             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
170         final Optional<? extends TreeNode> original = modification.getOriginal();
171         if (original.isPresent() && current.isPresent()) {
172             /*
173              * We need to do conflict detection only and only if the value of leaf changed
174              * before two transactions. If value of leaf is unchanged between two transactions
175              * it should not cause transaction to fail, since result of this merge
176              * leads to same data.
177              */
178             final TreeNode orig = original.orElseThrow();
179             final TreeNode cur = current.orElseThrow();
180             if (!orig.getData().equals(cur.getData())) {
181                 checkNotConflicting(path, orig, cur);
182             }
183         }
184     }
185
186     /**
187      * Checks if write operation can be applied to current TreeNode.
188      * The operation checks if original tree node to which the modification is going to be applied exists and if
189      * current node in TreeNode structure exists.
190      *
191      * @param path Path from current node in TreeNode
192      * @param modification modification to apply
193      * @param current current node in TreeNode for modification to apply
194      * @throws DataValidationFailedException when a data dependency conflict is detected
195      */
196     private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
197             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
198         final Optional<? extends TreeNode> original = modification.getOriginal();
199         if (original.isPresent() && current.isPresent()) {
200             checkNotConflicting(path, original.orElseThrow(), current.orElseThrow());
201         } else {
202             checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
203             checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
204         }
205     }
206
207     private static void checkDeleteApplicable(final NodeModification modification,
208             final Optional<? extends TreeNode> current) {
209         // Delete is always applicable, we do not expose it to subclasses
210         if (!current.isPresent()) {
211             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
212         }
213     }
214
215     @Override
216     Optional<? extends TreeNode> apply(final ModifiedNode modification, final Optional<? extends TreeNode> currentMeta,
217             final Version version) {
218         return switch (modification.getOperation()) {
219             case DELETE -> {
220                 // Deletion of a non-existing node is a no-op, report it as such
221                 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
222                         : ModificationType.UNMODIFIED);
223                 yield modification.setSnapshot(Optional.empty());
224             }
225             case TOUCH -> {
226                 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
227                 yield modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.orElseThrow(),
228                     version)));
229             }
230             case MERGE -> {
231                 final TreeNode result;
232
233                 if (!currentMeta.isPresent()) {
234                     // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
235                     // structure is usually verified when the transaction is sealed. To preserve correctness, we have
236                     // to run that validation here.
237                     modification.resolveModificationType(ModificationType.WRITE);
238                     result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
239                     fullVerifyStructure(result.getData());
240                 } else {
241                     result = applyMerge(modification, currentMeta.orElseThrow(), version);
242                 }
243
244                 yield modification.setSnapshot(Optional.of(result));
245             }
246             case WRITE -> {
247                 modification.resolveModificationType(ModificationType.WRITE);
248                 yield modification.setSnapshot(Optional.of(applyWrite(modification,
249                     verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
250             }
251             case NONE -> {
252                 modification.resolveModificationType(ModificationType.UNMODIFIED);
253                 yield currentMeta;
254             }
255         };
256     }
257
258     /**
259      * Apply a merge operation. Since the result of merge differs based on the data type
260      * being modified, implementations of this method are responsible for calling
261      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
262      *
263      * @param modification Modified node
264      * @param currentMeta Store Metadata Node on which NodeModification should be applied
265      * @param version New subtree version of parent node
266      * @return A sealed TreeNode representing applied operation.
267      */
268     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
269
270     protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode newValue,
271             Optional<? extends TreeNode> currentMeta, Version version);
272
273     /**
274      * Apply a nested operation. Since there may not actually be a nested operation
275      * to be applied, implementations of this method are responsible for calling
276      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
277      *
278      * @param modification Modified node
279      * @param currentMeta Store Metadata Node on which NodeModification should be applied
280      * @param version New subtree version of parent node
281      * @return A sealed TreeNode representing applied operation.
282      */
283     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
284
285     /**
286      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
287      *
288      * @param path Path to current node
289      * @param modification Node modification which should be applied.
290      * @param current Current state of data tree
291      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
292      * @throws org.opendaylight.yangtools.yang.data.tree.api.IncorrectDataStructureException If subtree
293      *         modification is not applicable (e.g. leaf node).
294      */
295     protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
296             Optional<? extends TreeNode> current, Version version) throws DataValidationFailedException;
297
298     /**
299      * Return the {@link WithStatus}-subclass schema associated with this operation.
300      * @return A model node
301      */
302     abstract @NonNull T getSchema();
303
304     /**
305      * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
306      * nodes in configuration tree are marked as such.
307      *
308      * @param treeType Tree Type
309      * @param node Schema node
310      * @return {@code true} if the node matches the tree type, {@code false} otherwise.
311      */
312     static final boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
313         return treeType == TreeType.OPERATIONAL || node.effectiveConfig().orElse(Boolean.TRUE);
314     }
315 }