85ed74f208e6b44ce8cb4613ea0729e8bd022a92
[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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Iterables;
13 import java.util.List;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
30 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
33 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
34 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
44     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
45
46     public static SchemaAwareApplyOperation from(final DataSchemaNode schemaNode) {
47         if (schemaNode instanceof ContainerSchemaNode) {
48             return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
49         } else if (schemaNode instanceof ListSchemaNode) {
50             return fromListSchemaNode((ListSchemaNode) schemaNode);
51         } else if (schemaNode instanceof ChoiceNode) {
52             return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
53         } else if (schemaNode instanceof LeafListSchemaNode) {
54             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
55         } else if (schemaNode instanceof LeafSchemaNode) {
56             return new ValueNodeModificationStrategy.LeafModificationStrategy((LeafSchemaNode) schemaNode);
57         }
58         throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
59     }
60
61     public static SchemaAwareApplyOperation from(final DataNodeContainer resolvedTree,
62             final AugmentationTarget augSchemas, final AugmentationIdentifier identifier) {
63         AugmentationSchema augSchema = null;
64
65         allAugments:
66             for (AugmentationSchema potential : augSchemas.getAvailableAugmentations()) {
67                 for (DataSchemaNode child : potential.getChildNodes()) {
68                     if (identifier.getPossibleChildNames().contains(child.getQName())) {
69                         augSchema = potential;
70                         break allAugments;
71                     }
72                 }
73             }
74
75         if (augSchema != null) {
76             return new DataNodeContainerModificationStrategy.AugmentationModificationStrategy(augSchema, resolvedTree);
77         }
78         return null;
79     }
80
81     public static boolean checkConflicting(final YangInstanceIdentifier path, final boolean condition, final String message) throws ConflictingModificationAppliedException {
82         if(!condition) {
83             throw new ConflictingModificationAppliedException(path, message);
84         }
85         return condition;
86     }
87
88     private static SchemaAwareApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode) {
89         List<QName> keyDefinition = schemaNode.getKeyDefinition();
90         if (keyDefinition == null || keyDefinition.isEmpty()) {
91             return new UnkeyedListModificationStrategy(schemaNode);
92         }
93         if (schemaNode.isUserOrdered()) {
94             return new NormalizedNodeContainerModificationStrategy.OrderedMapModificationStrategy(schemaNode);
95         }
96
97         return new NormalizedNodeContainerModificationStrategy.UnorderedMapModificationStrategy(schemaNode);
98     }
99
100     private static SchemaAwareApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode) {
101         if(schemaNode.isUserOrdered()) {
102             return new NormalizedNodeContainerModificationStrategy.OrderedLeafSetModificationStrategy(schemaNode);
103         } else {
104             return new NormalizedNodeContainerModificationStrategy.UnorderedLeafSetModificationStrategy(schemaNode);
105         }
106     }
107
108     private static final void checkNotConflicting(final YangInstanceIdentifier path, final TreeNode original, 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         Optional<ModificationApplyOperation> potential = getChild(child);
117         Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
118         return potential.get();
119     }
120
121     @Override
122     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
123         if (modification.getType() == ModificationType.WRITE) {
124             verifyWrittenStructure(modification.getWrittenValue());
125         }
126     }
127
128     @Override
129     public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
130         switch (modification.getType()) {
131         case DELETE:
132             checkDeleteApplicable(modification, current);
133         case SUBTREE_MODIFIED:
134             checkSubtreeModificationApplicable(path, modification, current);
135             return;
136         case WRITE:
137             checkWriteApplicable(path, modification, current);
138             return;
139         case MERGE:
140             checkMergeApplicable(path, modification, current);
141             return;
142         case UNMODIFIED:
143             return;
144         default:
145             throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
146         }
147
148     }
149
150     protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
151         Optional<TreeNode> original = modification.getOriginal();
152         if (original.isPresent() && current.isPresent()) {
153             /*
154              * We need to do conflict detection only and only if the value of leaf changed
155              * before two transactions. If value of leaf is unchanged between two transactions
156              * it should not cause transaction to fail, since result of this merge
157              * leads to same data.
158              */
159             if(!original.get().getData().equals(current.get().getData())) {
160                 checkNotConflicting(path, original.get(), current.get());
161             }
162         }
163     }
164
165     /**
166      * Checks if write operation can be applied to current TreeNode.
167      * The operation checks if original tree node to which the modification is going to be applied exists and if
168      * current node in TreeNode structure exists.
169      *
170      * @param path Path from current node in TreeNode
171      * @param modification modification to apply
172      * @param current current node in TreeNode for modification to apply
173      * @throws DataValidationFailedException
174      */
175     protected void checkWriteApplicable(final YangInstanceIdentifier path, final NodeModification modification,
176         final Optional<TreeNode> current) throws DataValidationFailedException {
177         Optional<TreeNode> original = modification.getOriginal();
178         if (original.isPresent() && current.isPresent()) {
179             checkNotConflicting(path, original.get(), current.get());
180         } else if(original.isPresent()) {
181             throw new ConflictingModificationAppliedException(path,"Node was deleted by other transaction.");
182         } else if(current.isPresent()) {
183             throw new ConflictingModificationAppliedException(path,"Node was created by other transaction.");
184         }
185     }
186
187     private void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
188         // Delete is always applicable, we do not expose it to subclasses
189         if (current.isPresent()) {
190             LOG.trace("Delete operation turned to no-op on missing node {}", modification);
191         }
192     }
193
194     boolean isOrdered() {
195         return false;
196     }
197
198     @Override
199     public final Optional<TreeNode> apply(final ModifiedNode modification,
200             final Optional<TreeNode> currentMeta, final Version version) {
201
202         switch (modification.getType()) {
203         case DELETE:
204             return modification.storeSnapshot(Optional.<TreeNode> absent());
205         case SUBTREE_MODIFIED:
206             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
207                     modification);
208             return modification.storeSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
209                     version)));
210         case MERGE:
211             final TreeNode result;
212
213             // This is a slight optimization: a merge on a non-existing node equals to a write
214             if (currentMeta.isPresent()) {
215                 result = applyMerge(modification,currentMeta.get(), version);
216             } else {
217                 result = applyWrite(modification, currentMeta, version);
218             }
219
220             return modification.storeSnapshot(Optional.of(result));
221         case WRITE:
222             return modification.storeSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
223         case UNMODIFIED:
224             return currentMeta;
225         default:
226             throw new IllegalArgumentException("Provided modification type is not supported.");
227         }
228     }
229
230     protected abstract TreeNode applyMerge(ModifiedNode modification,
231             TreeNode currentMeta, Version version);
232
233     protected abstract TreeNode applyWrite(ModifiedNode modification,
234             Optional<TreeNode> currentMeta, Version version);
235
236     protected abstract TreeNode applySubtreeChange(ModifiedNode modification,
237             TreeNode currentMeta, Version version);
238
239     /**
240      *
241      * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
242      *
243      * @param path Path to current node
244      * @param modification Node modification which should be applied.
245      * @param current Current state of data tree
246      * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
247      * @throws IncorrectDataStructureException If subtree modification is not applicable (e.g. leaf node).
248      */
249     protected abstract void checkSubtreeModificationApplicable(YangInstanceIdentifier path, final NodeModification modification,
250             final Optional<TreeNode> current) throws DataValidationFailedException;
251
252     protected abstract void verifyWrittenStructure(NormalizedNode<?, ?> writtenValue);
253
254     public static class UnkeyedListModificationStrategy extends SchemaAwareApplyOperation {
255
256         private final Optional<ModificationApplyOperation> entryStrategy;
257
258         protected UnkeyedListModificationStrategy(final ListSchemaNode schema) {
259             entryStrategy = Optional.<ModificationApplyOperation> of(new DataNodeContainerModificationStrategy.UnkeyedListItemModificationStrategy(schema));
260         }
261
262         @Override
263         boolean isOrdered() {
264             return true;
265         }
266
267         @Override
268         protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta,
269                 final Version version) {
270             return applyWrite(modification, Optional.of(currentMeta), version);
271         }
272
273         @Override
274         protected TreeNode applySubtreeChange(final ModifiedNode modification,
275                 final TreeNode currentMeta, final Version version) {
276             throw new UnsupportedOperationException("UnkeyedList does not support subtree change.");
277         }
278
279         @Override
280         protected TreeNode applyWrite(final ModifiedNode modification,
281                 final Optional<TreeNode> currentMeta, final Version version) {
282             final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
283             final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
284
285             if (Iterables.isEmpty(modification.getChildren())) {
286                 return newValueMeta;
287             }
288
289             /*
290              * This is where things get interesting. The user has performed a write and
291              * then she applied some more modifications to it. So we need to make sense
292              * of that an apply the operations on top of the written value. We could have
293              * done it during the write, but this operation is potentially expensive, so
294              * we have left it out of the fast path.
295              *
296              * As it turns out, once we materialize the written data, we can share the
297              * code path with the subtree change. So let's create an unsealed TreeNode
298              * and run the common parts on it -- which end with the node being sealed.
299              */
300             final MutableTreeNode mutable = newValueMeta.mutable();
301             mutable.setSubtreeVersion(version);
302
303             @SuppressWarnings("rawtypes")
304             final NormalizedNodeContainerBuilder dataBuilder = ImmutableUnkeyedListEntryNodeBuilder
305                 .create((UnkeyedListEntryNode) newValue);
306
307             return mutateChildren(mutable, dataBuilder, version, modification.getChildren());
308         }
309
310         /**
311          * Applies write/remove diff operation for each modification child in modification subtree.
312          * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
313          *
314          * @param meta MutableTreeNode (IndexTreeNode)
315          * @param data DataBuilder
316          * @param nodeVersion Version of TreeNode
317          * @param modifications modification operations to apply
318          * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
319          */
320         @SuppressWarnings({ "rawtypes", "unchecked" })
321         private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
322             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
323
324             for (ModifiedNode mod : modifications) {
325                 final PathArgument id = mod.getIdentifier();
326                 final Optional<TreeNode> cm = meta.getChild(id);
327
328                 Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
329                 if (result.isPresent()) {
330                     final TreeNode tn = result.get();
331                     meta.addChild(tn);
332                     data.addChild(tn.getData());
333                 } else {
334                     meta.removeChild(id);
335                     data.removeChild(id);
336                 }
337             }
338
339             meta.setData(data.build());
340             return meta.seal();
341         }
342
343         @Override
344         public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
345             if (child instanceof NodeIdentifier) {
346                 return entryStrategy;
347             }
348             return Optional.absent();
349         }
350
351         @Override
352         protected void verifyWrittenStructure(final NormalizedNode<?, ?> writtenValue) {
353
354         }
355
356         @Override
357         protected void checkSubtreeModificationApplicable(final YangInstanceIdentifier path, final NodeModification modification,
358                 final Optional<TreeNode> current) throws IncorrectDataStructureException {
359             throw new IncorrectDataStructureException(path, "Subtree modification is not allowed.");
360         }
361     }
362 }