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