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