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.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
33 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
34 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
36 abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
37 extends SchemaAwareApplyOperation<T> {
38 abstract static class Invisible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
39 private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
41 Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
42 final SchemaAwareApplyOperation<T> entryStrategy) {
43 super(support, treeConfig);
44 this.entryStrategy = requireNonNull(entryStrategy);
49 return entryStrategy.getSchema();
52 final Optional<ModificationApplyOperation> entryStrategy() {
53 return Optional.of(entryStrategy);
57 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
58 return super.addToStringAttributes(helper).add("entry", entryStrategy);
62 abstract static class Visible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
63 private final @NonNull T schema;
65 Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
67 super(support, treeConfig);
68 this.schema = requireNonNull(schema);
77 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
78 return super.addToStringAttributes(helper).add("schema", schema);
83 * Fake TreeNode version used in
84 * {@link #checkTouchApplicable(ModificationPath, NodeModification, Optional, Version)}
85 * It is okay to use a global constant, as the delegate will ignore it anyway.
87 private static final Version FAKE_VERSION = Version.initial();
89 private final NormalizedNodeContainerSupport<?, ?> support;
90 private final boolean verifyChildrenStructure;
92 AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
93 final DataTreeConfiguration treeConfig) {
94 this.support = requireNonNull(support);
95 this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
99 protected final ChildTrackingPolicy getChildPolicy() {
100 return support.childPolicy;
104 final void verifyValue(final NormalizedNode<?, ?> writtenValue) {
105 final Class<?> nodeClass = support.requiredClass;
106 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
107 checkArgument(writtenValue instanceof NormalizedNodeContainer);
111 final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
112 if (verifyChildrenStructure) {
113 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
114 for (final Object child : container.getValue()) {
115 checkArgument(child instanceof NormalizedNode);
116 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
117 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
118 if (childOp.isPresent()) {
119 childOp.get().fullVerifyStructure(castedChild);
121 throw new SchemaValidationFailedException(String.format(
122 "Node %s is not a valid child of %s according to the schema.",
123 castedChild.getIdentifier(), container.getIdentifier()));
127 optionalVerifyValueChildren(writtenValue);
129 mandatoryVerifyValueChildren(writtenValue);
133 * Perform additional verification on written value's child structure, like presence of mandatory children and
134 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
136 * @param writtenValue Effective written value
138 void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
143 * Perform additional verification on written value's child structure, like presence of mandatory children.
144 * The default implementation does nothing.
146 * @param writtenValue Effective written value
148 void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
153 protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
154 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
155 for (final Object child : container.getValue()) {
156 checkArgument(child instanceof NormalizedNode);
157 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
158 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
159 if (!childOp.isPresent()) {
160 throw new SchemaValidationFailedException(
161 String.format("Node %s is not a valid child of %s according to the schema.",
162 castedChild.getIdentifier(), container.getIdentifier()));
165 childOp.get().recursivelyVerifyStructure(castedChild);
170 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
171 final Optional<TreeNode> currentMeta, final Version version) {
172 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
174 if (modification.getChildren().isEmpty()) {
179 * This is where things get interesting. The user has performed a write and
180 * then she applied some more modifications to it. So we need to make sense
181 * of that an apply the operations on top of the written value. We could have
182 * done it during the write, but this operation is potentially expensive, so
183 * we have left it out of the fast path.
185 * As it turns out, once we materialize the written data, we can share the
186 * code path with the subtree change. So let's create an unsealed TreeNode
187 * and run the common parts on it -- which end with the node being sealed.
189 * FIXME: this code needs to be moved out from the prepare() path and into
190 * the read() and seal() paths. Merging of writes needs to be charged
191 * to the code which originated this, not to the code which is
192 * attempting to make it visible.
194 final MutableTreeNode mutable = newValueMeta.mutable();
195 mutable.setSubtreeVersion(version);
197 @SuppressWarnings("rawtypes")
198 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
199 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
201 // We are good to go except one detail: this is a single logical write, but
202 // we have a result TreeNode which has been forced to materialized, e.g. it
203 // is larger than it needs to be. Create a new TreeNode to host the data.
204 return TreeNodeFactory.createTreeNode(result.getData(), version);
208 * Applies write/remove diff operation for each modification child in modification subtree.
209 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
211 * @param meta MutableTreeNode (IndexTreeNode)
212 * @param data DataBuilder
213 * @param nodeVersion Version of TreeNode
214 * @param modifications modification operations to apply
215 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
217 @SuppressWarnings({ "rawtypes", "unchecked" })
218 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
219 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
221 for (final ModifiedNode mod : modifications) {
222 final PathArgument id = mod.getIdentifier();
223 final Optional<TreeNode> cm = meta.getChild(id);
225 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
226 if (result.isPresent()) {
227 final TreeNode tn = result.get();
229 data.addChild(tn.getData());
231 meta.removeChild(id);
232 data.removeChild(id);
236 meta.setData(data.build());
241 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
243 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
244 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
245 * heavy lifting of applying the children recursively (either through here or through applyWrite().
247 final NormalizedNode<?, ?> value = modification.getWrittenValue();
249 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
250 @SuppressWarnings({"unchecked", "rawtypes"})
251 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
252 for (final NormalizedNode<?, ?> c : children) {
253 final PathArgument id = c.getIdentifier();
254 modification.modifyChild(id, resolveChildOperation(id), version);
256 return applyTouch(modification, currentMeta, version);
259 private void mergeChildrenIntoModification(final ModifiedNode modification,
260 final Collection<NormalizedNode<?, ?>> children, final Version version) {
261 for (final NormalizedNode<?, ?> c : children) {
262 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
263 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
264 childOp.mergeIntoModifiedNode(childNode, c, version);
269 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
270 final Version version) {
271 @SuppressWarnings({ "unchecked", "rawtypes" })
272 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
274 switch (modification.getOperation()) {
276 // Fresh node, just record a MERGE with a value
277 recursivelyVerifyStructure(value);
278 modification.updateValue(LogicalOperation.MERGE, value);
282 mergeChildrenIntoModification(modification, children, version);
283 // We record empty merge value, since real children merges
284 // are already expanded. This is needed to satisfy non-null for merge
285 // original merge value can not be used since it mean different
286 // order of operation - parent changes are always resolved before
287 // children ones, and having node in TOUCH means children was modified
289 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
292 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
293 // as MERGE, invalidating cached snapshot
294 mergeChildrenIntoModification(modification, children, version);
295 modification.updateOperationType(LogicalOperation.MERGE);
298 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
299 // we are really performing a write. One thing that ruins that are any child modifications. If there
300 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
301 // and then append any child entries.
302 if (!modification.getChildren().isEmpty()) {
303 // Version does not matter here as we'll throw it out
304 final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
306 if (current.isPresent()) {
307 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
308 mergeChildrenIntoModification(modification, children, version);
313 modification.updateValue(LogicalOperation.WRITE, value);
316 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
317 // ModifiedNode and run recursively on it
318 mergeChildrenIntoModification(modification, children, version);
319 modification.updateOperationType(LogicalOperation.WRITE);
322 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
327 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
329 * The user may have issued an empty merge operation. In this case we do not perform
330 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
331 * also means the ModificationType is UNMODIFIED.
333 final Collection<ModifiedNode> children = modification.getChildren();
334 if (!children.isEmpty()) {
335 @SuppressWarnings("rawtypes")
336 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
337 final MutableTreeNode newMeta = currentMeta.mutable();
338 newMeta.setSubtreeVersion(version);
339 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
342 * It is possible that the only modifications under this node were empty merges,
343 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
344 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
345 * of speeding up any users, who can skip processing child nodes.
347 * In order to do that, though, we have to check all child operations are UNMODIFIED.
348 * Let's do precisely that, stopping as soon we find a different result.
350 for (final ModifiedNode child : children) {
351 if (child.getModificationType() != ModificationType.UNMODIFIED) {
352 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
358 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
359 // replace the metadata node.
360 modification.resolveModificationType(ModificationType.UNMODIFIED);
365 protected void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
366 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
367 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
368 final YangInstanceIdentifier id = path.toInstanceIdentifier();
369 throw new ModifiedNodeDoesNotExistException(id,
370 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
373 checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
374 checkChildPreconditions(path, modification, current.get(), version);
378 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification. This variant is used by
379 * subclasses which support automatic lifecycle.
381 * @param path Path to current node
382 * @param modification Node modification which should be applied.
383 * @param current Current state of data tree
384 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
385 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
386 * modification is not applicable (e.g. leaf node).
388 final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
389 final Optional<TreeNode> current, final Version version, final NormalizedNode<?, ?> emptyNode)
390 throws DataValidationFailedException {
391 checkChildPreconditions(path, modification, touchMeta(current, emptyNode), version);
395 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
396 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
397 if (current.isPresent()) {
398 checkChildPreconditions(path, modification, current.get(), version);
403 * Recursively check child preconditions.
405 * @param path current node path
406 * @param modification current modification
407 * @param current Current data tree node.
409 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
410 final TreeNode current, final Version version) throws DataValidationFailedException {
411 for (final NodeModification childMod : modification.getChildren()) {
412 final PathArgument childId = childMod.getIdentifier();
413 final Optional<TreeNode> childMeta = current.getChild(childId);
417 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
424 private static TreeNode touchMeta(final Optional<TreeNode> current, final NormalizedNode<?, ?> emptyNode) {
425 return current.isPresent() ? current.get() : TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
429 public final String toString() {
430 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
433 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
434 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);