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.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
34 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
35 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
37 abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
38 extends SchemaAwareApplyOperation<T> {
39 abstract static class Invisible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
40 private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
42 Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
43 final SchemaAwareApplyOperation<T> entryStrategy) {
44 super(support, treeConfig);
45 this.entryStrategy = requireNonNull(entryStrategy);
50 return entryStrategy.getSchema();
53 final Optional<ModificationApplyOperation> entryStrategy() {
54 return Optional.of(entryStrategy);
58 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
59 return super.addToStringAttributes(helper).add("entry", entryStrategy);
63 abstract static class Visible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
64 private final @NonNull T schema;
66 Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
68 super(support, treeConfig);
69 this.schema = requireNonNull(schema);
78 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
79 return super.addToStringAttributes(helper).add("schema", schema);
84 * Fake TreeNode version used in
85 * {@link #checkTouchApplicable(ModificationPath, NodeModification, Optional, Version)}
86 * It is okay to use a global constant, as the delegate will ignore it anyway.
88 private static final Version FAKE_VERSION = Version.initial();
90 private final NormalizedNodeContainerSupport<?, ?> support;
91 private final boolean verifyChildrenStructure;
93 AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
94 final DataTreeConfiguration treeConfig) {
95 this.support = requireNonNull(support);
96 this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
100 protected final ChildTrackingPolicy getChildPolicy() {
101 return support.childPolicy;
105 final void verifyValue(final NormalizedNode<?, ?> writtenValue) {
106 final Class<?> nodeClass = support.requiredClass;
107 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
108 checkArgument(writtenValue instanceof NormalizedNodeContainer);
112 final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
113 if (verifyChildrenStructure) {
114 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
115 for (final NormalizedNode<?, ?> child : container.getValue()) {
116 final Optional<ModificationApplyOperation> childOp = getChild(child.getIdentifier());
117 if (childOp.isPresent()) {
118 childOp.get().fullVerifyStructure(child);
120 throw new SchemaValidationFailedException(String.format(
121 "Node %s is not a valid child of %s according to the schema.",
122 child.getIdentifier(), container.getIdentifier()));
126 optionalVerifyValueChildren(writtenValue);
128 mandatoryVerifyValueChildren(writtenValue);
132 * Perform additional verification on written value's child structure, like presence of mandatory children and
133 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
135 * @param writtenValue Effective written value
137 void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
142 * Perform additional verification on written value's child structure, like presence of mandatory children.
143 * The default implementation does nothing.
145 * @param writtenValue Effective written value
147 void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
152 protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
153 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
154 for (final NormalizedNode<?, ?> child : container.getValue()) {
155 final Optional<ModificationApplyOperation> childOp = getChild(child.getIdentifier());
156 if (!childOp.isPresent()) {
157 throw new SchemaValidationFailedException(
158 String.format("Node %s is not a valid child of %s according to the schema.",
159 child.getIdentifier(), container.getIdentifier()));
162 childOp.get().recursivelyVerifyStructure(child);
167 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
168 final Optional<? extends TreeNode> currentMeta, final Version version) {
169 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
171 if (modification.getChildren().isEmpty()) {
176 * This is where things get interesting. The user has performed a write and
177 * then she applied some more modifications to it. So we need to make sense
178 * of that an apply the operations on top of the written value. We could have
179 * done it during the write, but this operation is potentially expensive, so
180 * we have left it out of the fast path.
182 * As it turns out, once we materialize the written data, we can share the
183 * code path with the subtree change. So let's create an unsealed TreeNode
184 * and run the common parts on it -- which end with the node being sealed.
186 * FIXME: this code needs to be moved out from the prepare() path and into
187 * the read() and seal() paths. Merging of writes needs to be charged
188 * to the code which originated this, not to the code which is
189 * attempting to make it visible.
191 final MutableTreeNode mutable = newValueMeta.mutable();
192 mutable.setSubtreeVersion(version);
194 @SuppressWarnings("rawtypes")
195 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
196 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
198 // We are good to go except one detail: this is a single logical write, but
199 // we have a result TreeNode which has been forced to materialized, e.g. it
200 // is larger than it needs to be. Create a new TreeNode to host the data.
201 return TreeNodeFactory.createTreeNode(result.getData(), version);
205 * Applies write/remove diff operation for each modification child in modification subtree.
206 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
208 * @param meta MutableTreeNode (IndexTreeNode)
209 * @param data DataBuilder
210 * @param nodeVersion Version of TreeNode
211 * @param modifications modification operations to apply
212 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
214 @SuppressWarnings({ "rawtypes", "unchecked" })
215 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
216 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
218 for (final ModifiedNode mod : modifications) {
219 final PathArgument id = mod.getIdentifier();
220 final Optional<? extends TreeNode> cm = meta.getChild(id);
222 final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
223 if (result.isPresent()) {
224 final TreeNode tn = result.get();
226 data.addChild(tn.getData());
228 meta.removeChild(id);
229 data.removeChild(id);
233 meta.setData(data.build());
238 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
240 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
241 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
242 * heavy lifting of applying the children recursively (either through here or through applyWrite().
244 final NormalizedNode<?, ?> value = modification.getWrittenValue();
246 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
247 for (final NormalizedNode<?, ?> c : ((NormalizedNodeContainer<?, ?, ?>) value).getValue()) {
248 final PathArgument id = c.getIdentifier();
249 modification.modifyChild(id, resolveChildOperation(id), version);
251 return applyTouch(modification, currentMeta, version);
254 private void mergeChildrenIntoModification(final ModifiedNode modification,
255 final Collection<? extends NormalizedNode<?, ?>> children, final Version version) {
256 for (final NormalizedNode<?, ?> c : children) {
257 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
258 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
259 childOp.mergeIntoModifiedNode(childNode, c, version);
264 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
265 final Version version) {
266 final Collection<? extends NormalizedNode<?, ?>> children =
267 ((NormalizedNodeContainer<?, ?, ?>)value).getValue();
269 switch (modification.getOperation()) {
271 // Fresh node, just record a MERGE with a value
272 recursivelyVerifyStructure(value);
273 modification.updateValue(LogicalOperation.MERGE, value);
277 mergeChildrenIntoModification(modification, children, version);
278 // We record empty merge value, since real children merges
279 // are already expanded. This is needed to satisfy non-null for merge
280 // original merge value can not be used since it mean different
281 // order of operation - parent changes are always resolved before
282 // children ones, and having node in TOUCH means children was modified
284 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
287 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
288 // as MERGE, invalidating cached snapshot
289 mergeChildrenIntoModification(modification, children, version);
290 modification.updateOperationType(LogicalOperation.MERGE);
293 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
294 // we are really performing a write. One thing that ruins that are any child modifications. If there
295 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
296 // and then append any child entries.
297 if (!modification.getChildren().isEmpty()) {
298 // Version does not matter here as we'll throw it out
299 final Optional<? extends TreeNode> current = apply(modification, modification.getOriginal(),
301 if (current.isPresent()) {
302 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
303 mergeChildrenIntoModification(modification, children, version);
308 modification.updateValue(LogicalOperation.WRITE, value);
311 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
312 // ModifiedNode and run recursively on it
313 mergeChildrenIntoModification(modification, children, version);
314 modification.updateOperationType(LogicalOperation.WRITE);
317 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
322 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
324 * The user may have issued an empty merge operation. In this case we do not perform
325 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
326 * also means the ModificationType is UNMODIFIED.
328 final Collection<ModifiedNode> children = modification.getChildren();
329 if (!children.isEmpty()) {
330 @SuppressWarnings("rawtypes")
331 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
332 final MutableTreeNode newMeta = currentMeta.mutable();
333 newMeta.setSubtreeVersion(version);
334 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
337 * It is possible that the only modifications under this node were empty merges,
338 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
339 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
340 * of speeding up any users, who can skip processing child nodes.
342 * In order to do that, though, we have to check all child operations are UNMODIFIED.
343 * Let's do precisely that, stopping as soon we find a different result.
345 for (final ModifiedNode child : children) {
346 if (child.getModificationType() != ModificationType.UNMODIFIED) {
347 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
353 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
354 // replace the metadata node.
355 modification.resolveModificationType(ModificationType.UNMODIFIED);
360 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
361 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
362 final TreeNode currentNode;
363 if (!current.isPresent()) {
364 currentNode = defaultTreeNode();
365 if (currentNode == null) {
366 if (!modification.getOriginal().isPresent()) {
367 final YangInstanceIdentifier id = path.toInstanceIdentifier();
368 throw new ModifiedNodeDoesNotExistException(id,
369 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
372 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
373 "Node was deleted by other transaction.");
376 currentNode = current.get();
379 checkChildPreconditions(path, modification, currentNode, version);
383 * Return the default tree node. Default implementation does nothing, but can be overridden to call
384 * {@link #defaultTreeNode(NormalizedNode)}.
386 * @return Default empty tree node, or null if no default is available
388 @Nullable TreeNode defaultTreeNode() {
389 // Defaults to no recovery
393 static final TreeNode defaultTreeNode(final NormalizedNode<?, ?> emptyNode) {
394 return TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
398 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
399 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
400 if (current.isPresent()) {
401 checkChildPreconditions(path, modification, current.get(), version);
406 * Recursively check child preconditions.
408 * @param path current node path
409 * @param modification current modification
410 * @param current Current data tree node.
412 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
413 final TreeNode current, final Version version) throws DataValidationFailedException {
414 for (final NodeModification childMod : modification.getChildren()) {
415 final PathArgument childId = childMod.getIdentifier();
416 final Optional<? extends TreeNode> childMeta = current.getChild(childId);
420 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
428 public final String toString() {
429 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
432 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
433 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);