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