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.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.CursorAwareDataTreeModification;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
32 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
33 AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
34 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
36 private final RootModificationApplyOperation strategyTree;
37 private final InMemoryDataTreeSnapshot snapshot;
38 private final ModifiedNode rootNode;
39 private final Version version;
41 private volatile int sealed = 0;
43 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final RootModificationApplyOperation resolver) {
44 this.snapshot = Preconditions.checkNotNull(snapshot);
45 this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
46 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
49 * We could allocate version beforehand, since Version contract
50 * states two allocated version must be always different.
52 * Preallocating version simplifies scenarios such as
53 * chaining of modifications, since version for particular
54 * node in modification and in data tree (if successfully
55 * committed) will be same and will not change.
57 this.version = snapshot.getRootNode().getSubtreeVersion().next();
60 ModifiedNode getRootModification() {
64 ModificationApplyOperation getStrategy() {
69 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
71 checkIdentifierReferencesData(path, data);
72 resolveModificationFor(path).write(data);
76 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
78 checkIdentifierReferencesData(path, data);
79 resolveModificationFor(path).merge(data, version);
83 public void delete(final YangInstanceIdentifier path) {
86 resolveModificationFor(path).delete();
90 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
92 * Walk the tree from the top, looking for the first node between root and
93 * the requested path which has been modified. If no such node exists,
94 * we use the node itself.
96 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
97 path, ModifiedNode.IS_TERMINAL_PREDICATE);
98 final YangInstanceIdentifier key = entry.getKey();
99 final ModifiedNode mod = entry.getValue();
101 final Optional<TreeNode> result = resolveSnapshot(key, mod);
102 if (result.isPresent()) {
103 final NormalizedNode<?, ?> data = result.get().getData();
104 return NormalizedNodes.findNode(key, data, path);
106 return Optional.absent();
110 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
111 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
112 if (potentialSnapshot != null) {
113 return potentialSnapshot;
117 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
118 } catch (final Exception e) {
119 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
124 void upgradeIfPossible() {
125 if (rootNode.getOperation() == LogicalOperation.NONE) {
126 strategyTree.upgradeIfPossible();
130 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
131 LOG.trace("Resolving modification apply strategy for {}", path);
134 return StoreTreeNodes.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
137 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
141 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
143 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
144 * ending with an empty one, as we will throw the exception below. This fact could end up
145 * being a problem, as we'd have bunch of phantom operations.
147 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
150 ModificationApplyOperation operation = strategyTree;
151 ModifiedNode modification = rootNode;
154 for(final PathArgument pathArg : path.getPathArguments()) {
155 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
156 if (!potential.isPresent()) {
157 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
158 path.getAncestor(i)));
160 operation = potential.get();
163 modification = modification.modifyChild(pathArg, operation, version);
166 return OperationWithModification.from(operation, modification);
169 private void checkSealed() {
170 Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
174 public String toString() {
175 return "MutableDataTree [modification=" + rootNode + "]";
179 public DataTreeModification newModification() {
180 Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
182 if (rootNode.getOperation() == LogicalOperation.NONE) {
183 // Simple fast case: just use the underlying modification
184 return snapshot.newModification();
188 * We will use preallocated version, this means returned snapshot will
189 * have same version each time this method is called.
191 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
192 final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
193 Preconditions.checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
195 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
196 return tempTree.newModification();
199 Version getVersion() {
207 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
208 final Collection<ModifiedNode> children = node.getChildren();
209 if (!children.isEmpty()) {
210 cursor.enter(node.getIdentifier());
211 for (final ModifiedNode child : children) {
212 applyNode(cursor, child);
218 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
219 switch (node.getOperation()) {
223 cursor.delete(node.getIdentifier());
226 cursor.merge(node.getIdentifier(), node.getWrittenValue());
227 applyChildren(cursor, node);
230 // TODO: we could improve efficiency of cursor use if we could understand
231 // nested TOUCH operations. One way of achieving that would be a proxy
232 // cursor, which would keep track of consecutive enter and exit calls
233 // and coalesce them.
234 applyChildren(cursor, node);
237 cursor.write(node.getIdentifier(), node.getWrittenValue());
238 applyChildren(cursor, node);
241 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
246 public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
247 for (final ModifiedNode child : rootNode.getChildren()) {
248 applyNode(cursor, child);
252 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
253 Preconditions.checkArgument(arg.equals(data.getIdentifier()),
254 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
257 private static void checkIdentifierReferencesData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
258 if (!path.isEmpty()) {
259 final PathArgument lastArg = path.getLastPathArgument();
260 Preconditions.checkArgument(lastArg != null, "Instance identifier %s has invalid null path argument", path);
261 checkIdentifierReferencesData(lastArg, data);
263 final QName type = data.getNodeType();
264 Preconditions.checkArgument(SchemaContext.NAME.equals(type), "Incorrect name %s of root node", type);
269 public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
270 final OperationWithModification op = resolveModificationFor(path);
271 return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
275 public void ready() {
276 final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
277 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
279 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
281 current = current.process(version);
282 } while (current != null);