Separate out ModificationApplyOperation.verifyStructure()
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / ModifiedNode.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.Verify.verifyNotNull;
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 java.util.Collection;
16 import java.util.Map;
17 import java.util.Optional;
18 import java.util.function.Predicate;
19 import javax.annotation.Nonnull;
20 import javax.annotation.concurrent.NotThreadSafe;
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.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
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
30 /**
31  * Node Modification Node and Tree.
32  *
33  * <p>
34  * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
35  * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
36  * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
37  *
38  * <p>
39  * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
40  * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
41  * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
42  * the tree.
43  */
44 @NotThreadSafe
45 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
46     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = input -> {
47         requireNonNull(input);
48         switch (input.getOperation()) {
49             case DELETE:
50             case MERGE:
51             case WRITE:
52                 return true;
53             case TOUCH:
54             case NONE:
55                 return false;
56             default:
57                 throw new IllegalArgumentException("Unhandled modification type " + input.getOperation());
58         }
59     };
60
61     private final Map<PathArgument, ModifiedNode> children;
62     private final Optional<TreeNode> original;
63     private final PathArgument identifier;
64     private LogicalOperation operation = LogicalOperation.NONE;
65     private Optional<TreeNode> snapshotCache;
66     private NormalizedNode<?, ?> value;
67     private ModificationType modType;
68
69     // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
70     private TreeNode writtenOriginal;
71
72     // Internal cache for TreeNodes created as part of validation
73     private ModificationApplyOperation validatedOp;
74     private Optional<TreeNode> validatedCurrent;
75     private Optional<TreeNode> validatedNode;
76
77     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original,
78             final ChildTrackingPolicy childPolicy) {
79         this.identifier = identifier;
80         this.original = original;
81         this.children = childPolicy.createMap();
82     }
83
84     @Override
85     public PathArgument getIdentifier() {
86         return identifier;
87     }
88
89     @Override
90     LogicalOperation getOperation() {
91         return operation;
92     }
93
94     @Override
95     Optional<TreeNode> getOriginal() {
96         return original;
97     }
98
99     /**
100      * Return the value which was written to this node. The returned object is only valid for
101      * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
102      * operations. It should only be consulted when this modification is going to end up being
103      * {@link ModificationType#WRITE}.
104      *
105      * @return Currently-written value
106      */
107     @Nonnull
108     NormalizedNode<?, ?> getWrittenValue() {
109         return verifyNotNull(value);
110     }
111
112     /**
113      * Returns child modification if child was modified.
114      *
115      * @return Child modification if direct child or it's subtree was modified.
116      */
117     @Override
118     public Optional<ModifiedNode> getChild(final PathArgument child) {
119         return Optional.ofNullable(children.get(child));
120     }
121
122     private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
123         return original.isPresent() ? original.get().getChild(child) : Optional.empty();
124     }
125
126     private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
127         if (writtenOriginal == null) {
128             // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
129             // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
130             // modifications.
131             writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
132         }
133
134         return writtenOriginal.getChild(child);
135     }
136
137     /**
138      * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
139      * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
140      * to take the current node's operation into account.
141      *
142      * @param child Child we are looking to modify
143      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
144      * @return Before-image tree node as observed by that child.
145      */
146     private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
147         switch (operation) {
148             case DELETE:
149                 // DELETE implies non-presence
150                 return Optional.empty();
151             case NONE:
152             case TOUCH:
153             case MERGE:
154                 return metadataFromSnapshot(child);
155             case WRITE:
156                 // WRITE implies presence based on written data
157                 return metadataFromData(child, modVersion);
158             default:
159                 throw new IllegalStateException("Unhandled node operation " + operation);
160         }
161     }
162
163     /**
164      * Returns child modification if child was modified, creates {@link ModifiedNode}
165      * for child otherwise. If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
166      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}.
167      *
168      * @param child child identifier, may not be null
169      * @param childOper Child operation
170      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
171      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
172      *         containing child metadata if child was present in original data.
173      */
174     ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ModificationApplyOperation childOper,
175             @Nonnull final Version modVersion) {
176         clearSnapshot();
177         if (operation == LogicalOperation.NONE) {
178             updateOperationType(LogicalOperation.TOUCH);
179         }
180         final ModifiedNode potential = children.get(child);
181         if (potential != null) {
182             return potential;
183         }
184
185         final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
186
187
188         final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childOper.getChildPolicy());
189         if (operation == LogicalOperation.MERGE && value != null) {
190             /*
191              * We are attempting to modify a previously-unmodified part of a MERGE node. If the
192              * value contains this component, we need to materialize it as a MERGE modification.
193              */
194             @SuppressWarnings({ "rawtypes", "unchecked" })
195             final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
196             if (childData.isPresent()) {
197                 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
198             }
199         }
200
201         children.put(child, newlyCreated);
202         return newlyCreated;
203     }
204
205     /**
206      * Returns all recorded direct child modifications.
207      *
208      * @return all recorded direct child modifications
209      */
210     @Override
211     Collection<ModifiedNode> getChildren() {
212         return children.values();
213     }
214
215     /**
216      * Records a delete for associated node.
217      */
218     void delete() {
219         final LogicalOperation newType;
220
221         switch (operation) {
222             case DELETE:
223             case NONE:
224                 // We need to record this delete.
225                 newType = LogicalOperation.DELETE;
226                 break;
227             case MERGE:
228                 // In case of merge - delete needs to be recored and must not to be changed into NONE, because lazy
229                 // expansion of parent MERGE node would reintroduce it again.
230                 newType = LogicalOperation.DELETE;
231                 break;
232             case TOUCH:
233             case WRITE:
234                 /*
235                  * We are canceling a previous modification. This is a bit tricky, as the original write may have just
236                  * introduced the data, or it may have modified it.
237                  *
238                  * As documented in BUG-2470, a delete of data introduced in this transaction needs to be turned into
239                  * a no-op.
240                  */
241                 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
242                 break;
243             default:
244                 throw new IllegalStateException("Unhandled deletion of node with " + operation);
245         }
246
247         clearSnapshot();
248         children.clear();
249         this.value = null;
250         updateOperationType(newType);
251     }
252
253     /**
254      * Records a write for associated node.
255      *
256      * @param newValue new value
257      */
258     void write(final NormalizedNode<?, ?> newValue) {
259         updateValue(LogicalOperation.WRITE, newValue);
260         children.clear();
261     }
262
263     /**
264      * Seal the modification node and prune any children which has not been modified.
265      *
266      * @param schema associated apply operation
267      * @param version target version
268      */
269     void seal(final ModificationApplyOperation schema, final Version version) {
270         clearSnapshot();
271         writtenOriginal = null;
272
273         switch (operation) {
274             case TOUCH:
275                 // A TOUCH node without any children is a no-op
276                 if (children.isEmpty()) {
277                     updateOperationType(LogicalOperation.NONE);
278                 }
279                 break;
280             case WRITE:
281                 // A WRITE can collapse all of its children
282                 if (!children.isEmpty()) {
283                     value = schema.apply(this, getOriginal(), version).map(TreeNode::getData).orElse(null);
284                     children.clear();
285                 }
286
287                 if (value == null) {
288                     // The write has ended up being empty, such as a write of an empty list.
289                     updateOperationType(LogicalOperation.DELETE);
290                 } else {
291                     schema.fullVerifyStructure(value);
292                 }
293                 break;
294             default:
295                 break;
296         }
297     }
298
299     private void clearSnapshot() {
300         snapshotCache = null;
301     }
302
303     Optional<TreeNode> getSnapshot() {
304         return snapshotCache;
305     }
306
307     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
308         snapshotCache = requireNonNull(snapshot);
309         return snapshot;
310     }
311
312     void updateOperationType(final LogicalOperation type) {
313         operation = type;
314         modType = null;
315
316         // Make sure we do not reuse previously-instantiated data-derived metadata
317         writtenOriginal = null;
318         clearSnapshot();
319     }
320
321     @Override
322     public String toString() {
323         final ToStringHelper helper = MoreObjects.toStringHelper(this).omitNullValues()
324                 .add("identifier", identifier).add("operation", operation).add("modificationType", modType);
325         if (!children.isEmpty()) {
326             helper.add("childModification", children);
327         }
328         return helper.toString();
329     }
330
331     void resolveModificationType(@Nonnull final ModificationType type) {
332         modType = type;
333     }
334
335     /**
336      * Update this node's value and operation type without disturbing any of its child modifications.
337      *
338      * @param type New operation type
339      * @param newValue New node value
340      */
341     void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> newValue) {
342         this.value = requireNonNull(newValue);
343         updateOperationType(type);
344     }
345
346     /**
347      * Return the physical modification done to data. May return null if the
348      * operation has not been applied to the underlying tree. This is different
349      * from the logical operation in that it can actually be a no-op if the
350      * operation has no side-effects (like an empty merge on a container).
351      *
352      * @return Modification type.
353      */
354     ModificationType getModificationType() {
355         return modType;
356     }
357
358     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
359         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
360     }
361
362     void setValidatedNode(final ModificationApplyOperation op, final Optional<TreeNode> current,
363             final Optional<TreeNode> node) {
364         this.validatedOp = requireNonNull(op);
365         this.validatedCurrent = requireNonNull(current);
366         this.validatedNode = requireNonNull(node);
367     }
368
369     Optional<TreeNode> getValidatedNode(final ModificationApplyOperation op, final Optional<TreeNode> current) {
370         return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;
371     }
372 }