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.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.DataTreeModification;
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 implements DataTreeModification {
29 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> 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, final RootModificationApplyOperation resolver) {
41 this.snapshot = Preconditions.checkNotNull(snapshot);
42 this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
43 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
46 * We could allocate version beforehand, since Version contract
47 * states two allocated version must be always different.
49 * Preallocating version simplifies scenarios such as
50 * chaining of modifications, since version for particular
51 * node in modification and in data tree (if successfully
52 * committed) will be same and will not change.
54 this.version = snapshot.getRootNode().getSubtreeVersion().next();
57 ModifiedNode getRootModification() {
61 ModificationApplyOperation getStrategy() {
66 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
69 resolveModificationFor(path).write(data);
73 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
76 resolveModificationFor(path).merge(data);
80 public void delete(final YangInstanceIdentifier path) {
83 resolveModificationFor(path).delete();
87 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
89 * Walk the tree from the top, looking for the first node between root and
90 * the requested path which has been modified. If no such node exists,
91 * we use the node itself.
93 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
94 final YangInstanceIdentifier key = entry.getKey();
95 final ModifiedNode mod = entry.getValue();
97 final Optional<TreeNode> result = resolveSnapshot(key, mod);
98 if (result.isPresent()) {
99 final NormalizedNode<?, ?> data = result.get().getData();
100 return NormalizedNodes.findNode(key, data, path);
102 return Optional.absent();
106 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
107 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
108 if (potentialSnapshot != null) {
109 return potentialSnapshot;
113 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
115 } catch (final Exception e) {
116 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
121 private void upgradeIfPossible() {
122 if (rootNode.getOperation() == LogicalOperation.NONE) {
123 strategyTree.upgradeIfPossible();
127 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
128 LOG.trace("Resolving modification apply strategy for {}", path);
131 return StoreTreeNodes.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
134 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
138 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
140 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
141 * ending with an empty one, as we will throw the exception below. This fact could end up
142 * being a problem, as we'd have bunch of phantom operations.
144 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
147 ModificationApplyOperation operation = strategyTree;
148 ModifiedNode modification = rootNode;
151 for(final PathArgument pathArg : path.getPathArguments()) {
152 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
153 if (!potential.isPresent()) {
154 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
155 Iterables.toString(Iterables.limit(path.getPathArguments(), i))));
157 operation = potential.get();
160 modification = modification.modifyChild(pathArg, operation.getChildPolicy());
163 return OperationWithModification.from(operation, modification);
166 private void checkSealed() {
167 Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
171 public String toString() {
172 return "MutableDataTree [modification=" + rootNode + "]";
176 public DataTreeModification newModification() {
177 Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
179 if (rootNode.getOperation() == LogicalOperation.NONE) {
180 // Simple fast case: just use the underlying modification
181 return snapshot.newModification();
185 * We will use preallocated version, this means returned snapshot will
186 * have same version each time this method is called.
188 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
189 final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
190 Preconditions.checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
192 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
193 return tempTree.newModification();
196 Version getVersion() {
200 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
201 final Collection<ModifiedNode> children = node.getChildren();
202 if (!children.isEmpty()) {
203 cursor.enter(node.getIdentifier());
204 for (final ModifiedNode child : children) {
205 applyNode(cursor, child);
211 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
212 switch (node.getOperation()) {
216 cursor.delete(node.getIdentifier());
219 cursor.merge(node.getIdentifier(), node.getWrittenValue());
220 applyChildren(cursor, node);
223 // TODO: we could improve efficiency of cursor use if we could understand
224 // nested TOUCH operations. One way of achieving that would be a proxy
225 // cursor, which would keep track of consecutive enter and exit calls
226 // and coalesce them.
227 applyChildren(cursor, node);
230 cursor.write(node.getIdentifier(), node.getWrittenValue());
231 applyChildren(cursor, node);
234 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
239 public void applyToCursor(final DataTreeModificationCursor cursor) {
240 for (final ModifiedNode child : rootNode.getChildren()) {
241 applyNode(cursor, child);
245 private static void checkIdentifierReferencesData(final YangInstanceIdentifier path,
246 final NormalizedNode<?, ?> data) {
247 final PathArgument lastArg = path.getLastPathArgument();
248 Preconditions.checkArgument(data.getIdentifier().equals(lastArg),
249 "Instance identifier references %s but data identifier is %s", lastArg, data.getIdentifier());
253 public void ready() {
254 final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
255 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
257 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode);
259 current = current.process();
260 } while (current != null);