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.tree.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.VerifyException;
15 import java.util.Collection;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
21 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeContainerBuilder;
22 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
23 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
24 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
25 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
26 import org.opendaylight.yangtools.yang.data.tree.api.ModifiedNodeDoesNotExistException;
27 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
28 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
29 import org.opendaylight.yangtools.yang.data.tree.impl.node.MutableTreeNode;
30 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
31 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 abstract sealed class AbstractNodeContainerModificationStrategy<T extends DataSchemaNode>
35 extends SchemaAwareApplyOperation<T> {
36 abstract static sealed class Invisible<T extends DataSchemaNode>
37 extends AbstractNodeContainerModificationStrategy<T>
38 permits LeafSetModificationStrategy, MapModificationStrategy {
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 @NonNull ModificationApplyOperation entryStrategy() {
57 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
58 return super.addToStringAttributes(helper).add("entry", entryStrategy);
62 abstract static sealed class Visible<T extends DataSchemaNode> extends AbstractNodeContainerModificationStrategy<T>
63 permits ChoiceModificationStrategy, DataNodeContainerModificationStrategy {
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, TreeNode, 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 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 final var container = (DistinctNodeContainer<?, ?>) writtenValue;
114 if (verifyChildrenStructure) {
115 for (var child : container.body()) {
116 final var childOp = childByArg(child.name());
117 if (childOp == null) {
118 throw new SchemaValidationFailedException(String.format(
119 "Node %s is not a valid child of %s according to the schema.",
120 child.name(), container.name()));
122 childOp.fullVerifyStructure(child);
125 optionalVerifyValueChildren(container);
127 mandatoryVerifyValueChildren(container);
131 * Perform additional verification on written value's child structure, like presence of mandatory children and
132 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
134 * @param writtenValue Effective written value
136 void optionalVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
141 * Perform additional verification on written value's child structure, like presence of mandatory children.
142 * The default implementation does nothing.
144 * @param writtenValue Effective written value
146 void mandatoryVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
151 protected final void recursivelyVerifyStructure(final NormalizedNode value) {
152 final var container = (NormalizedNodeContainer<?>) value;
153 for (var child : container.body()) {
154 final var childOp = childByArg(child.name());
155 if (childOp == null) {
156 throw new SchemaValidationFailedException(
157 String.format("Node %s is not a valid child of %s according to the schema.",
158 child.name(), container.name()));
161 childOp.recursivelyVerifyStructure(child);
166 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode newValue,
167 final TreeNode currentMeta, final Version version) {
168 final var newValueMeta = TreeNode.of(newValue, version);
169 if (modification.isEmpty()) {
174 * This is where things get interesting. The user has performed a write and then she applied some more
175 * modifications to it. So we need to make sense of that and apply the operations on top of the written value.
177 * We could have done it during the write, but this operation is potentially expensive, so we have left it out
180 * As it turns out, once we materialize the written data, we can share the code path with the subtree change. So
181 * let's create an unsealed TreeNode and run the common parts on it -- which end with the node being sealed.
183 * FIXME: this code needs to be moved out from the prepare() path and into the read() and seal() paths. Merging
184 * of writes needs to be charged to the code which originated this, not to the code which is attempting
185 * to make it visible.
187 final var mutable = newValueMeta.toMutable();
188 mutable.setSubtreeVersion(version);
190 final var result = mutateChildren(mutable, support.createBuilder(newValue), version,
191 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 TreeNode.of(result.data(), 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) {
212 for (var mod : modifications) {
213 final var id = mod.getIdentifier();
214 final var result = resolveChildOperation(id).apply(mod, meta.childByArg(id), nodeVersion);
215 if (result != null) {
216 meta.putChild(result);
217 data.addChild(result.data());
219 meta.removeChild(id);
220 data.removeChild(id);
224 meta.setData(data.build());
229 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
231 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
232 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
233 * heavy lifting of applying the children recursively (either through here or through applyWrite().
235 final var value = modification.getWrittenValue();
236 if (!(value instanceof DistinctNodeContainer<?, ?> containerValue)) {
237 throw new VerifyException("Attempted to merge non-container " + value);
240 for (var c : containerValue.body()) {
241 final var id = c.name();
242 modification.modifyChild(id, resolveChildOperation(id), version);
244 return applyTouch(modification, currentMeta, version);
247 private void mergeChildrenIntoModification(final ModifiedNode modification,
248 final Collection<? extends NormalizedNode> children, final Version version) {
249 for (final NormalizedNode c : children) {
250 final ModificationApplyOperation childOp = resolveChildOperation(c.name());
251 final ModifiedNode childNode = modification.modifyChild(c.name(), childOp, version);
252 childOp.mergeIntoModifiedNode(childNode, c, version);
257 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode value,
258 final Version version) {
259 final var valueChildren = ((DistinctNodeContainer<?, ?>) value).body();
260 switch (modification.getOperation()) {
262 // Fresh node, just record a MERGE with a value
263 recursivelyVerifyStructure(value);
264 modification.updateValue(LogicalOperation.MERGE, value);
268 mergeChildrenIntoModification(modification, valueChildren, version);
269 // We record empty merge value, since real children merges are already expanded. This is needed to
270 // satisfy non-null for merge original merge value can not be used since it mean different order of
271 // operation - parent changes are always resolved before children ones, and having node in TOUCH means
272 // children was modified before.
273 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
276 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
277 // as MERGE, invalidating cached snapshot
278 mergeChildrenIntoModification(modification, valueChildren, version);
279 modification.updateOperationType(LogicalOperation.MERGE);
282 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
283 // we are really performing a write. One thing that ruins that are any child modifications. If there
284 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
285 // and then append any child entries.
286 if (!modification.isEmpty()) {
287 // Version does not matter here as we'll throw it out
288 final var current = apply(modification, modification.original(), Version.initial());
289 if (current != null) {
290 modification.updateValue(LogicalOperation.WRITE, current.data());
291 mergeChildrenIntoModification(modification, valueChildren, version);
296 modification.updateValue(LogicalOperation.WRITE, value);
299 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
300 // ModifiedNode and run recursively on it
301 mergeChildrenIntoModification(modification, valueChildren, version);
302 modification.updateOperationType(LogicalOperation.WRITE);
305 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
310 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
312 * The user may have issued an empty merge operation. In this case we:
313 * - do not perform a data tree mutation
314 * - do not pass GO, and
315 * - do not collect useless garbage.
316 * It also means the ModificationType is UNMODIFIED.
318 if (!modification.isEmpty()) {
319 final var dataBuilder = support.createBuilder(currentMeta.data());
320 final var newMeta = currentMeta.toMutable();
321 newMeta.setSubtreeVersion(version);
322 final var children = modification.getChildren();
323 final var ret = mutateChildren(newMeta, dataBuilder, version, children);
326 * It is possible that the only modifications under this node were empty merges, which were turned into
327 * UNMODIFIED. If that is the case, we can turn this operation into UNMODIFIED, too, potentially cascading
328 * it up to root. This has the benefit of speeding up any users, who can skip processing child nodes.
330 * In order to do that, though, we have to check all child operations are UNMODIFIED.
332 * Let's do precisely that, stopping as soon we find a different result.
334 for (var child : children) {
335 if (child.getModificationType() != ModificationType.UNMODIFIED) {
336 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
342 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
343 // replace the metadata node.
344 modification.resolveModificationType(ModificationType.UNMODIFIED);
349 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
350 final TreeNode currentMeta, final Version version) throws DataValidationFailedException {
351 final TreeNode currentNode;
352 if (currentMeta == null) {
353 currentNode = defaultTreeNode();
354 if (currentNode == null) {
355 if (modification.original() == null) {
356 final var id = path.toInstanceIdentifier();
357 throw new ModifiedNodeDoesNotExistException(id,
358 "Node " + id + " does not exist. Cannot apply modification to its children.");
361 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
362 "Node was deleted by other transaction.");
365 currentNode = currentMeta;
368 checkChildPreconditions(path, modification, currentNode, version);
372 * Return the default tree node. Default implementation does nothing, but can be overridden to call
373 * {@link #defaultTreeNode(NormalizedNode)}.
375 * @return Default empty tree node, or null if no default is available
377 @Nullable TreeNode defaultTreeNode() {
378 // Defaults to no recovery
382 static final TreeNode defaultTreeNode(final NormalizedNode emptyNode) {
383 return TreeNode.of(emptyNode, FAKE_VERSION);
387 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
388 final TreeNode currentMeta, final Version version) throws DataValidationFailedException {
389 if (currentMeta != null) {
390 checkChildPreconditions(path, modification, currentMeta, version);
395 * Recursively check child preconditions.
397 * @param path current node path
398 * @param modification current modification
399 * @param currentMeta Current data tree node.
401 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
402 final @NonNull TreeNode currentMeta, final Version version) throws DataValidationFailedException {
403 for (var childMod : modification.getChildren()) {
404 final var childId = childMod.getIdentifier();
405 final var childMeta = currentMeta.childByArg(childId);
409 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
417 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
418 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);