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 MinMaxElementsValidation.from(new LeafSetModificationStrategy((LeafListSchemaNode) schemaNode,
63 } else if (schemaNode instanceof LeafSchemaNode) {
64 return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
66 throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
69 public static DataNodeContainerModificationStrategy<AugmentationSchemaNode> from(
70 final DataNodeContainer resolvedTree, final AugmentationTarget augSchemas,
71 final AugmentationIdentifier identifier, final DataTreeConfiguration treeConfig) {
72 for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
73 for (final DataSchemaNode child : potential.getChildNodes()) {
74 if (identifier.getPossibleChildNames().contains(child.getQName())) {
75 return from(potential, resolvedTree, treeConfig);
83 static DataNodeContainerModificationStrategy<AugmentationSchemaNode> from(final AugmentationSchemaNode schema,
84 final DataNodeContainer resolved, final DataTreeConfiguration treeConfig) {
85 return new DataNodeContainerModificationStrategy<>(AUGMENTATION_SUPPORT,
86 EffectiveAugmentationSchema.create(schema, resolved), treeConfig);
89 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
90 throws ConflictingModificationAppliedException {
92 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
96 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
97 final DataTreeConfiguration treeConfig) {
98 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
99 final SchemaAwareApplyOperation<ListSchemaNode> op;
100 if (keyDefinition == null || keyDefinition.isEmpty()) {
101 op = new UnkeyedListModificationStrategy(schemaNode, treeConfig);
103 op = MapModificationStrategy.of(schemaNode, treeConfig);
105 return MinMaxElementsValidation.from(op);
108 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
109 final TreeNode current) throws ConflictingModificationAppliedException {
110 checkConflicting(path, original.getVersion().equals(current.getVersion()),
111 "Node was replaced by other transaction.");
112 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
113 "Node children was modified by other transaction");
116 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
117 final Optional<ModificationApplyOperation> potential = getChild(child);
118 Preconditions.checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
119 return potential.get();
123 final void checkApplicable(final ModificationPath path, final NodeModification modification,
124 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
125 switch (modification.getOperation()) {
127 checkDeleteApplicable(modification, current);
130 checkTouchApplicable(path, modification, current, version);
133 checkWriteApplicable(path, modification, current, version);
136 checkMergeApplicable(path, modification, current, version);
141 throw new UnsupportedOperationException(
142 "Suplied modification type " + modification.getOperation() + " is not supported.");
147 final void quickVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
148 verifyValue(writtenValue);
152 final void fullVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
153 verifyValue(writtenValue);
154 verifyValueChildren(writtenValue);
158 * Verify the a written value, without performing deeper tree validation.
160 * @param writtenValue Written value
162 abstract void verifyValue(NormalizedNode<?, ?> writtenValue);
165 * Verify the children implied by a written value after the value itself has been verified by
166 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
168 * @param writtenValue Written value
170 void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
174 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
175 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
176 final Optional<TreeNode> original = modification.getOriginal();
177 if (original.isPresent() && current.isPresent()) {
179 * We need to do conflict detection only and only if the value of leaf changed
180 * before two transactions. If value of leaf is unchanged between two transactions
181 * it should not cause transaction to fail, since result of this merge
182 * leads to same data.
184 final TreeNode orig = original.get();
185 final TreeNode cur = current.get();
186 if (!orig.getData().equals(cur.getData())) {
187 checkNotConflicting(path, orig, cur);
193 * Checks if write operation can be applied to current TreeNode.
194 * The operation checks if original tree node to which the modification is going to be applied exists and if
195 * current node in TreeNode structure exists.
197 * @param path Path from current node in TreeNode
198 * @param modification modification to apply
199 * @param current current node in TreeNode for modification to apply
200 * @throws DataValidationFailedException when a data dependency conflict is detected
202 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
203 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
204 final Optional<TreeNode> original = modification.getOriginal();
205 if (original.isPresent() && current.isPresent()) {
206 checkNotConflicting(path, original.get(), current.get());
208 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
209 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
213 private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
214 // Delete is always applicable, we do not expose it to subclasses
215 if (!current.isPresent()) {
216 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
221 final Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
222 final Version version) {
223 switch (modification.getOperation()) {
225 // Deletion of a non-existing node is a no-op, report it as such
226 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
227 : ModificationType.UNMODIFIED);
228 return modification.setSnapshot(Optional.empty());
230 Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s",
232 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
235 final TreeNode result;
237 if (!currentMeta.isPresent()) {
238 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
239 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
240 // to run that validation here.
241 modification.resolveModificationType(ModificationType.WRITE);
242 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
243 fullVerifyStructure(result.getData());
245 result = applyMerge(modification, currentMeta.get(), version);
248 return modification.setSnapshot(Optional.of(result));
250 modification.resolveModificationType(ModificationType.WRITE);
251 return modification.setSnapshot(Optional.of(applyWrite(modification, modification.getWrittenValue(),
252 currentMeta, version)));
254 modification.resolveModificationType(ModificationType.UNMODIFIED);
257 throw new IllegalArgumentException("Provided modification type is not supported.");
262 * Apply a merge operation. Since the result of merge differs based on the data type
263 * being modified, implementations of this method are responsible for calling
264 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
266 * @param modification Modified node
267 * @param currentMeta Store Metadata Node on which NodeModification should be applied
268 * @param version New subtree version of parent node
269 * @return A sealed TreeNode representing applied operation.
271 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
273 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
274 Optional<TreeNode> currentMeta, Version version);
277 * Apply a nested operation. Since there may not actually be a nested operation
278 * to be applied, implementations of this method are responsible for calling
279 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
281 * @param modification Modified node
282 * @param currentMeta Store Metadata Node on which NodeModification should be applied
283 * @param version New subtree version of parent node
284 * @return A sealed TreeNode representing applied operation.
286 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
289 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
291 * @param path Path to current node
292 * @param modification Node modification which should be applied.
293 * @param current Current state of data tree
294 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
295 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
296 * modification is not applicable (e.g. leaf node).
298 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
299 Optional<TreeNode> current, Version version) throws DataValidationFailedException;
302 * Return the {@link WithStatus}-subclass schema associated with this operation.
303 * @return A model node
305 abstract @NonNull T getSchema();
308 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
309 * nodes in configuration tree are marked as such.
311 * @param treeType Tree Type
312 * @param node Schema node
313 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
315 static boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
316 return treeType == TreeType.OPERATIONAL || node.isConfiguration();