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