2d6985a17201ed64020300167ab4a2ad0f1c3af5
[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.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Verify;
16 import java.util.Collection;
17 import java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
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.ModifiedNodeDoesNotExistException;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
35 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
36
37 abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
38         extends SchemaAwareApplyOperation<T> {
39     abstract static class Invisible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
40         private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
41
42         Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
43                 final SchemaAwareApplyOperation<T> entryStrategy) {
44             super(support, treeConfig);
45             this.entryStrategy = requireNonNull(entryStrategy);
46         }
47
48         @Override
49         final T getSchema() {
50             return entryStrategy.getSchema();
51         }
52
53         final Optional<ModificationApplyOperation> entryStrategy() {
54             return Optional.of(entryStrategy);
55         }
56
57         @Override
58         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
59             return super.addToStringAttributes(helper).add("entry", entryStrategy);
60         }
61     }
62
63     abstract static class Visible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
64         private final @NonNull T schema;
65
66         Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
67             final T schema) {
68             super(support, treeConfig);
69             this.schema = requireNonNull(schema);
70         }
71
72         @Override
73         final T getSchema() {
74             return schema;
75         }
76
77         @Override
78         ToStringHelper addToStringAttributes(final ToStringHelper helper) {
79             return super.addToStringAttributes(helper).add("schema", schema);
80         }
81     }
82
83     /**
84      * Fake TreeNode version used in
85      * {@link #checkTouchApplicable(ModificationPath, NodeModification, Optional, Version)}
86      * It is okay to use a global constant, as the delegate will ignore it anyway.
87      */
88     private static final Version FAKE_VERSION = Version.initial();
89
90     private final NormalizedNodeContainerSupport<?, ?> support;
91     private final boolean verifyChildrenStructure;
92
93     AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
94             final DataTreeConfiguration treeConfig) {
95         this.support = requireNonNull(support);
96         this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
97     }
98
99     @Override
100     protected final ChildTrackingPolicy getChildPolicy() {
101         return support.childPolicy;
102     }
103
104     @Override
105     final void verifyValue(final NormalizedNode<?, ?> writtenValue) {
106         final Class<?> nodeClass = support.requiredClass;
107         checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
108         checkArgument(writtenValue instanceof NormalizedNodeContainer);
109     }
110
111     @Override
112     final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
113         if (verifyChildrenStructure) {
114             final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
115             for (final Object child : container.getValue()) {
116                 checkArgument(child instanceof NormalizedNode);
117                 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
118                 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
119                 if (childOp.isPresent()) {
120                     childOp.get().fullVerifyStructure(castedChild);
121                 } else {
122                     throw new SchemaValidationFailedException(String.format(
123                             "Node %s is not a valid child of %s according to the schema.",
124                             castedChild.getIdentifier(), container.getIdentifier()));
125                 }
126             }
127
128             optionalVerifyValueChildren(writtenValue);
129         }
130         mandatoryVerifyValueChildren(writtenValue);
131     }
132
133     /**
134      * Perform additional verification on written value's child structure, like presence of mandatory children and
135      * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
136      *
137      * @param writtenValue Effective written value
138      */
139     void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
140         // Defaults to no-op
141     }
142
143     /**
144      * Perform additional verification on written value's child structure, like presence of mandatory children.
145      * The default implementation does nothing.
146      *
147      * @param writtenValue Effective written value
148      */
149     void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
150         // Defaults to no-op
151     }
152
153     @Override
154     protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
155         final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
156         for (final Object child : container.getValue()) {
157             checkArgument(child instanceof NormalizedNode);
158             final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
159             final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
160             if (!childOp.isPresent()) {
161                 throw new SchemaValidationFailedException(
162                     String.format("Node %s is not a valid child of %s according to the schema.",
163                         castedChild.getIdentifier(), container.getIdentifier()));
164             }
165
166             childOp.get().recursivelyVerifyStructure(castedChild);
167         }
168     }
169
170     @Override
171     protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
172             final Optional<? extends TreeNode> currentMeta, final Version version) {
173         final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
174
175         if (modification.getChildren().isEmpty()) {
176             return newValueMeta;
177         }
178
179         /*
180          * This is where things get interesting. The user has performed a write and
181          * then she applied some more modifications to it. So we need to make sense
182          * of that an apply the operations on top of the written value. We could have
183          * done it during the write, but this operation is potentially expensive, so
184          * we have left it out of the fast path.
185          *
186          * As it turns out, once we materialize the written data, we can share the
187          * code path with the subtree change. So let's create an unsealed TreeNode
188          * and run the common parts on it -- which end with the node being sealed.
189          *
190          * FIXME: this code needs to be moved out from the prepare() path and into
191          *        the read() and seal() paths. Merging of writes needs to be charged
192          *        to the code which originated this, not to the code which is
193          *        attempting to make it visible.
194          */
195         final MutableTreeNode mutable = newValueMeta.mutable();
196         mutable.setSubtreeVersion(version);
197
198         @SuppressWarnings("rawtypes")
199         final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
200         final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
201
202         // We are good to go except one detail: this is a single logical write, but
203         // we have a result TreeNode which has been forced to materialized, e.g. it
204         // is larger than it needs to be. Create a new TreeNode to host the data.
205         return TreeNodeFactory.createTreeNode(result.getData(), version);
206     }
207
208     /**
209      * Applies write/remove diff operation for each modification child in modification subtree.
210      * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
211      *
212      * @param meta MutableTreeNode (IndexTreeNode)
213      * @param data DataBuilder
214      * @param nodeVersion Version of TreeNode
215      * @param modifications modification operations to apply
216      * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
217      */
218     @SuppressWarnings({ "rawtypes", "unchecked" })
219     private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
220             final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
221
222         for (final ModifiedNode mod : modifications) {
223             final PathArgument id = mod.getIdentifier();
224             final Optional<? extends TreeNode> cm = meta.getChild(id);
225
226             final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
227             if (result.isPresent()) {
228                 final TreeNode tn = result.get();
229                 meta.addChild(tn);
230                 data.addChild(tn.getData());
231             } else {
232                 meta.removeChild(id);
233                 data.removeChild(id);
234             }
235         }
236
237         meta.setData(data.build());
238         return meta.seal();
239     }
240
241     @Override
242     protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
243         /*
244          * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
245          * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
246          * heavy lifting of applying the children recursively (either through here or through applyWrite().
247          */
248         final NormalizedNode<?, ?> value = modification.getWrittenValue();
249
250         Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
251         @SuppressWarnings({"unchecked", "rawtypes"})
252         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
253         for (final NormalizedNode<?, ?> c : children) {
254             final PathArgument id = c.getIdentifier();
255             modification.modifyChild(id, resolveChildOperation(id), version);
256         }
257         return applyTouch(modification, currentMeta, version);
258     }
259
260     private void mergeChildrenIntoModification(final ModifiedNode modification,
261             final Collection<NormalizedNode<?, ?>> children, final Version version) {
262         for (final NormalizedNode<?, ?> c : children) {
263             final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
264             final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
265             childOp.mergeIntoModifiedNode(childNode, c, version);
266         }
267     }
268
269     @Override
270     final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
271             final Version version) {
272         @SuppressWarnings({ "unchecked", "rawtypes" })
273         final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
274
275         switch (modification.getOperation()) {
276             case NONE:
277                 // Fresh node, just record a MERGE with a value
278                 recursivelyVerifyStructure(value);
279                 modification.updateValue(LogicalOperation.MERGE, value);
280                 return;
281             case TOUCH:
282
283                 mergeChildrenIntoModification(modification, children, version);
284                 // We record empty merge value, since real children merges
285                 // are already expanded. This is needed to satisfy non-null for merge
286                 // original merge value can not be used since it mean different
287                 // order of operation - parent changes are always resolved before
288                 // children ones, and having node in TOUCH means children was modified
289                 // before.
290                 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
291                 return;
292             case MERGE:
293                 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
294                 // as MERGE, invalidating cached snapshot
295                 mergeChildrenIntoModification(modification, children, version);
296                 modification.updateOperationType(LogicalOperation.MERGE);
297                 return;
298             case DELETE:
299                 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
300                 // we are really performing a write. One thing that ruins that are any child modifications. If there
301                 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
302                 // and then append any child entries.
303                 if (!modification.getChildren().isEmpty()) {
304                     // Version does not matter here as we'll throw it out
305                     final Optional<? extends TreeNode> current = apply(modification, modification.getOriginal(),
306                         Version.initial());
307                     if (current.isPresent()) {
308                         modification.updateValue(LogicalOperation.WRITE, current.get().getData());
309                         mergeChildrenIntoModification(modification, children, version);
310                         return;
311                     }
312                 }
313
314                 modification.updateValue(LogicalOperation.WRITE, value);
315                 return;
316             case WRITE:
317                 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
318                 // ModifiedNode and run recursively on it
319                 mergeChildrenIntoModification(modification, children, version);
320                 modification.updateOperationType(LogicalOperation.WRITE);
321                 return;
322             default:
323                 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
324         }
325     }
326
327     @Override
328     protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
329         /*
330          * The user may have issued an empty merge operation. In this case we do not perform
331          * a data tree mutation, do not pass GO, and do not collect useless garbage. It
332          * also means the ModificationType is UNMODIFIED.
333          */
334         final Collection<ModifiedNode> children = modification.getChildren();
335         if (!children.isEmpty()) {
336             @SuppressWarnings("rawtypes")
337             final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
338             final MutableTreeNode newMeta = currentMeta.mutable();
339             newMeta.setSubtreeVersion(version);
340             final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
341
342             /*
343              * It is possible that the only modifications under this node were empty merges,
344              * which were turned into UNMODIFIED. If that is the case, we can turn this operation
345              * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
346              * of speeding up any users, who can skip processing child nodes.
347              *
348              * In order to do that, though, we have to check all child operations are UNMODIFIED.
349              * Let's do precisely that, stopping as soon we find a different result.
350              */
351             for (final ModifiedNode child : children) {
352                 if (child.getModificationType() != ModificationType.UNMODIFIED) {
353                     modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
354                     return ret;
355                 }
356             }
357         }
358
359         // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
360         // replace the metadata node.
361         modification.resolveModificationType(ModificationType.UNMODIFIED);
362         return currentMeta;
363     }
364
365     @Override
366     protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
367             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
368         final TreeNode currentNode;
369         if (!current.isPresent()) {
370             currentNode = defaultTreeNode();
371             if (currentNode == null) {
372                 if (!modification.getOriginal().isPresent()) {
373                     final YangInstanceIdentifier id = path.toInstanceIdentifier();
374                     throw new ModifiedNodeDoesNotExistException(id,
375                         String.format("Node %s does not exist. Cannot apply modification to its children.", id));
376                 }
377
378                 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
379                     "Node was deleted by other transaction.");
380             }
381         } else {
382             currentNode = current.get();
383         }
384
385         checkChildPreconditions(path, modification, currentNode, version);
386     }
387
388     /**
389      * Return the default tree node. Default implementation does nothing, but can be overridden to call
390      * {@link #defaultTreeNode(NormalizedNode)}.
391      *
392      * @return Default empty tree node, or null if no default is available
393      */
394     @Nullable TreeNode defaultTreeNode() {
395         // Defaults to no recovery
396         return null;
397     }
398
399     static final TreeNode defaultTreeNode(final NormalizedNode<?, ?> emptyNode) {
400         return TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
401     }
402
403     @Override
404     protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
405             final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
406         if (current.isPresent()) {
407             checkChildPreconditions(path, modification, current.get(), version);
408         }
409     }
410
411     /**
412      * Recursively check child preconditions.
413      *
414      * @param path current node path
415      * @param modification current modification
416      * @param current Current data tree node.
417      */
418     private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
419             final TreeNode current, final Version version) throws DataValidationFailedException {
420         for (final NodeModification childMod : modification.getChildren()) {
421             final PathArgument childId = childMod.getIdentifier();
422             final Optional<? extends TreeNode> childMeta = current.getChild(childId);
423
424             path.push(childId);
425             try {
426                 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
427             } finally {
428                 path.pop();
429             }
430         }
431     }
432
433     @Override
434     public final String toString() {
435         return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
436     }
437
438     ToStringHelper addToStringAttributes(final ToStringHelper helper) {
439         return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);
440     }
441 }