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 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.AugmentationIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.AnydataNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
28 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
30 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
47 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
49 static ModificationApplyOperation from(final DataSchemaNode schemaNode,
50 final DataTreeConfiguration treeConfig) throws ExcludedDataSchemaNodeException {
51 if (!belongsToTree(treeConfig.getTreeType(), schemaNode)) {
52 throw new ExcludedDataSchemaNodeException(schemaNode + " does not belong to configuration tree");
54 if (schemaNode instanceof ContainerSchemaNode) {
55 return ContainerModificationStrategy.of((ContainerSchemaNode) schemaNode, treeConfig);
56 } else if (schemaNode instanceof ListSchemaNode) {
57 return fromListSchemaNode((ListSchemaNode) schemaNode, treeConfig);
58 } else if (schemaNode instanceof ChoiceSchemaNode) {
59 return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode, treeConfig);
60 } else if (schemaNode instanceof LeafListSchemaNode) {
61 return MinMaxElementsValidation.from(new LeafSetModificationStrategy((LeafListSchemaNode) schemaNode,
63 } else if (schemaNode instanceof LeafSchemaNode) {
64 return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
65 } else if (schemaNode instanceof AnydataSchemaNode) {
66 return new ValueNodeModificationStrategy<>(AnydataNode.class, (AnydataSchemaNode) schemaNode);
67 } else if (schemaNode instanceof AnyxmlSchemaNode) {
68 return new ValueNodeModificationStrategy<>(AnyxmlNode.class, (AnyxmlSchemaNode) schemaNode);
69 } else if (schemaNode instanceof SchemaContext) {
70 return new StructuralContainerModificationStrategy((SchemaContext) schemaNode, treeConfig);
72 throw new IllegalStateException("Unsupported schema " + schemaNode);
76 static AugmentationModificationStrategy from(final DataNodeContainer resolvedTree,
77 final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
78 final DataTreeConfiguration treeConfig) {
79 for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
80 for (final DataSchemaNode child : potential.getChildNodes()) {
81 if (identifier.getPossibleChildNames().contains(child.getQName())) {
82 return new AugmentationModificationStrategy(potential, resolvedTree, treeConfig);
90 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
91 throws ConflictingModificationAppliedException {
93 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
97 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
98 final DataTreeConfiguration treeConfig) {
99 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
100 final SchemaAwareApplyOperation<ListSchemaNode> op;
101 if (keyDefinition == null || keyDefinition.isEmpty()) {
102 op = new ListModificationStrategy(schemaNode, treeConfig);
104 op = MapModificationStrategy.of(schemaNode, treeConfig);
107 return UniqueValidation.of(schemaNode, treeConfig, MinMaxElementsValidation.from(op));
110 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
111 final TreeNode current) throws ConflictingModificationAppliedException {
112 checkConflicting(path, original.getVersion().equals(current.getVersion()),
113 "Node was replaced by other transaction.");
114 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
115 "Node children was modified by other transaction");
118 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
119 final Optional<ModificationApplyOperation> potential = getChild(child);
120 checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
121 return potential.get();
125 final void checkApplicable(final ModificationPath path, final NodeModification modification,
126 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
127 switch (modification.getOperation()) {
129 checkDeleteApplicable(modification, current);
132 checkTouchApplicable(path, modification, current, version);
135 checkWriteApplicable(path, modification, current, version);
138 checkMergeApplicable(path, modification, current, version);
143 throw new UnsupportedOperationException(
144 "Suplied modification type " + modification.getOperation() + " is not supported.");
149 final void quickVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
150 verifyValue(writtenValue);
154 final void fullVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
155 verifyValue(writtenValue);
156 verifyValueChildren(writtenValue);
160 * Verify the a written value, without performing deeper tree validation.
162 * @param writtenValue Written value
164 abstract void verifyValue(NormalizedNode<?, ?> writtenValue);
167 * Verify the children implied by a written value after the value itself has been verified by
168 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
170 * @param writtenValue Written value
172 void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
176 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
177 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
178 final Optional<? extends TreeNode> original = modification.getOriginal();
179 if (original.isPresent() && current.isPresent()) {
181 * We need to do conflict detection only and only if the value of leaf changed
182 * before two transactions. If value of leaf is unchanged between two transactions
183 * it should not cause transaction to fail, since result of this merge
184 * leads to same data.
186 final TreeNode orig = original.get();
187 final TreeNode cur = current.get();
188 if (!orig.getData().equals(cur.getData())) {
189 checkNotConflicting(path, orig, cur);
195 * Checks if write operation can be applied to current TreeNode.
196 * The operation checks if original tree node to which the modification is going to be applied exists and if
197 * current node in TreeNode structure exists.
199 * @param path Path from current node in TreeNode
200 * @param modification modification to apply
201 * @param current current node in TreeNode for modification to apply
202 * @throws DataValidationFailedException when a data dependency conflict is detected
204 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
205 final Optional<? extends TreeNode> current, final Version version) throws DataValidationFailedException {
206 final Optional<? extends TreeNode> original = modification.getOriginal();
207 if (original.isPresent() && current.isPresent()) {
208 checkNotConflicting(path, original.get(), current.get());
210 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
211 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
215 private static void checkDeleteApplicable(final NodeModification modification,
216 final Optional<? extends TreeNode> current) {
217 // Delete is always applicable, we do not expose it to subclasses
218 if (!current.isPresent()) {
219 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
224 Optional<? extends TreeNode> apply(final ModifiedNode modification, final Optional<? extends TreeNode> currentMeta,
225 final Version version) {
226 switch (modification.getOperation()) {
228 // Deletion of a non-existing node is a no-op, report it as such
229 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
230 : ModificationType.UNMODIFIED);
231 return modification.setSnapshot(Optional.empty());
233 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
234 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
237 final TreeNode result;
239 if (!currentMeta.isPresent()) {
240 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
241 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
242 // to run that validation here.
243 modification.resolveModificationType(ModificationType.WRITE);
244 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
245 fullVerifyStructure(result.getData());
247 result = applyMerge(modification, currentMeta.get(), version);
250 return modification.setSnapshot(Optional.of(result));
252 modification.resolveModificationType(ModificationType.WRITE);
253 return modification.setSnapshot(Optional.of(applyWrite(modification,
254 verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
256 modification.resolveModificationType(ModificationType.UNMODIFIED);
259 throw new IllegalArgumentException("Provided modification type is not supported.");
264 * Apply a merge operation. Since the result of merge differs based on the data type
265 * being modified, implementations of this method are responsible for calling
266 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
268 * @param modification Modified node
269 * @param currentMeta Store Metadata Node on which NodeModification should be applied
270 * @param version New subtree version of parent node
271 * @return A sealed TreeNode representing applied operation.
273 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
275 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
276 Optional<? extends TreeNode> currentMeta, Version version);
279 * Apply a nested operation. Since there may not actually be a nested operation
280 * to be applied, implementations of this method are responsible for calling
281 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
283 * @param modification Modified node
284 * @param currentMeta Store Metadata Node on which NodeModification should be applied
285 * @param version New subtree version of parent node
286 * @return A sealed TreeNode representing applied operation.
288 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
291 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
293 * @param path Path to current node
294 * @param modification Node modification which should be applied.
295 * @param current Current state of data tree
296 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
297 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
298 * modification is not applicable (e.g. leaf node).
300 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
301 Optional<? extends TreeNode> current, Version version) throws DataValidationFailedException;
304 * Return the {@link WithStatus}-subclass schema associated with this operation.
305 * @return A model node
307 abstract @NonNull T getSchema();
310 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
311 * nodes in configuration tree are marked as such.
313 * @param treeType Tree Type
314 * @param node Schema node
315 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
317 static final boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
318 return treeType == TreeType.OPERATIONAL || node.isConfiguration();