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