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