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 Object child : container.getValue()) {
116 checkArgument(child instanceof NormalizedNode);
117 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
118 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
119 if (childOp.isPresent()) {
120 childOp.get().fullVerifyStructure(castedChild);
122 throw new SchemaValidationFailedException(String.format(
123 "Node %s is not a valid child of %s according to the schema.",
124 castedChild.getIdentifier(), container.getIdentifier()));
128 optionalVerifyValueChildren(writtenValue);
130 mandatoryVerifyValueChildren(writtenValue);
134 * Perform additional verification on written value's child structure, like presence of mandatory children and
135 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
137 * @param writtenValue Effective written value
139 void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
144 * Perform additional verification on written value's child structure, like presence of mandatory children.
145 * The default implementation does nothing.
147 * @param writtenValue Effective written value
149 void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
154 protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
155 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
156 for (final Object child : container.getValue()) {
157 checkArgument(child instanceof NormalizedNode);
158 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
159 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
160 if (!childOp.isPresent()) {
161 throw new SchemaValidationFailedException(
162 String.format("Node %s is not a valid child of %s according to the schema.",
163 castedChild.getIdentifier(), container.getIdentifier()));
166 childOp.get().recursivelyVerifyStructure(castedChild);
171 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
172 final Optional<? extends TreeNode> currentMeta, final Version version) {
173 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
175 if (modification.getChildren().isEmpty()) {
180 * This is where things get interesting. The user has performed a write and
181 * then she applied some more modifications to it. So we need to make sense
182 * of that an apply the operations on top of the written value. We could have
183 * done it during the write, but this operation is potentially expensive, so
184 * we have left it out of the fast path.
186 * As it turns out, once we materialize the written data, we can share the
187 * code path with the subtree change. So let's create an unsealed TreeNode
188 * and run the common parts on it -- which end with the node being sealed.
190 * FIXME: this code needs to be moved out from the prepare() path and into
191 * the read() and seal() paths. Merging of writes needs to be charged
192 * to the code which originated this, not to the code which is
193 * attempting to make it visible.
195 final MutableTreeNode mutable = newValueMeta.mutable();
196 mutable.setSubtreeVersion(version);
198 @SuppressWarnings("rawtypes")
199 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
200 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
202 // We are good to go except one detail: this is a single logical write, but
203 // we have a result TreeNode which has been forced to materialized, e.g. it
204 // is larger than it needs to be. Create a new TreeNode to host the data.
205 return TreeNodeFactory.createTreeNode(result.getData(), version);
209 * Applies write/remove diff operation for each modification child in modification subtree.
210 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
212 * @param meta MutableTreeNode (IndexTreeNode)
213 * @param data DataBuilder
214 * @param nodeVersion Version of TreeNode
215 * @param modifications modification operations to apply
216 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
218 @SuppressWarnings({ "rawtypes", "unchecked" })
219 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
220 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
222 for (final ModifiedNode mod : modifications) {
223 final PathArgument id = mod.getIdentifier();
224 final Optional<? extends TreeNode> cm = meta.getChild(id);
226 final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
227 if (result.isPresent()) {
228 final TreeNode tn = result.get();
230 data.addChild(tn.getData());
232 meta.removeChild(id);
233 data.removeChild(id);
237 meta.setData(data.build());
242 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
244 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
245 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
246 * heavy lifting of applying the children recursively (either through here or through applyWrite().
248 final NormalizedNode<?, ?> value = modification.getWrittenValue();
250 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
251 @SuppressWarnings({"unchecked", "rawtypes"})
252 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
253 for (final NormalizedNode<?, ?> c : children) {
254 final PathArgument id = c.getIdentifier();
255 modification.modifyChild(id, resolveChildOperation(id), version);
257 return applyTouch(modification, currentMeta, version);
260 private void mergeChildrenIntoModification(final ModifiedNode modification,
261 final Collection<NormalizedNode<?, ?>> children, final Version version) {
262 for (final NormalizedNode<?, ?> c : children) {
263 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
264 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
265 childOp.mergeIntoModifiedNode(childNode, c, version);
270 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
271 final Version version) {
272 @SuppressWarnings({ "unchecked", "rawtypes" })
273 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
275 switch (modification.getOperation()) {
277 // Fresh node, just record a MERGE with a value
278 recursivelyVerifyStructure(value);
279 modification.updateValue(LogicalOperation.MERGE, value);
283 mergeChildrenIntoModification(modification, children, version);
284 // We record empty merge value, since real children merges
285 // are already expanded. This is needed to satisfy non-null for merge
286 // original merge value can not be used since it mean different
287 // order of operation - parent changes are always resolved before
288 // children ones, and having node in TOUCH means children was modified
290 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
293 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
294 // as MERGE, invalidating cached snapshot
295 mergeChildrenIntoModification(modification, children, version);
296 modification.updateOperationType(LogicalOperation.MERGE);
299 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
300 // we are really performing a write. One thing that ruins that are any child modifications. If there
301 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
302 // and then append any child entries.
303 if (!modification.getChildren().isEmpty()) {
304 // Version does not matter here as we'll throw it out
305 final Optional<? extends TreeNode> current = apply(modification, modification.getOriginal(),
307 if (current.isPresent()) {
308 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
309 mergeChildrenIntoModification(modification, children, version);
314 modification.updateValue(LogicalOperation.WRITE, value);
317 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
318 // ModifiedNode and run recursively on it
319 mergeChildrenIntoModification(modification, children, version);
320 modification.updateOperationType(LogicalOperation.WRITE);
323 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
328 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
330 * The user may have issued an empty merge operation. In this case we do not perform
331 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
332 * also means the ModificationType is UNMODIFIED.
334 final Collection<ModifiedNode> children = modification.getChildren();
335 if (!children.isEmpty()) {
336 @SuppressWarnings("rawtypes")
337 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
338 final MutableTreeNode newMeta = currentMeta.mutable();
339 newMeta.setSubtreeVersion(version);
340 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
343 * It is possible that the only modifications under this node were empty merges,
344 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
345 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
346 * of speeding up any users, who can skip processing child nodes.
348 * In order to do that, though, we have to check all child operations are UNMODIFIED.
349 * Let's do precisely that, stopping as soon we find a different result.
351 for (final ModifiedNode child : children) {
352 if (child.getModificationType() != ModificationType.UNMODIFIED) {
353 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
359 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
360 // replace the metadata node.
361 modification.resolveModificationType(ModificationType.UNMODIFIED);
366 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
367 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
368 final TreeNode currentNode;
369 if (!current.isPresent()) {
370 currentNode = defaultTreeNode();
371 if (currentNode == null) {
372 if (!modification.getOriginal().isPresent()) {
373 final YangInstanceIdentifier id = path.toInstanceIdentifier();
374 throw new ModifiedNodeDoesNotExistException(id,
375 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
378 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
379 "Node was deleted by other transaction.");
382 currentNode = current.get();
385 checkChildPreconditions(path, modification, currentNode, version);
389 * Return the default tree node. Default implementation does nothing, but can be overridden to call
390 * {@link #defaultTreeNode(NormalizedNode)}.
392 * @return Default empty tree node, or null if no default is available
394 @Nullable TreeNode defaultTreeNode() {
395 // Defaults to no recovery
399 static final TreeNode defaultTreeNode(final NormalizedNode<?, ?> emptyNode) {
400 return TreeNodeFactory.createTreeNode(emptyNode, FAKE_VERSION);
404 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
405 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
406 if (current.isPresent()) {
407 checkChildPreconditions(path, modification, current.get(), version);
412 * Recursively check child preconditions.
414 * @param path current node path
415 * @param modification current modification
416 * @param current Current data tree node.
418 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
419 final TreeNode current, final Version version) throws DataValidationFailedException {
420 for (final NodeModification childMod : modification.getChildren()) {
421 final PathArgument childId = childMod.getIdentifier();
422 final Optional<? extends TreeNode> childMeta = current.getChild(childId);
426 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
434 public final String toString() {
435 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
438 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
439 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);