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.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.Iterables;
13 import java.util.Collection;
14 import java.util.Map.Entry;
15 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 final class InMemoryDataTreeModification implements DataTreeModification {
31 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> UPDATER =
32 AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
33 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
35 private final RootModificationApplyOperation strategyTree;
36 private final InMemoryDataTreeSnapshot snapshot;
37 private final ModifiedNode rootNode;
38 private final Version version;
40 private volatile int sealed = 0;
42 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, 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 void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
70 checkIdentifierReferencesData(path, data);
71 resolveModificationFor(path).write(data);
75 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
77 checkIdentifierReferencesData(path, data);
78 resolveModificationFor(path).merge(data);
82 public void delete(final YangInstanceIdentifier path) {
85 resolveModificationFor(path).delete();
89 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
91 * Walk the tree from the top, looking for the first node between root and
92 * the requested path which has been modified. If no such node exists,
93 * we use the node itself.
95 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
96 final YangInstanceIdentifier key = entry.getKey();
97 final ModifiedNode mod = entry.getValue();
99 final Optional<TreeNode> result = resolveSnapshot(key, mod);
100 if (result.isPresent()) {
101 final NormalizedNode<?, ?> data = result.get().getData();
102 return NormalizedNodes.findNode(key, data, path);
104 return Optional.absent();
108 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
109 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
110 if (potentialSnapshot != null) {
111 return potentialSnapshot;
115 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
117 } catch (final Exception e) {
118 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
123 private void upgradeIfPossible() {
124 if (rootNode.getOperation() == LogicalOperation.NONE) {
125 strategyTree.upgradeIfPossible();
129 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
130 LOG.trace("Resolving modification apply strategy for {}", path);
133 return StoreTreeNodes.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
136 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
140 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
142 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
143 * ending with an empty one, as we will throw the exception below. This fact could end up
144 * being a problem, as we'd have bunch of phantom operations.
146 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
149 ModificationApplyOperation operation = strategyTree;
150 ModifiedNode modification = rootNode;
153 for(final PathArgument pathArg : path.getPathArguments()) {
154 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
155 if (!potential.isPresent()) {
156 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
157 Iterables.toString(Iterables.limit(path.getPathArguments(), i))));
159 operation = potential.get();
162 modification = modification.modifyChild(pathArg, operation.getChildPolicy());
165 return OperationWithModification.from(operation, modification);
168 private void checkSealed() {
169 Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
173 public String toString() {
174 return "MutableDataTree [modification=" + rootNode + "]";
178 public DataTreeModification newModification() {
179 Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
181 if (rootNode.getOperation() == LogicalOperation.NONE) {
182 // Simple fast case: just use the underlying modification
183 return snapshot.newModification();
187 * We will use preallocated version, this means returned snapshot will
188 * have same version each time this method is called.
190 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
191 final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
192 Preconditions.checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
194 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
195 return tempTree.newModification();
198 Version getVersion() {
206 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
207 final Collection<ModifiedNode> children = node.getChildren();
208 if (!children.isEmpty()) {
209 cursor.enter(node.getIdentifier());
210 for (final ModifiedNode child : children) {
211 applyNode(cursor, child);
217 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
218 switch (node.getOperation()) {
222 cursor.delete(node.getIdentifier());
225 cursor.merge(node.getIdentifier(), node.getWrittenValue());
226 applyChildren(cursor, node);
229 // TODO: we could improve efficiency of cursor use if we could understand
230 // nested TOUCH operations. One way of achieving that would be a proxy
231 // cursor, which would keep track of consecutive enter and exit calls
232 // and coalesce them.
233 applyChildren(cursor, node);
236 cursor.write(node.getIdentifier(), node.getWrittenValue());
237 applyChildren(cursor, node);
240 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
245 public void applyToCursor(final DataTreeModificationCursor cursor) {
246 for (final ModifiedNode child : rootNode.getChildren()) {
247 applyNode(cursor, child);
251 private static void checkIdentifierReferencesData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
252 if (!path.isEmpty()) {
253 final PathArgument lastArg = path.getLastPathArgument();
254 Preconditions.checkArgument(lastArg != null, "Instance identifier %s has invalid null path argument", path);
255 Preconditions.checkArgument(lastArg.equals(data.getIdentifier()),
256 "Instance identifier references %s but data identifier is %s", lastArg, data.getIdentifier());
258 final QName type = data.getNodeType();
259 Preconditions.checkArgument(SchemaContext.NAME.equals(type), "Incorrect name %s of root node", type);
264 public void ready() {
265 final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
266 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
268 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
270 current = current.process();
271 } while (current != null);