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