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