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