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