eeb6a996e7c87f0c1b37a9858898c6edea4cfd5a
[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
12 import java.util.List;
13 import java.util.Optional;
14 import org.opendaylight.yangtools.yang.common.QName;
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.AugmentationSchemaNode;
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,
40             final DataTreeConfiguration treeConfig) {
41         if (treeConfig.getTreeType() == TreeType.CONFIGURATION) {
42             checkArgument(schemaNode.isConfiguration(), "Supplied %s does not belongs to configuration tree.",
43                 schemaNode.getPath());
44         }
45         if (schemaNode instanceof ContainerSchemaNode) {
46             final ContainerSchemaNode containerSchema = (ContainerSchemaNode) schemaNode;
47             return containerSchema.isPresenceContainer()
48                     ? new PresenceContainerModificationStrategy(containerSchema, treeConfig)
49                             : new StructuralContainerModificationStrategy(containerSchema, 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 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,
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 if (schemaNode.isUserOrdered()) {
90             op = new OrderedMapModificationStrategy(schemaNode, treeConfig);
91         } else {
92             op = new UnorderedMapModificationStrategy(schemaNode, treeConfig);
93         }
94
95         return MinMaxElementsValidation.from(op, schemaNode);
96     }
97
98     private static ModificationApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode,
99             final DataTreeConfiguration treeConfig) {
100         final SchemaAwareApplyOperation op;
101         if (schemaNode.isUserOrdered()) {
102             op = new OrderedLeafSetModificationStrategy(schemaNode, treeConfig);
103         } else {
104             op = new UnorderedLeafSetModificationStrategy(schemaNode, treeConfig);
105         }
106         return MinMaxElementsValidation.from(op, schemaNode);
107     }
108
109     protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
110             final TreeNode current) throws ConflictingModificationAppliedException {
111         checkConflicting(path, original.getVersion().equals(current.getVersion()),
112                 "Node was replaced by other transaction.");
113         checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
114                 "Node children was modified by other transaction");
115     }
116
117     protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
118         final Optional<ModificationApplyOperation> potential = getChild(child);
119         checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
120         return potential.get();
121     }
122
123     @Override
124     void checkApplicable(final ModificationPath path, final NodeModification modification,
125             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
126         switch (modification.getOperation()) {
127             case DELETE:
128                 checkDeleteApplicable(modification, current);
129                 break;
130             case TOUCH:
131                 checkTouchApplicable(path, modification, current, version);
132                 break;
133             case WRITE:
134                 checkWriteApplicable(path, modification, current, version);
135                 break;
136             case MERGE:
137                 checkMergeApplicable(path, modification, current, version);
138                 break;
139             case NONE:
140                 break;
141             default:
142                 throw new UnsupportedOperationException(
143                     "Suplied modification type " + modification.getOperation() + " is not supported.");
144         }
145     }
146
147     protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
148             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
149         final Optional<TreeNode> original = modification.getOriginal();
150         if (original.isPresent() && current.isPresent()) {
151             /*
152              * We need to do conflict detection only and only if the value of leaf changed
153              * before two transactions. If value of leaf is unchanged between two transactions
154              * it should not cause transaction to fail, since result of this merge
155              * leads to same data.
156              */
157             final TreeNode orig = original.get();
158             final TreeNode cur = current.get();
159             if (!orig.getData().equals(cur.getData())) {
160                 checkNotConflicting(path, orig, cur);
161             }
162         }
163     }
164
165     /**
166      * Checks if write operation can be applied to current TreeNode.
167      * The operation checks if original tree node to which the modification is going to be applied exists and if
168      * current node in TreeNode structure exists.
169      *
170      * @param path Path from current node in TreeNode
171      * @param modification modification to apply
172      * @param current current node in TreeNode for modification to apply
173      * @throws DataValidationFailedException when a data dependency conflict is detected
174      */
175     protected void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
176             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
177         final Optional<TreeNode> original = modification.getOriginal();
178         if (original.isPresent() && current.isPresent()) {
179             checkNotConflicting(path, original.get(), current.get());
180         } else {
181             checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
182             checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
183         }
184     }
185
186     private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
187         // Delete is always applicable, we do not expose it to subclasses
188         if (!current.isPresent()) {
189             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
190         }
191     }
192
193     @Override
194     protected ChildTrackingPolicy getChildPolicy() {
195         return ChildTrackingPolicy.UNORDERED;
196     }
197
198     @Override
199     Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
200             final Version version) {
201         switch (modification.getOperation()) {
202             case DELETE:
203                 // Deletion of a non-existing node is a no-op, report it as such
204                 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
205                         : ModificationType.UNMODIFIED);
206                 return modification.setSnapshot(Optional.empty());
207             case TOUCH:
208                 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
209                 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
210                     version)));
211             case MERGE:
212                 final TreeNode result;
213
214                 if (!currentMeta.isPresent()) {
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, currentMeta, version);
220                     verifyStructure(result.getData(), true);
221                 } else {
222                     result = applyMerge(modification, currentMeta.get(), version);
223                 }
224
225                 return modification.setSnapshot(Optional.of(result));
226             case WRITE:
227                 modification.resolveModificationType(ModificationType.WRITE);
228                 return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
229             case NONE:
230                 modification.resolveModificationType(ModificationType.UNMODIFIED);
231                 return currentMeta;
232             default:
233                 throw new IllegalArgumentException("Provided modification type is not supported.");
234         }
235     }
236
237     /**
238      * Apply a merge operation. Since the result of merge differs based on the data type
239      * being modified, implementations of this method are responsible for calling
240      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
241      *
242      * @param modification Modified node
243      * @param currentMeta Store Metadata Node on which NodeModification should be applied
244      * @param version New subtree version of parent node
245      * @return A sealed TreeNode representing applied operation.
246      */
247     protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
248
249     protected abstract TreeNode applyWrite(ModifiedNode modification, Optional<TreeNode> currentMeta, Version version);
250
251     /**
252      * Apply a nested operation. Since there may not actually be a nested operation
253      * to be applied, implementations of this method are responsible for calling
254      * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
255      *
256      * @param modification Modified node
257      * @param currentMeta Store Metadata Node on which NodeModification should be applied
258      * @param version New subtree version of parent node
259      * @return A sealed TreeNode representing applied operation.
260      */
261     protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
262
263     /**
264      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
265      *
266      * @param path Path to current node
267      * @param modification Node modification which should be applied.
268      * @param current Current state of data tree
269      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
270      * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
271      *         modification is not applicable (e.g. leaf node).
272      */
273     protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
274             Optional<TreeNode> current, Version version) throws DataValidationFailedException;
275
276     /**
277      * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
278      * nodes in configuration tree are marked as such.
279      *
280      * @param treeType Tree Type
281      * @param node Schema node
282      * @return {@code true} if the node matches the tree type, {@code false} otherwise.
283      */
284     static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
285         return treeType == TreeType.OPERATIONAL || node.isConfiguration();
286     }
287 }