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