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;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import java.util.Collection;
15 import java.util.Optional;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.DataTreeConfiguration;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
31 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
33 private final Class<? extends NormalizedNode<?, ?>> nodeClass;
34 private final boolean verifyChildrenStructure;
36 protected AbstractNodeContainerModificationStrategy(final Class<? extends NormalizedNode<?, ?>> nodeClass,
37 final DataTreeConfiguration treeConfig) {
38 this.nodeClass = Preconditions.checkNotNull(nodeClass , "nodeClass");
39 this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
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 "Node %s is not a valid child of %s according to the schema.",
57 castedChild.getIdentifier(), container.getIdentifier()));
64 protected void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
65 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
66 for (final Object child : container.getValue()) {
67 checkArgument(child instanceof NormalizedNode);
68 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
69 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
70 if (childOp.isPresent()) {
71 childOp.get().recursivelyVerifyStructure(castedChild);
73 throw new SchemaValidationFailedException(
74 String.format("Node %s is not a valid child of %s according to the schema.",
75 castedChild.getIdentifier(), container.getIdentifier()));
81 protected TreeNode applyWrite(final ModifiedNode modification,
82 final Optional<TreeNode> currentMeta, final Version version) {
83 final NormalizedNode<?, ?> newValue = modification.getWrittenValue();
84 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
86 if (modification.getChildren().isEmpty()) {
91 * This is where things get interesting. The user has performed a write and
92 * then she applied some more modifications to it. So we need to make sense
93 * of that an apply the operations on top of the written value. We could have
94 * done it during the write, but this operation is potentially expensive, so
95 * we have left it out of the fast path.
97 * As it turns out, once we materialize the written data, we can share the
98 * code path with the subtree change. So let's create an unsealed TreeNode
99 * and run the common parts on it -- which end with the node being sealed.
101 * FIXME: this code needs to be moved out from the prepare() path and into
102 * the read() and seal() paths. Merging of writes needs to be charged
103 * to the code which originated this, not to the code which is
104 * attempting to make it visible.
106 final MutableTreeNode mutable = newValueMeta.mutable();
107 mutable.setSubtreeVersion(version);
109 @SuppressWarnings("rawtypes")
110 final NormalizedNodeContainerBuilder dataBuilder = createBuilder(newValue);
111 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
113 // We are good to go except one detail: this is a single logical write, but
114 // we have a result TreeNode which has been forced to materialized, e.g. it
115 // is larger than it needs to be. Create a new TreeNode to host the data.
116 return TreeNodeFactory.createTreeNode(result.getData(), version);
120 * Applies write/remove diff operation for each modification child in modification subtree.
121 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
123 * @param meta MutableTreeNode (IndexTreeNode)
124 * @param data DataBuilder
125 * @param nodeVersion Version of TreeNode
126 * @param modifications modification operations to apply
127 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
129 @SuppressWarnings({ "rawtypes", "unchecked" })
130 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
131 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
133 for (final ModifiedNode mod : modifications) {
134 final PathArgument id = mod.getIdentifier();
135 final Optional<TreeNode> cm = meta.getChild(id);
137 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
138 if (result.isPresent()) {
139 final TreeNode tn = result.get();
141 data.addChild(tn.getData());
143 meta.removeChild(id);
144 data.removeChild(id);
148 meta.setData(data.build());
153 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
155 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
156 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
157 * heavy lifting of applying the children recursively (either through here or through applyWrite().
159 final NormalizedNode<?, ?> value = modification.getWrittenValue();
161 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
162 @SuppressWarnings({"unchecked", "rawtypes"})
163 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
164 for (final NormalizedNode<?, ?> c : children) {
165 final PathArgument id = c.getIdentifier();
166 modification.modifyChild(id, resolveChildOperation(id), version);
168 return applyTouch(modification, currentMeta, version);
171 private void mergeChildrenIntoModification(final ModifiedNode modification,
172 final Collection<NormalizedNode<?, ?>> children, final Version version) {
173 for (final NormalizedNode<?, ?> c : children) {
174 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
175 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
176 childOp.mergeIntoModifiedNode(childNode, c, version);
181 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
182 final Version version) {
183 @SuppressWarnings({ "unchecked", "rawtypes" })
184 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
186 switch (modification.getOperation()) {
188 // Fresh node, just record a MERGE with a value
189 recursivelyVerifyStructure(value);
190 modification.updateValue(LogicalOperation.MERGE, value);
194 mergeChildrenIntoModification(modification, children, version);
195 // We record empty merge value, since real children merges
196 // are already expanded. This is needed to satisfy non-null for merge
197 // original merge value can not be used since it mean different
198 // order of operation - parent changes are always resolved before
199 // children ones, and having node in TOUCH means children was modified
201 modification.updateValue(LogicalOperation.MERGE, createEmptyValue(value));
204 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
205 // as MERGE, invalidating cached snapshot
206 mergeChildrenIntoModification(modification, children, version);
207 modification.updateOperationType(LogicalOperation.MERGE);
210 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
211 // we are really performing a write. One thing that ruins that are any child modifications. If there
212 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
213 // and then append any child entries.
214 if (!modification.getChildren().isEmpty()) {
215 // Version does not matter here as we'll throw it out
216 final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
218 if (current.isPresent()) {
219 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
220 mergeChildrenIntoModification(modification, children, version);
225 modification.updateValue(LogicalOperation.WRITE, value);
228 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
229 // ModifiedNode and run recursively on it
230 mergeChildrenIntoModification(modification, children, version);
231 modification.updateOperationType(LogicalOperation.WRITE);
234 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
239 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
241 * The user may have issued an empty merge operation. In this case we do not perform
242 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
243 * also means the ModificationType is UNMODIFIED.
245 final Collection<ModifiedNode> children = modification.getChildren();
246 if (!children.isEmpty()) {
247 @SuppressWarnings("rawtypes")
248 final NormalizedNodeContainerBuilder dataBuilder = createBuilder(currentMeta.getData());
249 final MutableTreeNode newMeta = currentMeta.mutable();
250 newMeta.setSubtreeVersion(version);
251 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
254 * It is possible that the only modifications under this node were empty merges,
255 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
256 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
257 * of speeding up any users, who can skip processing child nodes.
259 * In order to do that, though, we have to check all child operations are UNMODIFIED.
260 * Let's do precisely that, stopping as soon we find a different result.
262 for (final ModifiedNode child : children) {
263 if (child.getModificationType() != ModificationType.UNMODIFIED) {
264 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
270 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
271 // replace the metadata node.
272 modification.resolveModificationType(ModificationType.UNMODIFIED);
277 protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
278 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
279 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
280 final YangInstanceIdentifier id = path.toInstanceIdentifier();
281 throw new ModifiedNodeDoesNotExistException(id,
282 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
285 checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
286 checkChildPreconditions(path, modification, current.get(), version);
290 * Recursively check child preconditions.
292 * @param path current node path
293 * @param modification current modification
294 * @param current Current data tree node.
296 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
297 final TreeNode current, final Version version) throws DataValidationFailedException {
298 for (final NodeModification childMod : modification.getChildren()) {
299 final PathArgument childId = childMod.getIdentifier();
300 final Optional<TreeNode> childMeta = current.getChild(childId);
304 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
312 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
313 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
314 if (current.isPresent()) {
315 checkChildPreconditions(path, modification, current.get(), version);
319 protected boolean verifyChildrenStructure() {
320 return verifyChildrenStructure;
323 @SuppressWarnings("rawtypes")
324 protected abstract NormalizedNodeContainerBuilder createBuilder(NormalizedNode<?, ?> original);
326 protected abstract NormalizedNode<?, ?> createEmptyValue(NormalizedNode<?, ?> original);