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