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.DataTreeConfiguration;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.MutableTreeNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNodeFactory;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
32 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
33 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
35 abstract class AbstractNodeContainerModificationStrategy<T extends WithStatus>
36 extends SchemaAwareApplyOperation<T> {
37 abstract static class Invisible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
38 private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
40 Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
41 final SchemaAwareApplyOperation<T> entryStrategy) {
42 super(support, treeConfig);
43 this.entryStrategy = requireNonNull(entryStrategy);
48 return entryStrategy.getSchema();
51 final Optional<ModificationApplyOperation> entryStrategy() {
52 return Optional.of(entryStrategy);
56 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
57 return super.addToStringAttributes(helper).add("entry", entryStrategy);
61 abstract static class Visible<T extends WithStatus> extends AbstractNodeContainerModificationStrategy<T> {
62 private final @NonNull T schema;
64 Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
66 super(support, treeConfig);
67 this.schema = requireNonNull(schema);
76 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
77 return super.addToStringAttributes(helper).add("schema", schema);
81 private final NormalizedNodeContainerSupport<?, ?> support;
82 private final boolean verifyChildrenStructure;
84 AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
85 final DataTreeConfiguration treeConfig) {
86 this.support = requireNonNull(support);
87 this.verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
91 protected final ChildTrackingPolicy getChildPolicy() {
92 return support.childPolicy;
96 final void verifyValue(final NormalizedNode<?, ?> writtenValue) {
97 final Class<?> nodeClass = support.requiredClass;
98 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
99 checkArgument(writtenValue instanceof NormalizedNodeContainer);
103 final void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
104 if (verifyChildrenStructure) {
105 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) writtenValue;
106 for (final Object child : container.getValue()) {
107 checkArgument(child instanceof NormalizedNode);
108 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
109 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
110 if (childOp.isPresent()) {
111 childOp.get().fullVerifyStructure(castedChild);
113 throw new SchemaValidationFailedException(String.format(
114 "Node %s is not a valid child of %s according to the schema.",
115 castedChild.getIdentifier(), container.getIdentifier()));
119 optionalVerifyValueChildren(writtenValue);
121 mandatoryVerifyValueChildren(writtenValue);
125 * Perform additional verification on written value's child structure, like presence of mandatory children and
126 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
128 * @param writtenValue Effective written value
130 void optionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
135 * Perform additional verification on written value's child structure, like presence of mandatory children.
136 * The default implementation does nothing.
138 * @param writtenValue Effective written value
140 void mandatoryVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
145 protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
146 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
147 for (final Object child : container.getValue()) {
148 checkArgument(child instanceof NormalizedNode);
149 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
150 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
151 if (!childOp.isPresent()) {
152 throw new SchemaValidationFailedException(
153 String.format("Node %s is not a valid child of %s according to the schema.",
154 castedChild.getIdentifier(), container.getIdentifier()));
157 childOp.get().recursivelyVerifyStructure(castedChild);
162 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
163 final Optional<TreeNode> currentMeta, final Version version) {
164 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
166 if (modification.getChildren().isEmpty()) {
171 * This is where things get interesting. The user has performed a write and
172 * then she applied some more modifications to it. So we need to make sense
173 * of that an apply the operations on top of the written value. We could have
174 * done it during the write, but this operation is potentially expensive, so
175 * we have left it out of the fast path.
177 * As it turns out, once we materialize the written data, we can share the
178 * code path with the subtree change. So let's create an unsealed TreeNode
179 * and run the common parts on it -- which end with the node being sealed.
181 * FIXME: this code needs to be moved out from the prepare() path and into
182 * the read() and seal() paths. Merging of writes needs to be charged
183 * to the code which originated this, not to the code which is
184 * attempting to make it visible.
186 final MutableTreeNode mutable = newValueMeta.mutable();
187 mutable.setSubtreeVersion(version);
189 @SuppressWarnings("rawtypes")
190 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
191 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
193 // We are good to go except one detail: this is a single logical write, but
194 // we have a result TreeNode which has been forced to materialized, e.g. it
195 // is larger than it needs to be. Create a new TreeNode to host the data.
196 return TreeNodeFactory.createTreeNode(result.getData(), version);
200 * Applies write/remove diff operation for each modification child in modification subtree.
201 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
203 * @param meta MutableTreeNode (IndexTreeNode)
204 * @param data DataBuilder
205 * @param nodeVersion Version of TreeNode
206 * @param modifications modification operations to apply
207 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
209 @SuppressWarnings({ "rawtypes", "unchecked" })
210 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
211 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
213 for (final ModifiedNode mod : modifications) {
214 final PathArgument id = mod.getIdentifier();
215 final Optional<TreeNode> cm = meta.getChild(id);
217 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
218 if (result.isPresent()) {
219 final TreeNode tn = result.get();
221 data.addChild(tn.getData());
223 meta.removeChild(id);
224 data.removeChild(id);
228 meta.setData(data.build());
233 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
235 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
236 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
237 * heavy lifting of applying the children recursively (either through here or through applyWrite().
239 final NormalizedNode<?, ?> value = modification.getWrittenValue();
241 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
242 @SuppressWarnings({"unchecked", "rawtypes"})
243 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
244 for (final NormalizedNode<?, ?> c : children) {
245 final PathArgument id = c.getIdentifier();
246 modification.modifyChild(id, resolveChildOperation(id), version);
248 return applyTouch(modification, currentMeta, version);
251 private void mergeChildrenIntoModification(final ModifiedNode modification,
252 final Collection<NormalizedNode<?, ?>> children, final Version version) {
253 for (final NormalizedNode<?, ?> c : children) {
254 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
255 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
256 childOp.mergeIntoModifiedNode(childNode, c, version);
261 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
262 final Version version) {
263 @SuppressWarnings({ "unchecked", "rawtypes" })
264 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
266 switch (modification.getOperation()) {
268 // Fresh node, just record a MERGE with a value
269 recursivelyVerifyStructure(value);
270 modification.updateValue(LogicalOperation.MERGE, value);
274 mergeChildrenIntoModification(modification, children, version);
275 // We record empty merge value, since real children merges
276 // are already expanded. This is needed to satisfy non-null for merge
277 // original merge value can not be used since it mean different
278 // order of operation - parent changes are always resolved before
279 // children ones, and having node in TOUCH means children was modified
281 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
284 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
285 // as MERGE, invalidating cached snapshot
286 mergeChildrenIntoModification(modification, children, version);
287 modification.updateOperationType(LogicalOperation.MERGE);
290 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
291 // we are really performing a write. One thing that ruins that are any child modifications. If there
292 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
293 // and then append any child entries.
294 if (!modification.getChildren().isEmpty()) {
295 // Version does not matter here as we'll throw it out
296 final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
298 if (current.isPresent()) {
299 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
300 mergeChildrenIntoModification(modification, children, version);
305 modification.updateValue(LogicalOperation.WRITE, value);
308 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
309 // ModifiedNode and run recursively on it
310 mergeChildrenIntoModification(modification, children, version);
311 modification.updateOperationType(LogicalOperation.WRITE);
314 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
319 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
321 * The user may have issued an empty merge operation. In this case we do not perform
322 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
323 * also means the ModificationType is UNMODIFIED.
325 final Collection<ModifiedNode> children = modification.getChildren();
326 if (!children.isEmpty()) {
327 @SuppressWarnings("rawtypes")
328 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
329 final MutableTreeNode newMeta = currentMeta.mutable();
330 newMeta.setSubtreeVersion(version);
331 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
334 * It is possible that the only modifications under this node were empty merges,
335 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
336 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
337 * of speeding up any users, who can skip processing child nodes.
339 * In order to do that, though, we have to check all child operations are UNMODIFIED.
340 * Let's do precisely that, stopping as soon we find a different result.
342 for (final ModifiedNode child : children) {
343 if (child.getModificationType() != ModificationType.UNMODIFIED) {
344 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
350 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
351 // replace the metadata node.
352 modification.resolveModificationType(ModificationType.UNMODIFIED);
357 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
358 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
359 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
360 final YangInstanceIdentifier id = path.toInstanceIdentifier();
361 throw new ModifiedNodeDoesNotExistException(id,
362 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
365 checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
366 checkChildPreconditions(path, modification, current.get(), version);
370 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
371 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
372 if (current.isPresent()) {
373 checkChildPreconditions(path, modification, current.get(), version);
378 * Recursively check child preconditions.
380 * @param path current node path
381 * @param modification current modification
382 * @param current Current data tree node.
384 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
385 final TreeNode current, final Version version) throws DataValidationFailedException {
386 for (final NodeModification childMod : modification.getChildren()) {
387 final PathArgument childId = childMod.getIdentifier();
388 final Optional<TreeNode> childMeta = current.getChild(childId);
392 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
400 public final String toString() {
401 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
404 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
405 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);