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 java.util.Collection;
13 import java.util.Map.Entry;
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.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
28 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
29 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
30 AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
31 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
33 private final RootModificationApplyOperation strategyTree;
34 private final InMemoryDataTreeSnapshot snapshot;
35 private final ModifiedNode rootNode;
36 private final Version version;
38 private volatile int sealed = 0;
40 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
41 final RootModificationApplyOperation resolver) {
42 this.snapshot = Preconditions.checkNotNull(snapshot);
43 this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
44 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
47 * We could allocate version beforehand, since Version contract
48 * states two allocated version must be always different.
50 * Preallocating version simplifies scenarios such as
51 * chaining of modifications, since version for particular
52 * node in modification and in data tree (if successfully
53 * committed) will be same and will not change.
55 this.version = snapshot.getRootNode().getSubtreeVersion().next();
58 ModifiedNode getRootModification() {
62 ModificationApplyOperation getStrategy() {
67 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
69 checkIdentifierReferencesData(path, data);
70 resolveModificationFor(path).write(data);
74 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
76 checkIdentifierReferencesData(path, data);
77 resolveModificationFor(path).merge(data, version);
81 public void delete(final YangInstanceIdentifier path) {
84 resolveModificationFor(path).delete();
88 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
90 * Walk the tree from the top, looking for the first node between root and
91 * the requested path which has been modified. If no such node exists,
92 * we use the node itself.
94 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
95 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);
105 return Optional.absent();
108 @SuppressWarnings("checkstyle:illegalCatch")
109 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
110 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
111 if (potentialSnapshot != null) {
112 return potentialSnapshot;
116 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
117 } catch (final Exception e) {
118 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
123 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.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 path.getAncestor(depth)));
159 operation = potential.get();
162 modification = modification.modifyChild(pathArg, operation, version);
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 InMemoryDataTreeModification 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(),
193 "Data tree root is not present, possibly removed by previous modification");
195 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
196 tempRoot.get(), strategyTree);
197 return tempTree.newModification();
200 Version getVersion() {
208 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
209 final Collection<ModifiedNode> children = node.getChildren();
210 if (!children.isEmpty()) {
211 cursor.enter(node.getIdentifier());
212 for (final ModifiedNode child : children) {
213 applyNode(cursor, child);
219 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
220 switch (node.getOperation()) {
224 cursor.delete(node.getIdentifier());
227 cursor.merge(node.getIdentifier(), node.getWrittenValue());
228 applyChildren(cursor, node);
231 // TODO: we could improve efficiency of cursor use if we could understand
232 // nested TOUCH operations. One way of achieving that would be a proxy
233 // cursor, which would keep track of consecutive enter and exit calls
234 // and coalesce them.
235 applyChildren(cursor, node);
238 cursor.write(node.getIdentifier(), node.getWrittenValue());
239 applyChildren(cursor, node);
242 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
247 public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
248 for (final ModifiedNode child : rootNode.getChildren()) {
249 applyNode(cursor, child);
253 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
254 Preconditions.checkArgument(arg.equals(data.getIdentifier()),
255 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
258 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
259 final NormalizedNode<?, ?> data) {
260 final PathArgument arg;
262 if (!path.isEmpty()) {
263 arg = path.getLastPathArgument();
264 Preconditions.checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
266 arg = rootNode.getIdentifier();
269 checkIdentifierReferencesData(arg, data);
273 public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
274 final OperationWithModification op = resolveModificationFor(path);
275 return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
279 public void ready() {
280 final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
281 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
283 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
285 current = current.process(version);
286 } while (current != null);