d7666a7b10d17f6696ffc923a38e448ceda6c41d
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / AbstractNodeContainerModificationStrategy.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 java.util.Objects.requireNonNull;
12
13 import com.google.common.base.Verify;
14 import java.util.Collection;
15 import java.util.Optional;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
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
31 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
32
33     private final Class<? extends NormalizedNode<?, ?>> nodeClass;
34     private final boolean verifyChildrenStructure;
35
36     protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
37             final DataTreeConfiguration treeConfig) {
38         this.nodeClass = requireNonNull(nodeClass , "nodeClass");
39         this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
40     }
41
42     @Override
43     void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
44         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
45         checkArgument(writtenValue instanceof NormalizedNodeContainer);
46         if (verifyChildrenStructure && verifyChildren) {
47             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
48             for (final Object child : container.getValue()) {
49                 checkArgument(child instanceof NormalizedNode);
50                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
51                 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
52                 if (childOp.isPresent()) {
53                     childOp.get().verifyStructure(castedChild, verifyChildren);
54                 } else {
55                     throw new SchemaValidationFailedException(String.format(
56                             "Node %s is not a valid child of %s according to the schema.",
57                             castedChild.getIdentifier(), container.getIdentifier()));
58                 }
59             }
60         }
61     }
62
63     @Override
64     protected void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
65         final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
66         for (final Object child : container.getValue()) {
67             checkArgument(child instanceof NormalizedNode);
68             final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
69             final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
70             if (childOp.isPresent()) {
71                 childOp.get().recursivelyVerifyStructure(castedChild);
72             } else {
73                 throw new SchemaValidationFailedException(
74                     String.format("Node %s is not a valid child of %s according to the schema.",
75                         castedChild.getIdentifier(), container.getIdentifier()));
76             }
77         }
78     }
79
80     @Override
81     protected TreeNode applyWrite(final ModifiedNode modification,
82             final Optional<TreeNode> currentMeta, final Version version) {
83         final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
84         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
85
86         if (modification.getChildren().isEmpty()) {
87             return newValueMeta;
88         }
89
90         /*
91          * This is where things get interesting. The user has performed a write and
92          * then she applied some more modifications to it. So we need to make sense
93          * of that an apply the operations on top of the written value. We could have
94          * done it during the write, but this operation is potentially expensive, so
95          * we have left it out of the fast path.
96          *
97          * As it turns out, once we materialize the written data, we can share the
98          * code path with the subtree change. So let's create an unsealed TreeNode
99          * and run the common parts on it -- which end with the node being sealed.
100          *
101          * FIXME: this code needs to be moved out from the prepare() path and into
102          *        the read() and seal() paths. Merging of writes needs to be charged
103          *        to the code which originated this, not to the code which is
104          *        attempting to make it visible.
105          */
106         final MutableTreeNode mutable = newValueMeta.mutable();
107         mutable.setSubtreeVersion(version);
108
109         @SuppressWarnings("rawtypes")
110         final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
111         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
112
113         // We are good to go except one detail: this is a single logical write, but
114         // we have a result TreeNode which has been forced to materialized, e.g. it
115         // is larger than it needs to be. Create a new TreeNode to host the data.
116         return TreeNodeFactory.createTreeNode(result.getData(), version);
117     }
118
119     /**
120      * Applies write/remove diff operation for each modification child in modification subtree.
121      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
122      *
123      * @param meta MutableTreeNode (IndexTreeNode)
124      * @param data DataBuilder
125      * @param nodeVersion Version of TreeNode
126      * @param modifications modification operations to apply
127      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
128      */
129     @SuppressWarnings({ "rawtypes", "unchecked" })
130     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
131             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
132
133         for (final ModifiedNode mod : modifications) {
134             final PathArgument id = mod.getIdentifier();
135             final Optional<TreeNode> cm = meta.getChild(id);
136
137             final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
138             if (result.isPresent()) {
139                 final TreeNode tn = result.get();
140                 meta.addChild(tn);
141                 data.addChild(tn.getData());
142             } else {
143                 meta.removeChild(id);
144                 data.removeChild(id);
145             }
146         }
147
148         meta.setData(data.build());
149         return meta.seal();
150     }
151
152     @Override
153     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
154         /*
155          * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
156          * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
157          * heavy lifting of applying the children recursively (either through here or through applyWrite().
158          */
159         final NormalizedNode<?, ?> value = modification.getWrittenValue();
160
161         Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
162         @SuppressWarnings({"unchecked", "rawtypes"})
163         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
164         for (final NormalizedNode<?, ?> c : children) {
165             final PathArgument id = c.getIdentifier();
166             modification.modifyChild(id, resolveChildOperation(id), version);
167         }
168         return applyTouch(modification, currentMeta, version);
169     }
170
171     private void mergeChildrenIntoModification(final ModifiedNode modification,
172             final Collection<NormalizedNode<?, ?>> children, final Version version) {
173         for (final NormalizedNode<?, ?> c : children) {
174             final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
175             final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
176             childOp.mergeIntoModifiedNode(childNode, c, version);
177         }
178     }
179
180     @Override
181     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
182             final Version version) {
183         @SuppressWarnings({ "unchecked", "rawtypes" })
184         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
185
186         switch (modification.getOperation()) {
187             case NONE:
188                 // Fresh node, just record a MERGE with a value
189                 recursivelyVerifyStructure(value);
190                 modification.updateValue(LogicalOperation.MERGE, value);
191                 return;
192             case TOUCH:
193
194                 mergeChildrenIntoModification(modification, children, version);
195                 // We record empty merge value, since real children merges
196                 // are already expanded. This is needed to satisfy non-null for merge
197                 // original merge value can not be used since it mean different
198                 // order of operation - parent changes are always resolved before
199                 // children ones, and having node in TOUCH means children was modified
200                 // before.
201                 modification.updateValue(LogicalOperation.MERGE, createEmptyValue(value));
202                 return;
203             case MERGE:
204                 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
205                 // as MERGE, invalidating cached snapshot
206                 mergeChildrenIntoModification(modification, children, version);
207                 modification.updateOperationType(LogicalOperation.MERGE);
208                 return;
209             case DELETE:
210                 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
211                 // we are really performing a write. One thing that ruins that are any child modifications. If there
212                 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
213                 // and then append any child entries.
214                 if (!modification.getChildren().isEmpty()) {
215                     // Version does not matter here as we'll throw it out
216                     final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
217                         Version.initial());
218                     if (current.isPresent()) {
219                         modification.updateValue(LogicalOperation.WRITE, current.get().getData());
220                         mergeChildrenIntoModification(modification, children, version);
221                         return;
222                     }
223                 }
224
225                 modification.updateValue(LogicalOperation.WRITE, value);
226                 return;
227             case WRITE:
228                 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
229                 // ModifiedNode and run recursively on it
230                 mergeChildrenIntoModification(modification, children, version);
231                 modification.updateOperationType(LogicalOperation.WRITE);
232                 return;
233             default:
234                 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
235         }
236     }
237
238     @Override
239     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
240         /*
241          * The user may have issued an empty merge operation. In this case we do not perform
242          * a data tree mutation, do not pass GO, and do not collect useless garbage. It
243          * also means the ModificationType is UNMODIFIED.
244          */
245         final Collection<ModifiedNode> children = modification.getChildren();
246         if (!children.isEmpty()) {
247             @SuppressWarnings("rawtypes")
248             final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
249             final MutableTreeNode newMeta = currentMeta.mutable();
250             newMeta.setSubtreeVersion(version);
251             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
252
253             /*
254              * It is possible that the only modifications under this node were empty merges,
255              * which were turned into UNMODIFIED. If that is the case, we can turn this operation
256              * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
257              * of speeding up any users, who can skip processing child nodes.
258              *
259              * In order to do that, though, we have to check all child operations are UNMODIFIED.
260              * Let's do precisely that, stopping as soon we find a different result.
261              */
262             for (final ModifiedNode child : children) {
263                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
264                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
265                     return ret;
266                 }
267             }
268         }
269
270         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
271         // replace the metadata node.
272         modification.resolveModificationType(ModificationType.UNMODIFIED);
273         return currentMeta;
274     }
275
276     @Override
277     protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
278             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
279         if (!modification.getOriginal().isPresent() && !current.isPresent()) {
280             final YangInstanceIdentifier id = path.toInstanceIdentifier();
281             throw new ModifiedNodeDoesNotExistException(id,
282                 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
283         }
284
285         checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
286         checkChildPreconditions(path, modification, current.get(), version);
287     }
288
289     /**
290      * Recursively check child preconditions.
291      *
292      * @param path current node path
293      * @param modification current modification
294      * @param current Current data tree node.
295      */
296     private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
297             final TreeNode current, final Version version) throws DataValidationFailedException {
298         for (final NodeModification childMod : modification.getChildren()) {
299             final PathArgument childId = childMod.getIdentifier();
300             final Optional<TreeNode> childMeta = current.getChild(childId);
301
302             path.push(childId);
303             try {
304                 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
305             } finally {
306                 path.pop();
307             }
308         }
309     }
310
311     @Override
312     protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
313             final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
314         if (current.isPresent()) {
315             checkChildPreconditions(path, modification, current.get(), version);
316         }
317     }
318
319     protected boolean verifyChildrenStructure() {
320         return verifyChildrenStructure;
321     }
322
323     @SuppressWarnings("rawtypes")
324     protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
325
326     protected abstract NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> original);
327 }