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.LeafNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeConfiguration;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
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.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 abstract class SchemaAwareApplyOperation<T extends WithStatus> extends ModificationApplyOperation {
42 private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareApplyOperation.class);
44 public static ModificationApplyOperation from(final DataSchemaNode schemaNode,
45 final DataTreeConfiguration treeConfig) {
46 if (treeConfig.getTreeType() == TreeType.CONFIGURATION) {
47 checkArgument(schemaNode.isConfiguration(), "Supplied %s does not belongs to configuration tree.",
48 schemaNode.getPath());
50 if (schemaNode instanceof ContainerSchemaNode) {
51 return ContainerModificationStrategy.of((ContainerSchemaNode) schemaNode, treeConfig);
52 } else if (schemaNode instanceof ListSchemaNode) {
53 return fromListSchemaNode((ListSchemaNode) schemaNode, treeConfig);
54 } else if (schemaNode instanceof ChoiceSchemaNode) {
55 return new ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode, treeConfig);
56 } else if (schemaNode instanceof LeafListSchemaNode) {
57 return MinMaxElementsValidation.from(new LeafSetModificationStrategy((LeafListSchemaNode) schemaNode,
59 } else if (schemaNode instanceof LeafSchemaNode) {
60 return new ValueNodeModificationStrategy<>(LeafNode.class, (LeafSchemaNode) schemaNode);
62 throw new IllegalArgumentException("Not supported schema node type for " + schemaNode.getClass());
65 public static AugmentationModificationStrategy from(final DataNodeContainer resolvedTree,
66 final AugmentationTarget augSchemas, final AugmentationIdentifier identifier,
67 final DataTreeConfiguration treeConfig) {
68 for (final AugmentationSchemaNode potential : augSchemas.getAvailableAugmentations()) {
69 for (final DataSchemaNode child : potential.getChildNodes()) {
70 if (identifier.getPossibleChildNames().contains(child.getQName())) {
71 return new AugmentationModificationStrategy(potential, resolvedTree, treeConfig);
79 static void checkConflicting(final ModificationPath path, final boolean condition, final String message)
80 throws ConflictingModificationAppliedException {
82 throw new ConflictingModificationAppliedException(path.toInstanceIdentifier(), message);
86 private static ModificationApplyOperation fromListSchemaNode(final ListSchemaNode schemaNode,
87 final DataTreeConfiguration treeConfig) {
88 final List<QName> keyDefinition = schemaNode.getKeyDefinition();
89 final SchemaAwareApplyOperation<ListSchemaNode> op;
90 if (keyDefinition == null || keyDefinition.isEmpty()) {
91 op = new UnkeyedListModificationStrategy(schemaNode, treeConfig);
93 op = MapModificationStrategy.of(schemaNode, treeConfig);
96 return MinMaxElementsValidation.from(op);
99 protected static void checkNotConflicting(final ModificationPath path, final TreeNode original,
100 final TreeNode current) throws ConflictingModificationAppliedException {
101 checkConflicting(path, original.getVersion().equals(current.getVersion()),
102 "Node was replaced by other transaction.");
103 checkConflicting(path, original.getSubtreeVersion().equals(current.getSubtreeVersion()),
104 "Node children was modified by other transaction");
107 protected final ModificationApplyOperation resolveChildOperation(final PathArgument child) {
108 final Optional<ModificationApplyOperation> potential = getChild(child);
109 checkArgument(potential.isPresent(), "Operation for child %s is not defined.", child);
110 return potential.get();
114 final void checkApplicable(final ModificationPath path, final NodeModification modification,
115 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
116 switch (modification.getOperation()) {
118 checkDeleteApplicable(modification, current);
121 checkTouchApplicable(path, modification, current, version);
124 checkWriteApplicable(path, modification, current, version);
127 checkMergeApplicable(path, modification, current, version);
132 throw new UnsupportedOperationException(
133 "Suplied modification type " + modification.getOperation() + " is not supported.");
138 final void quickVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
139 verifyValue(writtenValue);
143 final void fullVerifyStructure(final NormalizedNode<?, ?> writtenValue) {
144 verifyValue(writtenValue);
145 verifyValueChildren(writtenValue);
149 * Verify the a written value, without performing deeper tree validation.
151 * @param writtenValue Written value
153 abstract void verifyValue(NormalizedNode<?, ?> writtenValue);
156 * Verify the children implied by a written value after the value itself has been verified by
157 * {@link #verifyValue(NormalizedNode)}. Default implementation does nothing.
159 * @param writtenValue Written value
161 void verifyValueChildren(final NormalizedNode<?, ?> writtenValue) {
165 protected void checkMergeApplicable(final ModificationPath path, final NodeModification modification,
166 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
167 final Optional<TreeNode> original = modification.getOriginal();
168 if (original.isPresent() && current.isPresent()) {
170 * We need to do conflict detection only and only if the value of leaf changed
171 * before two transactions. If value of leaf is unchanged between two transactions
172 * it should not cause transaction to fail, since result of this merge
173 * leads to same data.
175 final TreeNode orig = original.get();
176 final TreeNode cur = current.get();
177 if (!orig.getData().equals(cur.getData())) {
178 checkNotConflicting(path, orig, cur);
184 * Checks if write operation can be applied to current TreeNode.
185 * The operation checks if original tree node to which the modification is going to be applied exists and if
186 * current node in TreeNode structure exists.
188 * @param path Path from current node in TreeNode
189 * @param modification modification to apply
190 * @param current current node in TreeNode for modification to apply
191 * @throws DataValidationFailedException when a data dependency conflict is detected
193 private static void checkWriteApplicable(final ModificationPath path, final NodeModification modification,
194 final Optional<TreeNode> current, final Version version) throws DataValidationFailedException {
195 final Optional<TreeNode> original = modification.getOriginal();
196 if (original.isPresent() && current.isPresent()) {
197 checkNotConflicting(path, original.get(), current.get());
199 checkConflicting(path, !original.isPresent(), "Node was deleted by other transaction.");
200 checkConflicting(path, !current.isPresent(), "Node was created by other transaction.");
204 private static void checkDeleteApplicable(final NodeModification modification, final Optional<TreeNode> current) {
205 // Delete is always applicable, we do not expose it to subclasses
206 if (!current.isPresent()) {
207 LOG.trace("Delete operation turned to no-op on missing node {}", modification);
212 Optional<TreeNode> apply(final ModifiedNode modification, final Optional<TreeNode> currentMeta,
213 final Version version) {
214 switch (modification.getOperation()) {
216 // Deletion of a non-existing node is a no-op, report it as such
217 modification.resolveModificationType(currentMeta.isPresent() ? ModificationType.DELETE
218 : ModificationType.UNMODIFIED);
219 return modification.setSnapshot(Optional.empty());
221 checkArgument(currentMeta.isPresent(), "Metadata not available for modification %s", modification);
222 return modification.setSnapshot(Optional.of(applyTouch(modification, currentMeta.get(),
225 final TreeNode result;
227 if (!currentMeta.isPresent()) {
228 // This is a slight optimization: a merge on a non-existing node equals to a write. Written data
229 // structure is usually verified when the transaction is sealed. To preserve correctness, we have
230 // to run that validation here.
231 modification.resolveModificationType(ModificationType.WRITE);
232 result = applyWrite(modification, modification.getWrittenValue(), currentMeta, version);
233 fullVerifyStructure(result.getData());
235 result = applyMerge(modification, currentMeta.get(), version);
238 return modification.setSnapshot(Optional.of(result));
240 modification.resolveModificationType(ModificationType.WRITE);
241 return modification.setSnapshot(Optional.of(applyWrite(modification,
242 verifyNotNull(modification.getWrittenValue()), currentMeta, version)));
244 modification.resolveModificationType(ModificationType.UNMODIFIED);
247 throw new IllegalArgumentException("Provided modification type is not supported.");
252 * Apply a merge operation. Since the result of merge differs based on the data type
253 * being modified, implementations of this method are responsible for calling
254 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
256 * @param modification Modified node
257 * @param currentMeta Store Metadata Node on which NodeModification should be applied
258 * @param version New subtree version of parent node
259 * @return A sealed TreeNode representing applied operation.
261 protected abstract TreeNode applyMerge(ModifiedNode modification, TreeNode currentMeta, Version version);
263 protected abstract TreeNode applyWrite(ModifiedNode modification, NormalizedNode<?, ?> newValue,
264 Optional<TreeNode> currentMeta, Version version);
267 * Apply a nested operation. Since there may not actually be a nested operation
268 * to be applied, implementations of this method are responsible for calling
269 * {@link ModifiedNode#resolveModificationType(ModificationType)} as appropriate.
271 * @param modification Modified node
272 * @param currentMeta Store Metadata Node on which NodeModification should be applied
273 * @param version New subtree version of parent node
274 * @return A sealed TreeNode representing applied operation.
276 protected abstract TreeNode applyTouch(ModifiedNode modification, TreeNode currentMeta, Version version);
279 * Checks is supplied {@link NodeModification} is applicable for Subtree Modification.
281 * @param path Path to current node
282 * @param modification Node modification which should be applied.
283 * @param current Current state of data tree
284 * @throws ConflictingModificationAppliedException If subtree was changed in conflicting way
285 * @throws org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException If subtree
286 * modification is not applicable (e.g. leaf node).
288 protected abstract void checkTouchApplicable(ModificationPath path, NodeModification modification,
289 Optional<TreeNode> current, Version version) throws DataValidationFailedException;
292 * Return the {@link WithStatus}-subclass schema associated with this operation.
293 * @return A model node
295 abstract @NonNull T getSchema();
298 * Checks if supplied schema node belong to specified Data Tree type. All nodes belong to the operational tree,
299 * nodes in configuration tree are marked as such.
301 * @param treeType Tree Type
302 * @param node Schema node
303 * @return {@code true} if the node matches the tree type, {@code false} otherwise.
305 static final boolean belongsToTree(final TreeType treeType, final DataSchemaNode node) {
306 return treeType == TreeType.OPERATIONAL || node.isConfiguration();