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