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 com.google.common.base.Verify.verifyNotNull;
13 import java.util.List;
14 import java.util.Optional;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
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.TreeType;
27 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
28 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
29 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
35 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
43 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
45 static ModificationApplyOperation from(final DataSchemaNode schemaNode,
46 final DataTreeConfiguration treeConfig) throws ExcludedDataSchemaNodeException {
47 if (!belongsToTree(treeConfig.getTreeType(), schemaNode)) {
48 throw new ExcludedDataSchemaNodeException(schemaNode + " does not belong to configuration tree");
50 if (schemaNode instanceof ContainerSchemaNode container) {
51 return ContainerModificationStrategy.of(container, treeConfig);
52 } else if (schemaNode instanceof ListSchemaNode list) {
53 return fromListSchemaNode(list, treeConfig);
54 } else if (schemaNode instanceof ChoiceSchemaNode choice) {
55 return new ChoiceModificationStrategy(choice, treeConfig);
56 } else if (schemaNode instanceof LeafListSchemaNode leafList) {
57 return MinMaxElementsValidation.from(new LeafSetModificationStrategy(leafList, treeConfig));
58 } else if (schemaNode instanceof LeafSchemaNode leaf) {
59 return new ValueNodeModificationStrategy<>(LeafNode.class, leaf);
60 } else if (schemaNode instanceof AnydataSchemaNode anydata) {
61 return new ValueNodeModificationStrategy<>(AnydataNode.class, anydata);
62 } else if (schemaNode instanceof AnyxmlSchemaNode anyxml) {
63 return new ValueNodeModificationStrategy<>(AnyxmlNode.class, anyxml);
64 } else if (schemaNode instanceof SchemaContext context) {
65 return new StructuralContainerModificationStrategy(context, treeConfig);
67 throw new IllegalStateException("Unsupported schema " + schemaNode);
71 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
72 throws ConflictingModificationAppliedException {
74 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
78 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
79 final DataTreeConfiguration treeConfig) {
80 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
81 final SchemaAwareApplyOperation<ListSchemaNode> op;
82 if (keyDefinition == null || keyDefinition.isEmpty()) {
83 op = new ListModificationStrategy(schemaNode, treeConfig);
85 op = MapModificationStrategy.of(schemaNode, treeConfig);
88 return UniqueValidation.of(schemaNode, treeConfig, MinMaxElementsValidation.from(op));
91 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
92 final TreeNode current) throws ConflictingModificationAppliedException {
93 checkConflicting(path, original.getVersion().equals(current.getVersion()),
94 "Node was replaced by other transaction.");
95 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
96 "Node children was modified by other transaction");
99 protected final @NonNull ModificationApplyOperation resolveChildOperation(final PathArgument child) {
100 final ModificationApplyOperation potential = childByArg(child);
101 checkArgument(potential != null, "Operation for child %s is not defined.", child);
106 final void checkApplicable(final ModificationPath path, final NodeModification modification,
107 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
108 switch (modification.getOperation()) {
109 case DELETE -> checkDeleteApplicable(modification, current);
110 case TOUCH -> checkTouchApplicable(path, modification, current, version);
111 case WRITE -> checkWriteApplicable(path, modification, current, version);
112 case MERGE -> checkMergeApplicable(path, modification, current, version);
116 default -> throw new UnsupportedOperationException(
117 "Suplied modification type " + modification.getOperation() + " is not supported.");
122 final void quickVerifyStructure(final NormalizedNode writtenValue) {
123 verifyValue(writtenValue);
127 final void fullVerifyStructure(final NormalizedNode writtenValue) {
128 verifyValue(writtenValue);
129 verifyValueChildren(writtenValue);
133 * Verify the a written value, without performing deeper tree validation.
135 * @param writtenValue Written value
137 abstract void verifyValue(NormalizedNode writtenValue);
140 * Verify the children implied by a written value after the value itself has been verified by
141 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
143 * @param writtenValue Written value
145 void verifyValueChildren(final NormalizedNode writtenValue) {
149 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
150 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
151 final Optional<? extends TreeNode> original = modification.getOriginal();
152 if (original.isPresent() && current.isPresent()) {
154 * We need to do conflict detection only and only if the value of leaf changed
155 * before two transactions. If value of leaf is unchanged between two transactions
156 * it should not cause transaction to fail, since result of this merge
157 * leads to same data.
159 final TreeNode orig = original.orElseThrow();
160 final TreeNode cur = current.orElseThrow();
161 if (!orig.getData().equals(cur.getData())) {
162 checkNotConflicting(path, orig, cur);
168 * Checks if write operation can be applied to current TreeNode.
169 * The operation checks if original tree node to which the modification is going to be applied exists and if
170 * current node in TreeNode structure exists.
172 * @param path Path from current node in TreeNode
173 * @param modification modification to apply
174 * @param current current node in TreeNode for modification to apply
175 * @throws DataValidationFailedException when a data dependency conflict is detected
177 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
178 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
179 final Optional<? extends TreeNode> original = modification.getOriginal();
180 if (original.isPresent() && current.isPresent()) {
181 checkNotConflicting(path, original.orElseThrow(), current.orElseThrow());
183 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
184 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
188 private static void checkDeleteApplicable(final NodeModification modification,
189 final Optional<? extends TreeNode> current) {
190 // Delete is always applicable, we do not expose it to subclasses
191 if (!current.isPresent()) {
192 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
197 Optional<? extends TreeNode> apply(final ModifiedNode modification, final Optional<? extends TreeNode> currentMeta,
198 final Version version) {
199 return switch (modification.getOperation()) {
201 // Deletion of a non-existing node is a no-op, report it as such
202 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
203 : ModificationType.UNMODIFIED);
204 yield modification.setSnapshot(Optional.empty());
207 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
208 yield modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.orElseThrow(),
212 final TreeNode result;
214 if (!currentMeta.isPresent()) {
215 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
216 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
217 // to run that validation here.
218 modification.resolveModificationType(ModificationType.WRITE);
219 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
220 fullVerifyStructure(result.getData());
222 result = applyMerge(modification, currentMeta.orElseThrow(), version);
225 yield modification.setSnapshot(Optional.of(result));
228 modification.resolveModificationType(ModificationType.WRITE);
229 yield modification.setSnapshot(Optional.of(applyWrite(modification,
230 verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
233 modification.resolveModificationType(ModificationType.UNMODIFIED);
240 * Apply a merge operation. Since the result of merge differs based on the data type
241 * being modified, implementations of this method are responsible for calling
242 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
244 * @param modification Modified node
245 * @param currentMeta Store Metadata Node on which NodeModification should be applied
246 * @param version New subtree version of parent node
247 * @return A sealed TreeNode representing applied operation.
249 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
251 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode newValue,
252 Optional<? extends TreeNode> currentMeta, Version version);
255 * Apply a nested operation. Since there may not actually be a nested operation
256 * to be applied, implementations of this method are responsible for calling
257 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
259 * @param modification Modified node
260 * @param currentMeta Store Metadata Node on which NodeModification should be applied
261 * @param version New subtree version of parent node
262 * @return A sealed TreeNode representing applied operation.
264 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
267 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
269 * @param path Path to current node
270 * @param modification Node modification which should be applied.
271 * @param current Current state of data tree
272 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
273 * @throws org.opendaylight.yangtools.yang.data.tree.api.IncorrectDataStructureException If subtree
274 * modification is not applicable (e.g. leaf node).
276 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
277 Optional<? extends TreeNode> current, Version version) throws DataValidationFailedException;
280 * Return the {@link WithStatus}-subclass schema associated with this operation.
281 * @return A model node
283 abstract @NonNull T getSchema();
286 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
287 * nodes in configuration tree are marked as such.
289 * @param treeType Tree Type
290 * @param node Schema node
291 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
293 static final boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
294 return treeType == TreeType.OPERATIONAL || node.effectiveConfig().orElse(Boolean.TRUE);