23674daf32655142e17815d6ca3c52486e3b6485
[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.NormalizedNodes;
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
30  * to the data store tree.
31  *
32  * This tree is lazily created and populated via {@link #modifyChild(PathArgument)}
33  * and {@link TreeNode} which represents original state as tracked by {@link #getOriginal()}.
34  */
35 @NotThreadSafe
36 final class ModifiedNode extends NodeModification implements StoreTreeNode<ModifiedNode> {
37     static final Predicate<ModifiedNode> IS_TERMINAL_PREDICATE = new Predicate<ModifiedNode>() {
38         @Override
39         public boolean apply(@Nonnull final ModifiedNode input) {
40             Preconditions.checkNotNull(input);
41             switch (input.getOperation()) {
42             case DELETE:
43             case MERGE:
44             case WRITE:
45                 return true;
46             case TOUCH:
47             case NONE:
48                 return false;
49             }
50
51             throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
52         }
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     private ModifiedNode(final PathArgument identifier, final Optional<TreeNode> original, final ChildTrackingPolicy childPolicy) {
67         this.identifier = identifier;
68         this.original = original;
69         this.children = childPolicy.createMap();
70     }
71
72     /**
73      * Return the value which was written to this node.
74      *
75      * @return Currently-written value
76      */
77     public NormalizedNode<?, ?> getWrittenValue() {
78         return value;
79     }
80
81     @Override
82     public PathArgument getIdentifier() {
83         return identifier;
84     }
85
86     @Override
87     Optional<TreeNode> getOriginal() {
88         return original;
89     }
90
91     @Override
92     LogicalOperation getOperation() {
93         return operation;
94     }
95
96     /**
97      *
98      * Returns child modification if child was modified
99      *
100      * @return Child modification if direct child or it's subtree
101      *  was modified.
102      *
103      */
104     @Override
105     public Optional<ModifiedNode> getChild(final PathArgument child) {
106         return Optional.<ModifiedNode> fromNullable(children.get(child));
107     }
108
109     private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
110         return original.isPresent() ? original.get().getChild(child) : Optional.<TreeNode>absent();
111     }
112
113     private Optional<TreeNode> metadataFromData(@Nonnull final PathArgument child, final Version modVersion) {
114         if (writtenOriginal == null) {
115             // Lazy instantiation, as we do not want do this for all writes. We are using the modification's version
116             // here, as that version is what the SchemaAwareApplyOperation will see when dealing with the resulting
117             // modifications.
118             writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
119         }
120
121         return writtenOriginal.getChild(child);
122     }
123
124     /**
125      * Determine the base tree node we are going to apply the operation to. This is not entirely trivial because
126      * both DELETE and WRITE operations unconditionally detach their descendants from the original snapshot, so we need
127      * to take the current node's operation into account.
128      *
129      * @param child Child we are looking to modify
130      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
131      * @return Before-image tree node as observed by that child.
132      */
133     private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
134         switch (operation) {
135         case DELETE:
136             // DELETE implies non-presence
137             return Optional.absent();
138         case NONE:
139         case TOUCH:
140             return metadataFromSnapshot(child);
141         case MERGE:
142             // MERGE is half-way between TOUCH and WRITE. If the child exists in data, it behaves as a WRITE, otherwise
143             // it behaves as a TOUCH
144             if (NormalizedNodes.findNode(value, child).isPresent()) {
145                 return metadataFromData(child, modVersion);
146             } else {
147                 return metadataFromSnapshot(child);
148             }
149         case WRITE:
150             // WRITE implies presence based on written data
151             return metadataFromData(child, modVersion);
152         }
153
154         throw new IllegalStateException("Unhandled node operation " + operation);
155     }
156
157     /**
158      *
159      * Returns child modification if child was modified, creates {@link ModifiedNode}
160      * for child otherwise.
161      *
162      * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
163      * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
164      *
165      * @param child child identifier, may not be null
166      * @param childPolicy child tracking policy for the node we are looking for
167      * @param modVersion Version allocated by the calling {@link InMemoryDataTreeModification}
168      * @return {@link ModifiedNode} for specified child, with {@link #getOriginal()}
169      *         containing child metadata if child was present in original data.
170      */
171     ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ChildTrackingPolicy childPolicy,
172             @Nonnull final Version modVersion) {
173         clearSnapshot();
174         if (operation == LogicalOperation.NONE) {
175             updateOperationType(LogicalOperation.TOUCH);
176         }
177         final ModifiedNode potential = children.get(child);
178         if (potential != null) {
179             return potential;
180         }
181
182         final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
183
184
185         final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childPolicy);
186         children.put(child, newlyCreated);
187         return newlyCreated;
188     }
189
190     /**
191      * Returns all recorded direct child modification
192      *
193      * @return all recorded direct child modifications
194      */
195     @Override
196     Collection<ModifiedNode> getChildren() {
197         return children.values();
198     }
199
200     /**
201      * Records a delete for associated node.
202      */
203     void delete() {
204         final LogicalOperation newType;
205
206         switch (operation) {
207         case DELETE:
208         case NONE:
209             // We need to record this delete.
210             newType = LogicalOperation.DELETE;
211             break;
212         case MERGE:
213         case TOUCH:
214         case WRITE:
215             /*
216              * We are canceling a previous modification. This is a bit tricky,
217              * as the original write may have just introduced the data, or it
218              * may have modified it.
219              *
220              * As documented in BUG-2470, a delete of data introduced in this
221              * transaction needs to be turned into a no-op.
222              */
223             newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
224             break;
225         default:
226             throw new IllegalStateException("Unhandled deletion of node with " + operation);
227         }
228
229         clearSnapshot();
230         children.clear();
231         this.value = null;
232         updateOperationType(newType);
233     }
234
235     /**
236      * Records a write for associated node.
237      *
238      * @param value
239      */
240     void write(final NormalizedNode<?, ?> value) {
241         pushWrite(value);
242         children.clear();
243     }
244
245     // Promote the node to write, but do not lose children
246     void pushWrite(final NormalizedNode<?, ?> value) {
247         clearSnapshot();
248         updateOperationType(LogicalOperation.WRITE);
249         this.value = value;
250     }
251
252     void merge(final NormalizedNode<?, ?> value) {
253         clearSnapshot();
254         updateOperationType(LogicalOperation.MERGE);
255
256         /*
257          * Blind overwrite of any previous data is okay, no matter whether the node
258          * is simple or complex type.
259          *
260          * If this is a simple or complex type with unkeyed children, this merge will
261          * be turned into a write operation, overwriting whatever was there before.
262          *
263          * If this is a container with keyed children, there are two possibilities:
264          * - if it existed before, this value will never be consulted and the children
265          *   will get explicitly merged onto the original data.
266          * - if it did not exist before, this value will be used as a seed write and
267          *   children will be merged into it.
268          * In either case we rely on OperationWithModification to manipulate the children
269          * before calling this method, so unlike a write we do not want to clear them.
270          */
271         this.value = value;
272     }
273
274     /**
275      * Seal the modification node and prune any children which has not been modified.
276      *
277      * @param schema
278      */
279     void seal(final ModificationApplyOperation schema, final Version version) {
280         clearSnapshot();
281         writtenOriginal = null;
282
283         switch (operation) {
284             case TOUCH:
285                 // A TOUCH node without any children is a no-op
286                 if (children.isEmpty()) {
287                     updateOperationType(LogicalOperation.NONE);
288                 }
289                 break;
290             case WRITE:
291                 // A WRITE can collapse all of its children
292                 if (!children.isEmpty()) {
293                     value = schema.apply(this, getOriginal(), version).get().getData();
294                     children.clear();
295                 }
296
297                 schema.verifyStructure(value, true);
298                 break;
299             default:
300                 break;
301         }
302     }
303
304     private void clearSnapshot() {
305         snapshotCache = null;
306     }
307
308     Optional<TreeNode> getSnapshot() {
309         return snapshotCache;
310     }
311
312     Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
313         snapshotCache = Preconditions.checkNotNull(snapshot);
314         return snapshot;
315     }
316
317     private void updateOperationType(final LogicalOperation type) {
318         operation = type;
319         modType = null;
320
321         // Make sure we do not reuse previously-instantiated data-derived metadata
322         writtenOriginal = null;
323         clearSnapshot();
324     }
325
326     @Override
327     public String toString() {
328         return "NodeModification [identifier=" + identifier + ", modificationType="
329                 + operation + ", childModification=" + children + "]";
330     }
331
332     void resolveModificationType(@Nonnull final ModificationType type) {
333         modType = type;
334     }
335
336     /**
337      * Return the physical modification done to data. May return null if the
338      * operation has not been applied to the underlying tree. This is different
339      * from the logical operation in that it can actually be a no-op if the
340      * operation has no side-effects (like an empty merge on a container).
341      *
342      * @return Modification type.
343      */
344     ModificationType getModificationType() {
345         return modType;
346     }
347
348     /**
349      * Create a node which will reflect the state of this node, except it will behave as newly-written
350      * value. This is useful only for merge validation.
351      *
352      * @param value Value associated with the node
353      * @return An isolated node. This node should never reach a datatree.
354      */
355     ModifiedNode asNewlyWritten(final NormalizedNode<?, ?> value) {
356         /*
357          * We are instantiating an "equivalent" of this node. Currently the only callsite does not care
358          * about the actual iteration order, so we do not have to specify the same tracking policy as
359          * we were instantiated with. Since this is the only time we need to know that policy (it affects
360          * only things in constructor), we do not want to retain it (saves some memory on per-instance
361          * basis).
362          *
363          * We could reconstruct it using two instanceof checks (to undo what the constructor has done),
364          * which would give perfect results. The memory saving would be at most 32 bytes of a short-lived
365          * object, so let's not bother with that.
366          */
367         final ModifiedNode ret = new ModifiedNode(getIdentifier(), Optional.<TreeNode>absent(), ChildTrackingPolicy.UNORDERED);
368         ret.write(value);
369         return ret;
370     }
371
372     public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
373         return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
374     }
375 }