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 static com.google.common.base.Preconditions.checkArgument;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import java.util.Collection;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
28 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
30 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
32 private final Class<? extends NormalizedNode<?, ?>> nodeClass;
33 private final boolean verifyChildrenStructure;
35 protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
36 final TreeType treeType) {
37 this.nodeClass = Preconditions.checkNotNull(nodeClass , "nodeClass");
38 this.verifyChildrenStructure = (treeType == TreeType.CONFIGURATION);
41 @SuppressWarnings("rawtypes")
43 void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
44 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
45 checkArgument(writtenValue instanceof NormalizedNodeContainer);
46 if (verifyChildrenStructure && verifyChildren) {
47 final NormalizedNodeContainer container = (NormalizedNodeContainer) writtenValue;
48 for (final Object child : container.getValue()) {
49 checkArgument(child instanceof NormalizedNode);
50 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
51 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
52 if (childOp.isPresent()) {
53 childOp.get().verifyStructure(castedChild, verifyChildren);
55 throw new SchemaValidationFailedException(String.format(
56 "Child %s is not valid child according to schema.", castedChild.getIdentifier()));
62 protected void recursivelyVerifyStructure(NormalizedNode<?, ?> value) {
63 final NormalizedNodeContainer container = (NormalizedNodeContainer) value;
64 for (final Object child : container.getValue()) {
65 checkArgument(child instanceof NormalizedNode);
66 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
67 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
68 if (childOp.isPresent()) {
69 childOp.get().recursivelyVerifyStructure(castedChild);
71 throw new SchemaValidationFailedException(
72 String.format("Child %s is not valid child according to schema.", castedChild.getIdentifier()));
78 protected TreeNode applyWrite(final ModifiedNode modification,
79 final Optional<TreeNode> currentMeta, final Version version) {
80 final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
81 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
83 if (modification.getChildren().isEmpty()) {
88 * This is where things get interesting. The user has performed a write and
89 * then she applied some more modifications to it. So we need to make sense
90 * of that an apply the operations on top of the written value. We could have
91 * done it during the write, but this operation is potentially expensive, so
92 * we have left it out of the fast path.
94 * As it turns out, once we materialize the written data, we can share the
95 * code path with the subtree change. So let's create an unsealed TreeNode
96 * and run the common parts on it -- which end with the node being sealed.
98 * FIXME: this code needs to be moved out from the prepare() path and into
99 * the read() and seal() paths. Merging of writes needs to be charged
100 * to the code which originated this, not to the code which is
101 * attempting to make it visible.
103 final MutableTreeNode mutable = newValueMeta.mutable();
104 mutable.setSubtreeVersion(version);
106 @SuppressWarnings("rawtypes")
107 final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
108 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
110 // We are good to go except one detail: this is a single logical write, but
111 // we have a result TreeNode which has been forced to materialized, e.g. it
112 // is larger than it needs to be. Create a new TreeNode to host the data.
113 return TreeNodeFactory.createTreeNode(result.getData(), version);
117 * Applies write/remove diff operation for each modification child in modification subtree.
118 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
120 * @param meta MutableTreeNode (IndexTreeNode)
121 * @param data DataBuilder
122 * @param nodeVersion Version of TreeNode
123 * @param modifications modification operations to apply
124 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
126 @SuppressWarnings({ "rawtypes", "unchecked" })
127 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
128 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
130 for (final ModifiedNode mod : modifications) {
131 final YangInstanceIdentifier.PathArgument id = mod.getIdentifier();
132 final Optional<TreeNode> cm = meta.getChild(id);
134 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
135 if (result.isPresent()) {
136 final TreeNode tn = result.get();
138 data.addChild(tn.getData());
140 meta.removeChild(id);
141 data.removeChild(id);
145 meta.setData(data.build());
150 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
152 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
153 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
154 * heavy lifting of applying the children recursively (either through here or through applyWrite().
156 final NormalizedNode<?, ?> value = modification.getWrittenValue();
158 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
159 @SuppressWarnings({"unchecked", "rawtypes"})
160 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
161 for (NormalizedNode<?, ?> c : children) {
162 final PathArgument id = c.getIdentifier();
163 modification.modifyChild(id, resolveChildOperation(id).getChildPolicy(), version);
165 return applyTouch(modification, currentMeta, version);
168 private void mergeChildrenIntoModification(final ModifiedNode modification,
169 final Collection<NormalizedNode<?, ?>> children, final Version version) {
170 for (NormalizedNode<?, ?> c : children) {
171 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
172 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp.getChildPolicy(), version);
173 childOp.mergeIntoModifiedNode(childNode, c, version);
178 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
179 final Version version) {
180 @SuppressWarnings({ "unchecked", "rawtypes" })
181 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
183 switch (modification.getOperation()) {
185 // Fresh node, just record a MERGE with a value
186 recursivelyVerifyStructure(value);
187 modification.updateValue(LogicalOperation.MERGE, value);
191 mergeChildrenIntoModification(modification, children, version);
192 // We record empty merge value, since real children merges
193 // are already expanded. This is needed to satisfy non-null for merge
194 // original merge value can not be used since it mean different
195 // order of operation - parent changes are always resolved before
196 // children ones, and having node in TOUCH means children was modified
198 modification.updateValue(LogicalOperation.MERGE, createEmptyValue(value));
201 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark as MERGE,
202 // invalidating cached snapshot
203 mergeChildrenIntoModification(modification, children, version);
204 modification.updateOperationType(LogicalOperation.MERGE);
207 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means we
208 // are really performing a write. One thing that ruins that are any child modifications. If there are any,
209 // we will perform a read() to get the current state of affairs, turn this into into a WRITE and then
210 // append any child entries.
211 if (!modification.getChildren().isEmpty()) {
212 // Version does not matter here as we'll throw it out
213 final Optional<TreeNode> current = apply(modification, modification.getOriginal(), Version.initial());
214 if (current.isPresent()) {
215 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
216 mergeChildrenIntoModification(modification, children, version);
221 modification.updateValue(LogicalOperation.WRITE, value);
224 // We are augmenting a previous write. We'll just walk value's children, get the corresponding ModifiedNode
225 // and run recursively on it
226 mergeChildrenIntoModification(modification, children, version);
227 modification.updateOperationType(LogicalOperation.WRITE);
231 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
234 @SuppressWarnings({"rawtypes", "unchecked"})
235 private NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> value,
236 Collection<NormalizedNode<?, ?>> children) {
237 NormalizedNodeContainerBuilder builder = createBuilder(value);
238 for (NormalizedNode<?, ?> child : children) {
239 builder.removeChild(child.getIdentifier());
241 return builder.build();
245 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
247 * The user may have issued an empty merge operation. In this case we do not perform
248 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
249 * also means the ModificationType is UNMODIFIED.
251 final Collection<ModifiedNode> children = modification.getChildren();
252 if (!children.isEmpty()) {
253 @SuppressWarnings("rawtypes")
254 final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
255 final MutableTreeNode newMeta = currentMeta.mutable();
256 newMeta.setSubtreeVersion(version);
257 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
260 * It is possible that the only modifications under this node were empty merges,
261 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
262 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
263 * of speeding up any users, who can skip processing child nodes.
265 * In order to do that, though, we have to check all child operations are UNMODIFIED.
266 * Let's do precisely that, stopping as soon we find a different result.
268 for (final ModifiedNode child : children) {
269 if (child.getModificationType() != ModificationType.UNMODIFIED) {
270 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
276 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
277 // replace the metadata node.
278 modification.resolveModificationType(ModificationType.UNMODIFIED);
283 protected void checkTouchApplicable(final YangInstanceIdentifier path, final NodeModification modification,
284 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
285 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
286 throw new ModifiedNodeDoesNotExistException(path, String.format("Node %s does not exist. Cannot apply modification to its children.", path));
289 if (!current.isPresent()) {
290 throw new ConflictingModificationAppliedException(path, "Node was deleted by other transaction.");
293 checkChildPreconditions(path, modification, current.get(), version);
297 * Recursively check child preconditions.
299 * @param path current node path
300 * @param modification current modification
301 * @param current Current data tree node.
303 private void checkChildPreconditions(final YangInstanceIdentifier path, final NodeModification modification,
304 final TreeNode current, final Version version) throws DataValidationFailedException {
305 for (final NodeModification childMod : modification.getChildren()) {
306 final YangInstanceIdentifier.PathArgument childId = childMod.getIdentifier();
307 final Optional<TreeNode> childMeta = current.getChild(childId);
309 final YangInstanceIdentifier childPath = path.node(childId);
310 resolveChildOperation(childId).checkApplicable(childPath, childMod, childMeta, version);
315 protected void checkMergeApplicable(final YangInstanceIdentifier path, final NodeModification modification,
316 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
317 if (current.isPresent()) {
318 checkChildPreconditions(path, modification, current.get(), version);
322 protected boolean verifyChildrenStructure() {
323 return verifyChildrenStructure;
326 @SuppressWarnings("rawtypes")
327 protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
329 protected abstract NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> original);