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.Collection;
12 import java.util.Map.Entry;
13 import java.util.Optional;
14 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeModification;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
29 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
30 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
31 AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
32 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
34 private final RootModificationApplyOperation strategyTree;
35 private final InMemoryDataTreeSnapshot snapshot;
36 private final ModifiedNode rootNode;
37 private final Version version;
39 private volatile int sealed = 0;
41 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
42 final RootModificationApplyOperation resolver) {
43 this.snapshot = Preconditions.checkNotNull(snapshot);
44 this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
45 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
48 * We could allocate version beforehand, since Version contract
49 * states two allocated version must be always different.
51 * Preallocating version simplifies scenarios such as
52 * chaining of modifications, since version for particular
53 * node in modification and in data tree (if successfully
54 * committed) will be same and will not change.
56 this.version = snapshot.getRootNode().getSubtreeVersion().next();
59 ModifiedNode getRootModification() {
63 ModificationApplyOperation getStrategy() {
68 public SchemaContext getSchemaContext() {
69 return snapshot.getSchemaContext();
73 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
75 checkIdentifierReferencesData(path, data);
76 resolveModificationFor(path).write(data);
80 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
82 checkIdentifierReferencesData(path, data);
83 resolveModificationFor(path).merge(data, version);
87 public void delete(final YangInstanceIdentifier path) {
90 resolveModificationFor(path).delete();
94 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
96 * Walk the tree from the top, looking for the first node between root and
97 * the requested path which has been modified. If no such node exists,
98 * we use the node itself.
100 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
101 path, ModifiedNode.IS_TERMINAL_PREDICATE);
102 final YangInstanceIdentifier key = entry.getKey();
103 final ModifiedNode mod = entry.getValue();
105 final Optional<TreeNode> result = resolveSnapshot(key, mod);
106 if (result.isPresent()) {
107 final NormalizedNode<?, ?> data = result.get().getData();
108 return NormalizedNodes.findNode(key, data, path);
111 return Optional.empty();
114 @SuppressWarnings("checkstyle:illegalCatch")
115 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
116 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
117 if (potentialSnapshot != null) {
118 return potentialSnapshot;
122 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
123 } catch (final Exception e) {
124 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
129 void upgradeIfPossible() {
130 if (rootNode.getOperation() == LogicalOperation.NONE) {
131 strategyTree.upgradeIfPossible();
135 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
136 LOG.trace("Resolving modification apply strategy for {}", path);
139 return StoreTreeNodes.findNodeChecked(strategyTree, path);
142 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
146 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
148 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
149 * ending with an empty one, as we will throw the exception below. This fact could end up
150 * being a problem, as we'd have bunch of phantom operations.
152 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
155 ModificationApplyOperation operation = strategyTree;
156 ModifiedNode modification = rootNode;
159 for (final PathArgument pathArg : path.getPathArguments()) {
160 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
161 if (!potential.isPresent()) {
162 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
163 path.getAncestor(depth)));
165 operation = potential.get();
168 modification = modification.modifyChild(pathArg, operation, version);
171 return OperationWithModification.from(operation, modification);
174 private void checkSealed() {
175 Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
179 public String toString() {
180 return "MutableDataTree [modification=" + rootNode + "]";
184 public InMemoryDataTreeModification newModification() {
185 Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
187 if (rootNode.getOperation() == LogicalOperation.NONE) {
188 // Simple fast case: just use the underlying modification
189 return snapshot.newModification();
193 * We will use preallocated version, this means returned snapshot will
194 * have same version each time this method is called.
196 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
197 final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
198 Preconditions.checkState(tempRoot.isPresent(),
199 "Data tree root is not present, possibly removed by previous modification");
201 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
202 tempRoot.get(), strategyTree);
203 return tempTree.newModification();
206 Version getVersion() {
214 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
215 final Collection<ModifiedNode> children = node.getChildren();
216 if (!children.isEmpty()) {
217 cursor.enter(node.getIdentifier());
218 for (final ModifiedNode child : children) {
219 applyNode(cursor, child);
225 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
226 switch (node.getOperation()) {
230 cursor.delete(node.getIdentifier());
233 cursor.merge(node.getIdentifier(), node.getWrittenValue());
234 applyChildren(cursor, node);
237 // TODO: we could improve efficiency of cursor use if we could understand
238 // nested TOUCH operations. One way of achieving that would be a proxy
239 // cursor, which would keep track of consecutive enter and exit calls
240 // and coalesce them.
241 applyChildren(cursor, node);
244 cursor.write(node.getIdentifier(), node.getWrittenValue());
245 applyChildren(cursor, node);
248 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
253 public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
254 for (final ModifiedNode child : rootNode.getChildren()) {
255 applyNode(cursor, child);
259 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
260 Preconditions.checkArgument(arg.equals(data.getIdentifier()),
261 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
264 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
265 final NormalizedNode<?, ?> data) {
266 final PathArgument arg;
268 if (!path.isEmpty()) {
269 arg = path.getLastPathArgument();
270 Preconditions.checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
272 arg = rootNode.getIdentifier();
275 checkIdentifierReferencesData(arg, data);
279 public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
280 final OperationWithModification op = resolveModificationFor(path);
281 return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
285 public void ready() {
286 final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
287 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
289 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
291 current = current.process(version);
292 } while (current != null);