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.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
31 SchemaContextProvider {
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,
44 final RootModificationApplyOperation resolver) {
45 this.snapshot = Preconditions.checkNotNull(snapshot);
46 this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
47 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
50 * We could allocate version beforehand, since Version contract
51 * states two allocated version must be always different.
53 * Preallocating version simplifies scenarios such as
54 * chaining of modifications, since version for particular
55 * node in modification and in data tree (if successfully
56 * committed) will be same and will not change.
58 this.version = snapshot.getRootNode().getSubtreeVersion().next();
61 ModifiedNode getRootModification() {
65 ModificationApplyOperation getStrategy() {
70 public SchemaContext getSchemaContext() {
71 return snapshot.getSchemaContext();
75 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
77 checkIdentifierReferencesData(path, data);
78 resolveModificationFor(path).write(data);
82 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
84 checkIdentifierReferencesData(path, data);
85 resolveModificationFor(path).merge(data, version);
89 public void delete(final YangInstanceIdentifier path) {
92 resolveModificationFor(path).delete();
96 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
98 * Walk the tree from the top, looking for the first node between root and
99 * the requested path which has been modified. If no such node exists,
100 * we use the node itself.
102 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
103 path, ModifiedNode.IS_TERMINAL_PREDICATE);
104 final YangInstanceIdentifier key = entry.getKey();
105 final ModifiedNode mod = entry.getValue();
107 final Optional<TreeNode> result = resolveSnapshot(key, mod);
108 if (result.isPresent()) {
109 final NormalizedNode<?, ?> data = result.get().getData();
110 return NormalizedNodes.findNode(key, data, path);
113 return Optional.empty();
116 @SuppressWarnings("checkstyle:illegalCatch")
117 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
118 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
119 if (potentialSnapshot != null) {
120 return potentialSnapshot;
124 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
125 } catch (final Exception e) {
126 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
131 void upgradeIfPossible() {
132 if (rootNode.getOperation() == LogicalOperation.NONE) {
133 strategyTree.upgradeIfPossible();
137 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
138 LOG.trace("Resolving modification apply strategy for {}", path);
141 return StoreTreeNodes.findNodeChecked(strategyTree, path);
144 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
148 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
150 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
151 * ending with an empty one, as we will throw the exception below. This fact could end up
152 * being a problem, as we'd have bunch of phantom operations.
154 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
157 ModificationApplyOperation operation = strategyTree;
158 ModifiedNode modification = rootNode;
161 for (final PathArgument pathArg : path.getPathArguments()) {
162 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
163 if (!potential.isPresent()) {
164 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
165 path.getAncestor(depth)));
167 operation = potential.get();
170 modification = modification.modifyChild(pathArg, operation, version);
173 return OperationWithModification.from(operation, modification);
176 private void checkSealed() {
177 Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
181 public String toString() {
182 return "MutableDataTree [modification=" + rootNode + "]";
186 public InMemoryDataTreeModification newModification() {
187 Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
189 if (rootNode.getOperation() == LogicalOperation.NONE) {
190 // Simple fast case: just use the underlying modification
191 return snapshot.newModification();
195 * We will use preallocated version, this means returned snapshot will
196 * have same version each time this method is called.
198 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
199 final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
200 Preconditions.checkState(tempRoot.isPresent(),
201 "Data tree root is not present, possibly removed by previous modification");
203 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
204 tempRoot.get(), strategyTree);
205 return tempTree.newModification();
208 Version getVersion() {
216 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
217 final Collection<ModifiedNode> children = node.getChildren();
218 if (!children.isEmpty()) {
219 cursor.enter(node.getIdentifier());
220 for (final ModifiedNode child : children) {
221 applyNode(cursor, child);
227 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
228 switch (node.getOperation()) {
232 cursor.delete(node.getIdentifier());
235 cursor.merge(node.getIdentifier(), node.getWrittenValue());
236 applyChildren(cursor, node);
239 // TODO: we could improve efficiency of cursor use if we could understand
240 // nested TOUCH operations. One way of achieving that would be a proxy
241 // cursor, which would keep track of consecutive enter and exit calls
242 // and coalesce them.
243 applyChildren(cursor, node);
246 cursor.write(node.getIdentifier(), node.getWrittenValue());
247 applyChildren(cursor, node);
250 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
255 public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
256 for (final ModifiedNode child : rootNode.getChildren()) {
257 applyNode(cursor, child);
261 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
262 Preconditions.checkArgument(arg.equals(data.getIdentifier()),
263 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
266 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
267 final NormalizedNode<?, ?> data) {
268 final PathArgument arg;
270 if (!path.isEmpty()) {
271 arg = path.getLastPathArgument();
272 Preconditions.checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
274 arg = rootNode.getIdentifier();
277 checkIdentifierReferencesData(arg, data);
281 public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
282 final OperationWithModification op = resolveModificationFor(path);
283 return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
287 public void ready() {
288 final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
289 Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
291 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
293 current = current.process(version);
294 } while (current != null);