Bug 5968: Mandatory leaf enforcement does not work in some cases
[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 com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Predicate;
13 import java.util.Collection;
14 import java.util.Map;
15 import javax.annotation.Nonnull;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25
26 /**
27  * Node Modification Node and Tree
28  *
29  * Tree which structurally resembles data tree and captures client modifications to the data store tree. This tree is
30  * lazily created and populated via {@link #modifyChild(PathArgument, ModificationApplyOperation, Version)} and
31  * {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
32  *
33  * The contract is that the state information exposed here preserves the temporal ordering of whatever modifications
34  * were executed. A child's effects pertain to data node as modified by its ancestors. This means that in order to
35  * reconstruct the effective data node presentation, it is sufficient to perform a depth-first pre-order traversal of
36  * the tree.
37  */
38 @NotThreadSafe
39 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
40     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = input -> {
41         Preconditions.checkNotNull(input);
42         switch (input.getOperation()) {
43             case DELETE:
44             case MERGE:
45             case WRITE:
46                 return true;
47             case TOUCH:
48             case NONE:
49                 return false;
50         }
51
52         throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
53     };
54
55     private final Map<PathArgument, ModifiedNode> children;
56     private final Optional<TreeNode> original;
57     private final PathArgument identifier;
58     private LogicalOperation operation = LogicalOperation.NONE;
59     private Optional<TreeNode> snapshotCache;
60     private NormalizedNode<?, ?> value;
61     private ModificationType modType;
62
63     // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
64     private TreeNode writtenOriginal;
65
66     // Internal cache for TreeNodes created as part of validation
67     private SchemaAwareApplyOperation validatedOp;
68     private Optional<TreeNode> validatedCurrent;
69     private TreeNode validatedNode;
70
71     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
72         this.identifier = identifier;
73         this.original = original;
74         this.children = childPolicy.createMap();
75     }
76
77     @Override
78     public PathArgument getIdentifier() {
79         return identifier;
80     }
81
82     @Override
83     LogicalOperation getOperation() {
84         return operation;
85     }
86
87     @Override
88     Optional<TreeNode> getOriginal() {
89         return original;
90     }
91
92     /**
93      * Return the value which was written to this node. The returned object is only valid for
94      * {@link LogicalOperation#MERGE} and {@link LogicalOperation#WRITE}.
95      * operations. It should only be consulted when this modification is going to end up being
96      * {@link ModificationType#WRITE}.
97      *
98      * @return Currently-written value
99      */
100     NormalizedNode<?, ?> getWrittenValue() {
101         return value;
102     }
103
104     /**
105      *
106      * Returns child modification if child was modified
107      *
108      * @return Child modification if direct child or it's subtree
109      *  was modified.
110      *
111      */
112     @Override
113     public Optional<ModifiedNode> getChild(final PathArgument child) {
114         return Optional.fromNullable(children.get(child));
115     }
116
117     private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
118         return original.isPresent() ? original.get().getChild(child) : Optional.absent();
119     }
120
121     private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
122         if (writtenOriginal == null) {
123             // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
124             // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
125             // modifications.
126             writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
127         }
128
129         return writtenOriginal.getChild(child);
130     }
131
132     /**
133      * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
134      * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
135      * to take the current node's operation into account.
136      *
137      * @param child Child we are looking to modify
138      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
139      * @return Before-image tree node as observed by that child.
140      */
141     private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
142         switch (operation) {
143         case DELETE:
144             // DELETE implies non-presence
145             return Optional.absent();
146         case NONE:
147         case TOUCH:
148         case MERGE:
149             return metadataFromSnapshot(child);
150         case WRITE:
151             // WRITE implies presence based on written data
152             return metadataFromData(child, modVersion);
153         }
154
155         throw new IllegalStateException("Unhandled node operation " + operation);
156     }
157
158     /**
159      *
160      * Returns child modification if child was modified, creates {@link ModifiedNode}
161      * for child otherwise.
162      *
163      * 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 modification
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
227                 // NONE, because lazy expansion of parent MERGE node would reintroduce it
228                 // again.
229                 newType = LogicalOperation.DELETE;
230                 break;
231         case TOUCH:
232         case WRITE:
233             /*
234              * We are canceling a previous modification. This is a bit tricky,
235              * as the original write may have just introduced the data, or it
236              * may have modified it.
237              *
238              * As documented in BUG-2470, a delete of data introduced in this
239              * transaction needs to be turned into 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 value
257      */
258     void write(final NormalizedNode<?, ?> value) {
259         updateValue(LogicalOperation.WRITE, value);
260         children.clear();
261     }
262
263     /**
264      * Seal the modification node and prune any children which has not been modified.
265      *
266      * @param schema
267      */
268     void seal(final ModificationApplyOperation schema, final Version version) {
269         clearSnapshot();
270         writtenOriginal = null;
271
272         switch (operation) {
273             case TOUCH:
274                 // A TOUCH node without any children is a no-op
275                 if (children.isEmpty()) {
276                     updateOperationType(LogicalOperation.NONE);
277                 }
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).get().getData();
284                     children.clear();
285                 }
286
287                 schema.verifyStructure(value, true);
288                 break;
289             /*
290              * Perform full validation in case of merge operation. This validation is performed during sealing of
291              * a ModifiedNode when we run InMemoryDataTreeModification.ready() just as it is in case of write operation
292              * above.
293              *
294              * Some parts of this validation may also be re-done during InMemoryDataTree.prepare() in case when we
295              * merge or write a MapEntry directly (e.g. Bug5968MergeTest.mergeValidMapEntryTest()), however in other
296              * cases full validation is performed only once just here.
297              */
298             case MERGE:
299                 schema.verifyStructure(schema.apply(this, getOriginal(), version).get().getData(), true);
300                 break;
301             default:
302                 break;
303         }
304     }
305
306     private void clearSnapshot() {
307         snapshotCache = null;
308     }
309
310     Optional<TreeNode> getSnapshot() {
311         return snapshotCache;
312     }
313
314     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
315         snapshotCache = Preconditions.checkNotNull(snapshot);
316         return snapshot;
317     }
318
319     void updateOperationType(final LogicalOperation type) {
320         operation = type;
321         modType = null;
322
323         // Make sure we do not reuse previously-instantiated data-derived metadata
324         writtenOriginal = null;
325         clearSnapshot();
326     }
327
328     @Override
329     public String toString() {
330         return "NodeModification [identifier=" + identifier + ", modificationType="
331                 + operation + ", childModification=" + children + "]";
332     }
333
334     void resolveModificationType(@Nonnull final ModificationType type) {
335         modType = type;
336     }
337
338     /**
339      * Update this node's value and operation type without disturbing any of its child modifications.
340      *
341      * @param type New operation type
342      * @param value New node value
343      */
344     void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
345         this.value = Preconditions.checkNotNull(value);
346         updateOperationType(type);
347     }
348
349     /**
350      * Return the physical modification done to data. May return null if the
351      * operation has not been applied to the underlying tree. This is different
352      * from the logical operation in that it can actually be a no-op if the
353      * operation has no side-effects (like an empty merge on a container).
354      *
355      * @return Modification type.
356      */
357     ModificationType getModificationType() {
358         return modType;
359     }
360
361     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
362         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
363     }
364
365     void setValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current, final TreeNode node) {
366         this.validatedOp = Preconditions.checkNotNull(op);
367         this.validatedCurrent = Preconditions.checkNotNull(current);
368         this.validatedNode = Preconditions.checkNotNull(node);
369     }
370
371     TreeNode getValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current) {
372         return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;
373     }
374 }