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