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