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