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 static java.util.Objects.requireNonNull;
13 import com.google.common.base.MoreObjects;
14 import com.google.common.base.MoreObjects.ToStringHelper;
15 import com.google.common.base.Verify;
16 import java.util.Collection;
17 import java.util.Optional;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
31 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
33 abstract class AbstractNodeContainerModificationStrategy extends SchemaAwareApplyOperation {
34 private final NormalizedNodeContainerSupport<?, ?> support;
35 private final boolean verifyChildrenStructure;
37 AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
38 final DataTreeConfiguration treeConfig) {
39 this.support = requireNonNull(support);
40 this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
44 protected final ChildTrackingPolicy getChildPolicy() {
45 return support.childPolicy;
49 void verifyStructure(final NormalizedNode<?, ?> writtenValue, final boolean verifyChildren) {
50 final Class<?> nodeClass = support.requiredClass;
51 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
52 checkArgument(writtenValue instanceof NormalizedNodeContainer);
53 if (verifyChildrenStructure && verifyChildren) {
54 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
55 for (final Object child : container.getValue()) {
56 checkArgument(child instanceof NormalizedNode);
57 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
58 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
59 if (childOp.isPresent()) {
60 childOp.get().verifyStructure(castedChild, verifyChildren);
62 throw new SchemaValidationFailedException(String.format(
63 "Node %s is not a valid child of %s according to the schema.",
64 castedChild.getIdentifier(), container.getIdentifier()));
71 protected void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
72 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
73 for (final Object child : container.getValue()) {
74 checkArgument(child instanceof NormalizedNode);
75 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
76 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
77 if (childOp.isPresent()) {
78 childOp.get().recursivelyVerifyStructure(castedChild);
80 throw new SchemaValidationFailedException(
81 String.format("Node %s is not a valid child of %s according to the schema.",
82 castedChild.getIdentifier(), container.getIdentifier()));
88 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
89 final Optional<TreeNode> currentMeta, final Version version) {
90 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
92 if (modification.getChildren().isEmpty()) {
97 * This is where things get interesting. The user has performed a write and
98 * then she applied some more modifications to it. So we need to make sense
99 * of that an apply the operations on top of the written value. We could have
100 * done it during the write, but this operation is potentially expensive, so
101 * we have left it out of the fast path.
103 * As it turns out, once we materialize the written data, we can share the
104 * code path with the subtree change. So let's create an unsealed TreeNode
105 * and run the common parts on it -- which end with the node being sealed.
107 * FIXME: this code needs to be moved out from the prepare() path and into
108 * the read() and seal() paths. Merging of writes needs to be charged
109 * to the code which originated this, not to the code which is
110 * attempting to make it visible.
112 final MutableTreeNode mutable = newValueMeta.mutable();
113 mutable.setSubtreeVersion(version);
115 @SuppressWarnings("rawtypes")
116 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
117 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
119 // We are good to go except one detail: this is a single logical write, but
120 // we have a result TreeNode which has been forced to materialized, e.g. it
121 // is larger than it needs to be. Create a new TreeNode to host the data.
122 return TreeNodeFactory.createTreeNode(result.getData(), version);
126 * Applies write/remove diff operation for each modification child in modification subtree.
127 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
129 * @param meta MutableTreeNode (IndexTreeNode)
130 * @param data DataBuilder
131 * @param nodeVersion Version of TreeNode
132 * @param modifications modification operations to apply
133 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
135 @SuppressWarnings({ "rawtypes", "unchecked" })
136 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
137 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
139 for (final ModifiedNode mod : modifications) {
140 final PathArgument id = mod.getIdentifier();
141 final Optional<TreeNode> cm = meta.getChild(id);
143 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
144 if (result.isPresent()) {
145 final TreeNode tn = result.get();
147 data.addChild(tn.getData());
149 meta.removeChild(id);
150 data.removeChild(id);
154 meta.setData(data.build());
159 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
161 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
162 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
163 * heavy lifting of applying the children recursively (either through here or through applyWrite().
165 final NormalizedNode<?, ?> value = modification.getWrittenValue();
167 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
168 @SuppressWarnings({"unchecked", "rawtypes"})
169 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
170 for (final NormalizedNode<?, ?> c : children) {
171 final PathArgument id = c.getIdentifier();
172 modification.modifyChild(id, resolveChildOperation(id), version);
174 return applyTouch(modification, currentMeta, version);
177 private void mergeChildrenIntoModification(final ModifiedNode modification,
178 final Collection<NormalizedNode<?, ?>> children, final Version version) {
179 for (final NormalizedNode<?, ?> c : children) {
180 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
181 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
182 childOp.mergeIntoModifiedNode(childNode, c, version);
187 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
188 final Version version) {
189 @SuppressWarnings({ "unchecked", "rawtypes" })
190 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
192 switch (modification.getOperation()) {
194 // Fresh node, just record a MERGE with a value
195 recursivelyVerifyStructure(value);
196 modification.updateValue(LogicalOperation.MERGE, value);
200 mergeChildrenIntoModification(modification, children, version);
201 // We record empty merge value, since real children merges
202 // are already expanded. This is needed to satisfy non-null for merge
203 // original merge value can not be used since it mean different
204 // order of operation - parent changes are always resolved before
205 // children ones, and having node in TOUCH means children was modified
207 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
210 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
211 // as MERGE, invalidating cached snapshot
212 mergeChildrenIntoModification(modification, children, version);
213 modification.updateOperationType(LogicalOperation.MERGE);
216 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
217 // we are really performing a write. One thing that ruins that are any child modifications. If there
218 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
219 // and then append any child entries.
220 if (!modification.getChildren().isEmpty()) {
221 // Version does not matter here as we'll throw it out
222 final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
224 if (current.isPresent()) {
225 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
226 mergeChildrenIntoModification(modification, children, version);
231 modification.updateValue(LogicalOperation.WRITE, value);
234 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
235 // ModifiedNode and run recursively on it
236 mergeChildrenIntoModification(modification, children, version);
237 modification.updateOperationType(LogicalOperation.WRITE);
240 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
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 = support.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 ModificationPath path, final NodeModification modification,
284 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
285 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
286 final YangInstanceIdentifier id = path.toInstanceIdentifier();
287 throw new ModifiedNodeDoesNotExistException(id,
288 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
291 checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
292 checkChildPreconditions(path, modification, current.get(), version);
296 * Recursively check child preconditions.
298 * @param path current node path
299 * @param modification current modification
300 * @param current Current data tree node.
302 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
303 final TreeNode current, final Version version) throws DataValidationFailedException {
304 for (final NodeModification childMod : modification.getChildren()) {
305 final PathArgument childId = childMod.getIdentifier();
306 final Optional<TreeNode> childMeta = current.getChild(childId);
310 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
318 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
319 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
320 if (current.isPresent()) {
321 checkChildPreconditions(path, modification, current.get(), version);
325 protected boolean verifyChildrenStructure() {
326 return verifyChildrenStructure;
330 public final String toString() {
331 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
334 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
335 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);