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 com.google.common.base.Preconditions;
11 import java.util.List;
12 import java.util.Optional;
13 import org.eclipse.jdt.annotation.NonNull;
14 import org.opendaylight.yangtools.yang.common.QName;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
17 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAugmentationNodeBuilder;
28 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
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.util.EffectiveAugmentationSchema;
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);
44 private static final NormalizedNodeContainerSupport<AugmentationIdentifier, AugmentationNode> AUGMENTATION_SUPPORT =
45 new NormalizedNodeContainerSupport<>(AugmentationNode.class, ImmutableAugmentationNodeBuilder::create,
46 ImmutableAugmentationNodeBuilder::create);
48 public static ModificationApplyOperation from(final DataSchemaNode schemaNode,
49 final DataTreeConfiguration treeConfig) {
50 if (treeConfig.getTreeType() == TreeType.CONFIGURATION) {
51 Preconditions.checkArgument(schemaNode.isConfiguration(),
52 "Supplied %s does not belongs to configuration tree.", schemaNode.getPath());
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 fromLeafListSchemaNode((LeafListSchemaNode) schemaNode, treeConfig);
62 } else if (schemaNode instanceof LeafSchemaNode) {
63 return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
65 throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
68 public static DataNodeContainerModificationStrategy<AugmentationSchemaNode> from(
69 final DataNodeContainer resolvedTree, final AugmentationTarget augSchemas,
70 final AugmentationIdentifier identifier, final DataTreeConfiguration treeConfig) {
71 for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
72 for (final DataSchemaNode child : potential.getChildNodes()) {
73 if (identifier.getPossibleChildNames().contains(child.getQName())) {
74 return from(potential, resolvedTree, treeConfig);
82 static DataNodeContainerModificationStrategy<AugmentationSchemaNode> from(final AugmentationSchemaNode schema,
83 final DataNodeContainer resolved, final DataTreeConfiguration treeConfig) {
84 return new DataNodeContainerModificationStrategy<>(AUGMENTATION_SUPPORT,
85 EffectiveAugmentationSchema.create(schema, resolved), treeConfig);
88 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
89 throws ConflictingModificationAppliedException {
91 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
95 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
96 final DataTreeConfiguration treeConfig) {
97 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
98 final SchemaAwareApplyOperation<?> op;
99 if (keyDefinition == null || keyDefinition.isEmpty()) {
100 op = new UnkeyedListModificationStrategy(schemaNode, treeConfig);
102 op = MapModificationStrategy.of(schemaNode, treeConfig);
104 return MinMaxElementsValidation.from(op, schemaNode);
107 private static ModificationApplyOperation fromLeafListSchemaNode(final LeafListSchemaNode schemaNode,
108 final DataTreeConfiguration treeConfig) {
109 return MinMaxElementsValidation.from(new LeafSetModificationStrategy(schemaNode, treeConfig), schemaNode);
112 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
113 final TreeNode current) throws ConflictingModificationAppliedException {
114 checkConflicting(path, original.getVersion().equals(current.getVersion()),
115 "Node was replaced by other transaction.");
116 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
117 "Node children was modified by other transaction");
120 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
121 final Optional<ModificationApplyOperation> potential = getChild(child);
122 Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
123 return potential.get();
127 final void checkApplicable(final ModificationPath path, final NodeModification modification,
128 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
129 switch (modification.getOperation()) {
131 checkDeleteApplicable(modification, current);
134 checkTouchApplicable(path, modification, current, version);
137 checkWriteApplicable(path, modification, current, version);
140 checkMergeApplicable(path, modification, current, version);
145 throw new UnsupportedOperationException(
146 "Suplied modification type " + modification.getOperation() + " is not supported.");
151 final void quickVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
152 verifyValue(writtenValue);
156 final void fullVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
157 verifyValue(writtenValue);
158 verifyValueChildren(writtenValue);
162 * Verify the a written value, without performing deeper tree validation.
164 * @param writtenValue Written value
166 abstract void verifyValue(NormalizedNode<?, ?> writtenValue);
169 * Verify the children implied by a written value after the value itself has been verified by
170 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
172 * @param writtenValue Written value
174 void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
178 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
179 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
180 final Optional<TreeNode> original = modification.getOriginal();
181 if (original.isPresent() && current.isPresent()) {
183 * We need to do conflict detection only and only if the value of leaf changed
184 * before two transactions. If value of leaf is unchanged between two transactions
185 * it should not cause transaction to fail, since result of this merge
186 * leads to same data.
188 final TreeNode orig = original.get();
189 final TreeNode cur = current.get();
190 if (!orig.getData().equals(cur.getData())) {
191 checkNotConflicting(path, orig, cur);
197 * Checks if write operation can be applied to current TreeNode.
198 * The operation checks if original tree node to which the modification is going to be applied exists and if
199 * current node in TreeNode structure exists.
201 * @param path Path from current node in TreeNode
202 * @param modification modification to apply
203 * @param current current node in TreeNode for modification to apply
204 * @throws DataValidationFailedException when a data dependency conflict is detected
206 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
207 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
208 final Optional<TreeNode> original = modification.getOriginal();
209 if (original.isPresent() && current.isPresent()) {
210 checkNotConflicting(path, original.get(), current.get());
212 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
213 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
217 private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
218 // Delete is always applicable, we do not expose it to subclasses
219 if (!current.isPresent()) {
220 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
225 final Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
226 final Version version) {
227 switch (modification.getOperation()) {
229 // Deletion of a non-existing node is a no-op, report it as such
230 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
231 : ModificationType.UNMODIFIED);
232 return modification.setSnapshot(Optional.empty());
234 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s",
236 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
239 final TreeNode result;
241 if (!currentMeta.isPresent()) {
242 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
243 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
244 // to run that validation here.
245 modification.resolveModificationType(ModificationType.WRITE);
246 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
247 fullVerifyStructure(result.getData());
249 result = applyMerge(modification, currentMeta.get(), version);
252 return modification.setSnapshot(Optional.of(result));
254 modification.resolveModificationType(ModificationType.WRITE);
255 return modification.setSnapshot(Optional.of(applyWrite(modification, modification.getWrittenValue(),
256 currentMeta, version)));
258 modification.resolveModificationType(ModificationType.UNMODIFIED);
261 throw new IllegalArgumentException("Provided modification type is not supported.");
266 * Apply a merge operation. Since the result of merge differs based on the data type
267 * being modified, implementations of this method are responsible for calling
268 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
270 * @param modification Modified node
271 * @param currentMeta Store Metadata Node on which NodeModification should be applied
272 * @param version New subtree version of parent node
273 * @return A sealed TreeNode representing applied operation.
275 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
277 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
278 Optional<TreeNode> currentMeta, Version version);
281 * Apply a nested operation. Since there may not actually be a nested operation
282 * to be applied, implementations of this method are responsible for calling
283 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
285 * @param modification Modified node
286 * @param currentMeta Store Metadata Node on which NodeModification should be applied
287 * @param version New subtree version of parent node
288 * @return A sealed TreeNode representing applied operation.
290 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
293 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
295 * @param path Path to current node
296 * @param modification Node modification which should be applied.
297 * @param current Current state of data tree
298 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
299 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
300 * modification is not applicable (e.g. leaf node).
302 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
303 Optional<TreeNode> current, Version version) throws DataValidationFailedException;
306 * Return the {@link WithStatus}-subclass schema associated with this operation.
307 * @return A model node
309 abstract @NonNull T getSchema();
312 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
313 * nodes in configuration tree are marked as such.
315 * @param treeType Tree Type
316 * @param node Schema node
317 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
319 static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
320 return treeType == TreeType.OPERATIONAL || node.isConfiguration();