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 additionalVerifyValueChildren(writtenValue);
124 * Perform additional verification on written value's child structure, like presence of mandatory children and
125 * exclusion. The default implementation does nothing.
127 * @param writtenValue Effective written value
129 void additionalVerifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
134 protected final void recursivelyVerifyStructure(final NormalizedNode<?, ?> value) {
135 final NormalizedNodeContainer<?, ?, ?> container = (NormalizedNodeContainer<?, ?, ?>) value;
136 for (final Object child : container.getValue()) {
137 checkArgument(child instanceof NormalizedNode);
138 final NormalizedNode<?, ?> castedChild = (NormalizedNode<?, ?>) child;
139 final Optional<ModificationApplyOperation> childOp = getChild(castedChild.getIdentifier());
140 if (!childOp.isPresent()) {
141 throw new SchemaValidationFailedException(
142 String.format("Node %s is not a valid child of %s according to the schema.",
143 castedChild.getIdentifier(), container.getIdentifier()));
146 childOp.get().recursivelyVerifyStructure(castedChild);
151 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode<?, ?> newValue,
152 final Optional<TreeNode> currentMeta, final Version version) {
153 final TreeNode newValueMeta = TreeNodeFactory.createTreeNode(newValue, version);
155 if (modification.getChildren().isEmpty()) {
160 * This is where things get interesting. The user has performed a write and
161 * then she applied some more modifications to it. So we need to make sense
162 * of that an apply the operations on top of the written value. We could have
163 * done it during the write, but this operation is potentially expensive, so
164 * we have left it out of the fast path.
166 * As it turns out, once we materialize the written data, we can share the
167 * code path with the subtree change. So let's create an unsealed TreeNode
168 * and run the common parts on it -- which end with the node being sealed.
170 * FIXME: this code needs to be moved out from the prepare() path and into
171 * the read() and seal() paths. Merging of writes needs to be charged
172 * to the code which originated this, not to the code which is
173 * attempting to make it visible.
175 final MutableTreeNode mutable = newValueMeta.mutable();
176 mutable.setSubtreeVersion(version);
178 @SuppressWarnings("rawtypes")
179 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(newValue);
180 final TreeNode result = mutateChildren(mutable, dataBuilder, version, modification.getChildren());
182 // We are good to go except one detail: this is a single logical write, but
183 // we have a result TreeNode which has been forced to materialized, e.g. it
184 // is larger than it needs to be. Create a new TreeNode to host the data.
185 return TreeNodeFactory.createTreeNode(result.getData(), version);
189 * Applies write/remove diff operation for each modification child in modification subtree.
190 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
192 * @param meta MutableTreeNode (IndexTreeNode)
193 * @param data DataBuilder
194 * @param nodeVersion Version of TreeNode
195 * @param modifications modification operations to apply
196 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
198 @SuppressWarnings({ "rawtypes", "unchecked" })
199 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
200 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
202 for (final ModifiedNode mod : modifications) {
203 final PathArgument id = mod.getIdentifier();
204 final Optional<TreeNode> cm = meta.getChild(id);
206 final Optional<TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
207 if (result.isPresent()) {
208 final TreeNode tn = result.get();
210 data.addChild(tn.getData());
212 meta.removeChild(id);
213 data.removeChild(id);
217 meta.setData(data.build());
222 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
224 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
225 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
226 * heavy lifting of applying the children recursively (either through here or through applyWrite().
228 final NormalizedNode<?, ?> value = modification.getWrittenValue();
230 Verify.verify(value instanceof NormalizedNodeContainer, "Attempted to merge non-container %s", value);
231 @SuppressWarnings({"unchecked", "rawtypes"})
232 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer) value).getValue();
233 for (final NormalizedNode<?, ?> c : children) {
234 final PathArgument id = c.getIdentifier();
235 modification.modifyChild(id, resolveChildOperation(id), version);
237 return applyTouch(modification, currentMeta, version);
240 private void mergeChildrenIntoModification(final ModifiedNode modification,
241 final Collection<NormalizedNode<?, ?>> children, final Version version) {
242 for (final NormalizedNode<?, ?> c : children) {
243 final ModificationApplyOperation childOp = resolveChildOperation(c.getIdentifier());
244 final ModifiedNode childNode = modification.modifyChild(c.getIdentifier(), childOp, version);
245 childOp.mergeIntoModifiedNode(childNode, c, version);
250 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode<?, ?> value,
251 final Version version) {
252 @SuppressWarnings({ "unchecked", "rawtypes" })
253 final Collection<NormalizedNode<?, ?>> children = ((NormalizedNodeContainer)value).getValue();
255 switch (modification.getOperation()) {
257 // Fresh node, just record a MERGE with a value
258 recursivelyVerifyStructure(value);
259 modification.updateValue(LogicalOperation.MERGE, value);
263 mergeChildrenIntoModification(modification, children, version);
264 // We record empty merge value, since real children merges
265 // are already expanded. This is needed to satisfy non-null for merge
266 // original merge value can not be used since it mean different
267 // order of operation - parent changes are always resolved before
268 // children ones, and having node in TOUCH means children was modified
270 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
273 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
274 // as MERGE, invalidating cached snapshot
275 mergeChildrenIntoModification(modification, children, version);
276 modification.updateOperationType(LogicalOperation.MERGE);
279 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
280 // we are really performing a write. One thing that ruins that are any child modifications. If there
281 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
282 // and then append any child entries.
283 if (!modification.getChildren().isEmpty()) {
284 // Version does not matter here as we'll throw it out
285 final Optional<TreeNode> current = apply(modification, modification.getOriginal(),
287 if (current.isPresent()) {
288 modification.updateValue(LogicalOperation.WRITE, current.get().getData());
289 mergeChildrenIntoModification(modification, children, version);
294 modification.updateValue(LogicalOperation.WRITE, value);
297 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
298 // ModifiedNode and run recursively on it
299 mergeChildrenIntoModification(modification, children, version);
300 modification.updateOperationType(LogicalOperation.WRITE);
303 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
308 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
310 * The user may have issued an empty merge operation. In this case we do not perform
311 * a data tree mutation, do not pass GO, and do not collect useless garbage. It
312 * also means the ModificationType is UNMODIFIED.
314 final Collection<ModifiedNode> children = modification.getChildren();
315 if (!children.isEmpty()) {
316 @SuppressWarnings("rawtypes")
317 final NormalizedNodeContainerBuilder dataBuilder = support.createBuilder(currentMeta.getData());
318 final MutableTreeNode newMeta = currentMeta.mutable();
319 newMeta.setSubtreeVersion(version);
320 final TreeNode ret = mutateChildren(newMeta, dataBuilder, version, children);
323 * It is possible that the only modifications under this node were empty merges,
324 * which were turned into UNMODIFIED. If that is the case, we can turn this operation
325 * into UNMODIFIED, too, potentially cascading it up to root. This has the benefit
326 * of speeding up any users, who can skip processing child nodes.
328 * In order to do that, though, we have to check all child operations are UNMODIFIED.
329 * Let's do precisely that, stopping as soon we find a different result.
331 for (final ModifiedNode child : children) {
332 if (child.getModificationType() != ModificationType.UNMODIFIED) {
333 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
339 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
340 // replace the metadata node.
341 modification.resolveModificationType(ModificationType.UNMODIFIED);
346 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
347 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
348 if (!modification.getOriginal().isPresent() && !current.isPresent()) {
349 final YangInstanceIdentifier id = path.toInstanceIdentifier();
350 throw new ModifiedNodeDoesNotExistException(id,
351 String.format("Node %s does not exist. Cannot apply modification to its children.", id));
354 checkConflicting(path, current.isPresent(), "Node was deleted by other transaction.");
355 checkChildPreconditions(path, modification, current.get(), version);
359 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
360 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
361 if (current.isPresent()) {
362 checkChildPreconditions(path, modification, current.get(), version);
367 * Recursively check child preconditions.
369 * @param path current node path
370 * @param modification current modification
371 * @param current Current data tree node.
373 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
374 final TreeNode current, final Version version) throws DataValidationFailedException {
375 for (final NodeModification childMod : modification.getChildren()) {
376 final PathArgument childId = childMod.getIdentifier();
377 final Optional<TreeNode> childMeta = current.getChild(childId);
381 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
389 public final String toString() {
390 return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
393 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
394 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);