2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
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;
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;
27 * Node Modification Node and Tree
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()}.
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
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()) {
52 throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
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;
63 // Alternative history introduced in WRITE nodes. Instantiated when we touch any child underneath such a node.
64 private TreeNode writtenOriginal;
66 // Internal cache for TreeNodes created as part of validation
67 private SchemaAwareApplyOperation validatedOp;
68 private Optional<TreeNode> validatedCurrent;
69 private TreeNode validatedNode;
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();
78 public PathArgument getIdentifier() {
83 LogicalOperation getOperation() {
88 Optional<TreeNode> getOriginal() {
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}.
98 * @return Currently-written value
100 NormalizedNode<?, ?> getWrittenValue() {
106 * Returns child modification if child was modified
108 * @return Child modification if direct child or it's subtree
113 public Optional<ModifiedNode> getChild(final PathArgument child) {
114 return Optional.fromNullable(children.get(child));
117 private Optional<TreeNode> metadataFromSnapshot(@Nonnull final PathArgument child) {
118 return original.isPresent() ? original.get().getChild(child) : Optional.absent();
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
126 writtenOriginal = TreeNodeFactory.createTreeNode(value, modVersion);
129 return writtenOriginal.getChild(child);
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.
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.
141 private Optional<TreeNode> findOriginalMetadata(@Nonnull final PathArgument child, final Version modVersion) {
144 // DELETE implies non-presence
145 return Optional.absent();
149 return metadataFromSnapshot(child);
151 // WRITE implies presence based on written data
152 return metadataFromData(child, modVersion);
155 throw new IllegalStateException("Unhandled node operation " + operation);
160 * Returns child modification if child was modified, creates {@link ModifiedNode}
161 * for child otherwise.
163 * If this node's {@link ModificationType} is {@link ModificationType#UNMODIFIED}
164 * changes modification type to {@link ModificationType#SUBTREE_MODIFIED}
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.
172 ModifiedNode modifyChild(@Nonnull final PathArgument child, @Nonnull final ModificationApplyOperation childOper,
173 @Nonnull final Version modVersion) {
175 if (operation == LogicalOperation.NONE) {
176 updateOperationType(LogicalOperation.TOUCH);
178 final ModifiedNode potential = children.get(child);
179 if (potential != null) {
183 final Optional<TreeNode> currentMetadata = findOriginalMetadata(child, modVersion);
186 final ModifiedNode newlyCreated = new ModifiedNode(child, currentMetadata, childOper.getChildPolicy());
187 if (operation == LogicalOperation.MERGE && value != null) {
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.
192 @SuppressWarnings({ "rawtypes", "unchecked" })
193 final Optional<NormalizedNode<?, ?>> childData = ((NormalizedNodeContainer)value).getChild(child);
194 if (childData.isPresent()) {
195 childOper.mergeIntoModifiedNode(newlyCreated, childData.get(), modVersion);
199 children.put(child, newlyCreated);
204 * Returns all recorded direct child modification
206 * @return all recorded direct child modifications
209 Collection<ModifiedNode> getChildren() {
210 return children.values();
214 * Records a delete for associated node.
217 final LogicalOperation newType;
222 // We need to record this delete.
223 newType = LogicalOperation.DELETE;
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
229 newType = LogicalOperation.DELETE;
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.
238 * As documented in BUG-2470, a delete of data introduced in this
239 * transaction needs to be turned into a no-op.
241 newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
244 throw new IllegalStateException("Unhandled deletion of node with " + operation);
250 updateOperationType(newType);
254 * Records a write for associated node.
258 void write(final NormalizedNode<?, ?> value) {
259 updateValue(LogicalOperation.WRITE, value);
264 * Seal the modification node and prune any children which has not been modified.
268 void seal(final ModificationApplyOperation schema, final Version version) {
270 writtenOriginal = null;
274 // A TOUCH node without any children is a no-op
275 if (children.isEmpty()) {
276 updateOperationType(LogicalOperation.NONE);
280 // A WRITE can collapse all of its children
281 if (!children.isEmpty()) {
282 value = schema.apply(this, getOriginal(), version).get().getData();
286 schema.verifyStructure(value, true);
293 private void clearSnapshot() {
294 snapshotCache = null;
297 Optional<TreeNode> getSnapshot() {
298 return snapshotCache;
301 Optional<TreeNode> setSnapshot(final Optional<TreeNode> snapshot) {
302 snapshotCache = Preconditions.checkNotNull(snapshot);
306 void updateOperationType(final LogicalOperation type) {
310 // Make sure we do not reuse previously-instantiated data-derived metadata
311 writtenOriginal = null;
316 public String toString() {
317 return "NodeModification [identifier=" + identifier + ", modificationType="
318 + operation + ", childModification=" + children + "]";
321 void resolveModificationType(@Nonnull final ModificationType type) {
326 * Update this node's value and operation type without disturbing any of its child modifications.
328 * @param type New operation type
329 * @param value New node value
331 void updateValue(final LogicalOperation type, final NormalizedNode<?, ?> value) {
332 this.value = Preconditions.checkNotNull(value);
333 updateOperationType(type);
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).
342 * @return Modification type.
344 ModificationType getModificationType() {
348 public static ModifiedNode createUnmodified(final TreeNode metadataTree, final ChildTrackingPolicy childPolicy) {
349 return new ModifiedNode(metadataTree.getIdentifier(), Optional.of(metadataTree), childPolicy);
352 void setValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current, final TreeNode node) {
353 this.validatedOp = Preconditions.checkNotNull(op);
354 this.validatedCurrent = Preconditions.checkNotNull(current);
355 this.validatedNode = Preconditions.checkNotNull(node);
358 TreeNode getValidatedNode(final SchemaAwareApplyOperation op, final Optional<TreeNode> current) {
359 return op.equals(validatedOp) && current.equals(validatedCurrent) ? validatedNode : null;