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.Verify;
15 import java.util.Collection;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.DistinctNodeContainer;
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.builder.NormalizedNodeContainerBuilder;
24 import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
25 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeConfiguration;
26 import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
28 import org.opendaylight.yangtools.yang.data.tree.api.ModifiedNodeDoesNotExistException;
29 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
30 import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
31 import org.opendaylight.yangtools.yang.data.tree.impl.node.MutableTreeNode;
32 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
33 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 abstract sealed class AbstractNodeContainerModificationStrategy<T extends DataSchemaNode>
37 extends SchemaAwareApplyOperation<T> {
38 abstract static sealed class Invisible<T extends DataSchemaNode>
39 extends AbstractNodeContainerModificationStrategy<T>
40 permits LeafSetModificationStrategy, MapModificationStrategy {
41 private final @NonNull SchemaAwareApplyOperation<T> entryStrategy;
43 Invisible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
44 final SchemaAwareApplyOperation<T> entryStrategy) {
45 super(support, treeConfig);
46 this.entryStrategy = requireNonNull(entryStrategy);
51 return entryStrategy.getSchema();
54 final @NonNull ModificationApplyOperation entryStrategy() {
59 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
60 return super.addToStringAttributes(helper).add("entry", entryStrategy);
64 abstract static sealed class Visible<T extends DataSchemaNode> extends AbstractNodeContainerModificationStrategy<T>
65 permits ChoiceModificationStrategy, DataNodeContainerModificationStrategy {
66 private final @NonNull T schema;
68 Visible(final NormalizedNodeContainerSupport<?, ?> support, final DataTreeConfiguration treeConfig,
70 super(support, treeConfig);
71 this.schema = requireNonNull(schema);
80 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
81 return super.addToStringAttributes(helper).add("schema", schema);
86 * Fake TreeNode version used in
87 * {@link #checkTouchApplicable(ModificationPath, NodeModification, Optional, Version)}
88 * It is okay to use a global constant, as the delegate will ignore it anyway.
90 private static final Version FAKE_VERSION = Version.initial();
92 private final NormalizedNodeContainerSupport<?, ?> support;
93 private final boolean verifyChildrenStructure;
95 AbstractNodeContainerModificationStrategy(final NormalizedNodeContainerSupport<?, ?> support,
96 final DataTreeConfiguration treeConfig) {
97 this.support = requireNonNull(support);
98 verifyChildrenStructure = treeConfig.getTreeType() == TreeType.CONFIGURATION;
102 protected final ChildTrackingPolicy getChildPolicy() {
103 return support.childPolicy;
107 final void verifyValue(final NormalizedNode writtenValue) {
108 final Class<?> nodeClass = support.requiredClass;
109 checkArgument(nodeClass.isInstance(writtenValue), "Node %s is not of type %s", writtenValue, nodeClass);
110 checkArgument(writtenValue instanceof NormalizedNodeContainer);
114 final void verifyValueChildren(final NormalizedNode writtenValue) {
115 final var container = (DistinctNodeContainer<?, ?>) writtenValue;
116 if (verifyChildrenStructure) {
117 for (var child : container.body()) {
118 final var childOp = childByArg(child.name());
119 if (childOp == null) {
120 throw new SchemaValidationFailedException(String.format(
121 "Node %s is not a valid child of %s according to the schema.",
122 child.name(), container.name()));
124 childOp.fullVerifyStructure(child);
127 optionalVerifyValueChildren(container);
129 mandatoryVerifyValueChildren(container);
133 * Perform additional verification on written value's child structure, like presence of mandatory children and
134 * exclusion. The default implementation does nothing and is not invoked for non-CONFIG data trees.
136 * @param writtenValue Effective written value
138 void optionalVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
143 * Perform additional verification on written value's child structure, like presence of mandatory children.
144 * The default implementation does nothing.
146 * @param writtenValue Effective written value
148 void mandatoryVerifyValueChildren(final DistinctNodeContainer<?, ?> writtenValue) {
153 protected final void recursivelyVerifyStructure(final NormalizedNode value) {
154 final var container = (NormalizedNodeContainer<?>) value;
155 for (var child : container.body()) {
156 final var childOp = childByArg(child.name());
157 if (childOp == null) {
158 throw new SchemaValidationFailedException(
159 String.format("Node %s is not a valid child of %s according to the schema.",
160 child.name(), container.name()));
163 childOp.recursivelyVerifyStructure(child);
168 protected TreeNode applyWrite(final ModifiedNode modification, final NormalizedNode newValue,
169 final Optional<? extends TreeNode> currentMeta, final Version version) {
170 final var newValueMeta = TreeNode.of(newValue, version);
171 if (modification.isEmpty()) {
176 * This is where things get interesting. The user has performed a write and then she applied some more
177 * modifications to it. So we need to make sense of that and apply the operations on top of the written value.
179 * We could have done it during the write, but this operation is potentially expensive, so we have left it out
182 * As it turns out, once we materialize the written data, we can share the code path with the subtree change. So
183 * let's create an unsealed TreeNode and run the common parts on it -- which end with the node being sealed.
185 * FIXME: this code needs to be moved out from the prepare() path and into the read() and seal() paths. Merging
186 * of writes needs to be charged to the code which originated this, not to the code which is attempting
187 * to make it visible.
189 final var mutable = newValueMeta.mutable();
190 mutable.setSubtreeVersion(version);
192 final var result = mutateChildren(mutable, support.createBuilder(newValue), version,
193 modification.getChildren());
195 // We are good to go except one detail: this is a single logical write, but
196 // we have a result TreeNode which has been forced to materialized, e.g. it
197 // is larger than it needs to be. Create a new TreeNode to host the data.
198 return TreeNode.of(result.getData(), version);
202 * Applies write/remove diff operation for each modification child in modification subtree.
203 * Operation also sets the Data tree references for each Tree Node (Index Node) in meta (MutableTreeNode) structure.
205 * @param meta MutableTreeNode (IndexTreeNode)
206 * @param data DataBuilder
207 * @param nodeVersion Version of TreeNode
208 * @param modifications modification operations to apply
209 * @return Sealed immutable copy of TreeNode structure with all Data Node references set.
211 @SuppressWarnings({ "rawtypes", "unchecked" })
212 private TreeNode mutateChildren(final MutableTreeNode meta, final NormalizedNodeContainerBuilder data,
213 final Version nodeVersion, final Iterable<ModifiedNode> modifications) {
215 for (final ModifiedNode mod : modifications) {
216 final PathArgument id = mod.getIdentifier();
217 final Optional<? extends TreeNode> cm = meta.findChildByArg(id);
219 final Optional<? extends TreeNode> result = resolveChildOperation(id).apply(mod, cm, nodeVersion);
220 if (result.isPresent()) {
221 final TreeNode tn = result.orElseThrow();
223 data.addChild(tn.getData());
225 meta.removeChild(id);
226 data.removeChild(id);
230 meta.setData(data.build());
235 protected TreeNode applyMerge(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
237 * The node which we are merging exists. We now need to expand any child operations implied by the value. Once
238 * we do that, ModifiedNode children will look like this node were a TOUCH and we will let applyTouch() do the
239 * heavy lifting of applying the children recursively (either through here or through applyWrite().
241 final NormalizedNode value = modification.getWrittenValue();
243 Verify.verify(value instanceof DistinctNodeContainer, "Attempted to merge non-container %s", value);
244 for (var c : ((DistinctNodeContainer<?, ?>) value).body()) {
245 final var id = c.name();
246 modification.modifyChild(id, resolveChildOperation(id), version);
248 return applyTouch(modification, currentMeta, version);
251 private void mergeChildrenIntoModification(final ModifiedNode modification,
252 final Collection<? extends NormalizedNode> children, final Version version) {
253 for (final NormalizedNode c : children) {
254 final ModificationApplyOperation childOp = resolveChildOperation(c.name());
255 final ModifiedNode childNode = modification.modifyChild(c.name(), childOp, version);
256 childOp.mergeIntoModifiedNode(childNode, c, version);
261 final void mergeIntoModifiedNode(final ModifiedNode modification, final NormalizedNode value,
262 final Version version) {
263 final var valueChildren = ((DistinctNodeContainer<?, ?>) value).body();
264 switch (modification.getOperation()) {
266 // Fresh node, just record a MERGE with a value
267 recursivelyVerifyStructure(value);
268 modification.updateValue(LogicalOperation.MERGE, value);
272 mergeChildrenIntoModification(modification, valueChildren, version);
273 // We record empty merge value, since real children merges are already expanded. This is needed to
274 // satisfy non-null for merge original merge value can not be used since it mean different order of
275 // operation - parent changes are always resolved before children ones, and having node in TOUCH means
276 // children was modified before.
277 modification.updateValue(LogicalOperation.MERGE, support.createEmptyValue(value));
280 // Merging into an existing node. Merge data children modifications (maybe recursively) and mark
281 // as MERGE, invalidating cached snapshot
282 mergeChildrenIntoModification(modification, valueChildren, version);
283 modification.updateOperationType(LogicalOperation.MERGE);
286 // Delete performs a data dependency check on existence of the node. Performing a merge on DELETE means
287 // we are really performing a write. One thing that ruins that are any child modifications. If there
288 // are any, we will perform a read() to get the current state of affairs, turn this into into a WRITE
289 // and then append any child entries.
290 if (!modification.isEmpty()) {
291 // Version does not matter here as we'll throw it out
292 final var current = apply(modification, modification.getOriginal(), Version.initial());
293 if (current.isPresent()) {
294 modification.updateValue(LogicalOperation.WRITE, current.orElseThrow().getData());
295 mergeChildrenIntoModification(modification, valueChildren, version);
300 modification.updateValue(LogicalOperation.WRITE, value);
303 // We are augmenting a previous write. We'll just walk value's children, get the corresponding
304 // ModifiedNode and run recursively on it
305 mergeChildrenIntoModification(modification, valueChildren, version);
306 modification.updateOperationType(LogicalOperation.WRITE);
309 throw new IllegalArgumentException("Unsupported operation " + modification.getOperation());
314 protected TreeNode applyTouch(final ModifiedNode modification, final TreeNode currentMeta, final Version version) {
316 * The user may have issued an empty merge operation. In this case we:
317 * - do not perform a data tree mutation
318 * - do not pass GO, and
319 * - do not collect useless garbage.
320 * It also means the ModificationType is UNMODIFIED.
322 if (!modification.isEmpty()) {
323 final var dataBuilder = support.createBuilder(currentMeta.getData());
324 final var newMeta = currentMeta.mutable();
325 newMeta.setSubtreeVersion(version);
326 final var children = modification.getChildren();
327 final var ret = mutateChildren(newMeta, dataBuilder, version, children);
330 * It is possible that the only modifications under this node were empty merges, which were turned into
331 * UNMODIFIED. If that is the case, we can turn this operation into UNMODIFIED, too, potentially cascading
332 * it up to root. This has the benefit of speeding up any users, who can skip processing child nodes.
334 * In order to do that, though, we have to check all child operations are UNMODIFIED.
336 * Let's do precisely that, stopping as soon we find a different result.
338 for (var child : children) {
339 if (child.getModificationType() != ModificationType.UNMODIFIED) {
340 modification.resolveModificationType(ModificationType.SUBTREE_MODIFIED);
346 // The merge operation did not have any children, or all of them turned out to be UNMODIFIED, hence do not
347 // replace the metadata node.
348 modification.resolveModificationType(ModificationType.UNMODIFIED);
353 protected final void checkTouchApplicable(final ModificationPath path, final NodeModification modification,
354 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
355 final TreeNode currentNode;
356 if (current.isEmpty()) {
357 currentNode = defaultTreeNode();
358 if (currentNode == null) {
359 if (modification.original() == null) {
360 final var id = path.toInstanceIdentifier();
361 throw new ModifiedNodeDoesNotExistException(id,
362 "Node " + id + " does not exist. Cannot apply modification to its children.");
365 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(),
366 "Node was deleted by other transaction.");
369 currentNode = current.orElseThrow();
372 checkChildPreconditions(path, modification, currentNode, version);
376 * Return the default tree node. Default implementation does nothing, but can be overridden to call
377 * {@link #defaultTreeNode(NormalizedNode)}.
379 * @return Default empty tree node, or null if no default is available
381 @Nullable TreeNode defaultTreeNode() {
382 // Defaults to no recovery
386 static final TreeNode defaultTreeNode(final NormalizedNode emptyNode) {
387 return TreeNode.of(emptyNode, FAKE_VERSION);
391 protected final void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
392 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
393 if (current.isPresent()) {
394 checkChildPreconditions(path, modification, current.orElseThrow(), version);
399 * Recursively check child preconditions.
401 * @param path current node path
402 * @param modification current modification
403 * @param current Current data tree node.
405 private void checkChildPreconditions(final ModificationPath path, final NodeModification modification,
406 final TreeNode current, final Version version) throws DataValidationFailedException {
407 for (final NodeModification childMod : modification.getChildren()) {
408 final PathArgument childId = childMod.getIdentifier();
409 final Optional<? extends TreeNode> childMeta = current.findChildByArg(childId);
413 resolveChildOperation(childId).checkApplicable(path, childMod, childMeta, version);
421 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
422 return helper.add("support", support).add("verifyChildren", verifyChildrenStructure);