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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import java.util.Collection;
15 import java.util.Map.Entry;
16 import java.util.Optional;
17 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
18 import javax.annotation.Nonnull;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeModification;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
28 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
29 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
34 SchemaContextProvider {
35 private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
36 AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
37 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
39 private final RootApplyStrategy strategyTree;
40 private final InMemoryDataTreeSnapshot snapshot;
41 private final ModifiedNode rootNode;
42 private final Version version;
44 private volatile int sealed = 0;
46 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
47 final RootApplyStrategy resolver) {
48 this.snapshot = requireNonNull(snapshot);
49 this.strategyTree = requireNonNull(resolver).snapshot();
50 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
53 * We could allocate version beforehand, since Version contract
54 * states two allocated version must be always different.
56 * Preallocating version simplifies scenarios such as
57 * chaining of modifications, since version for particular
58 * node in modification and in data tree (if successfully
59 * committed) will be same and will not change.
61 this.version = snapshot.getRootNode().getSubtreeVersion().next();
64 ModifiedNode getRootModification() {
68 ModificationApplyOperation getStrategy() {
69 return strategyTree.delegate();
73 public SchemaContext getSchemaContext() {
74 return snapshot.getSchemaContext();
78 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
80 checkIdentifierReferencesData(path, data);
81 resolveModificationFor(path).write(data);
85 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
87 checkIdentifierReferencesData(path, data);
88 resolveModificationFor(path).merge(data, version);
92 public void delete(final YangInstanceIdentifier path) {
95 resolveModificationFor(path).delete();
99 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
101 * Walk the tree from the top, looking for the first node between root and
102 * the requested path which has been modified. If no such node exists,
103 * we use the node itself.
105 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
106 path, ModifiedNode.IS_TERMINAL_PREDICATE);
107 final YangInstanceIdentifier key = entry.getKey();
108 final ModifiedNode mod = entry.getValue();
110 final Optional<TreeNode> result = resolveSnapshot(key, mod);
111 if (result.isPresent()) {
112 final NormalizedNode<?, ?> data = result.get().getData();
113 return NormalizedNodes.findNode(key, data, path);
116 return Optional.empty();
119 @SuppressWarnings("checkstyle:illegalCatch")
120 private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
121 final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
122 if (potentialSnapshot != null) {
123 return potentialSnapshot;
127 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
128 } catch (final Exception e) {
129 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
134 void upgradeIfPossible() {
135 if (rootNode.getOperation() == LogicalOperation.NONE) {
136 strategyTree.upgradeIfPossible();
140 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
141 LOG.trace("Resolving modification apply strategy for {}", path);
144 return StoreTreeNodes.findNodeChecked(getStrategy(), path);
147 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
151 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
153 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
154 * ending with an empty one, as we will throw the exception below. This fact could end up
155 * being a problem, as we'd have bunch of phantom operations.
157 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
160 ModificationApplyOperation operation = getStrategy();
161 ModifiedNode modification = rootNode;
164 for (final PathArgument pathArg : path.getPathArguments()) {
165 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
166 if (!potential.isPresent()) {
167 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
168 path.getAncestor(depth)));
170 operation = potential.get();
173 modification = modification.modifyChild(pathArg, operation, version);
176 return OperationWithModification.from(operation, modification);
179 private void checkSealed() {
180 checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
184 public String toString() {
185 return "MutableDataTree [modification=" + rootNode + "]";
189 public InMemoryDataTreeModification newModification() {
190 checkState(sealed == 1, "Attempted to chain on an unsealed modification");
192 if (rootNode.getOperation() == LogicalOperation.NONE) {
193 // Simple fast case: just use the underlying modification
194 return snapshot.newModification();
198 * We will use preallocated version, this means returned snapshot will
199 * have same version each time this method is called.
201 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
202 final Optional<TreeNode> tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
203 checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
205 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
206 tempRoot.get(), strategyTree);
207 return tempTree.newModification();
210 Version getVersion() {
218 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
219 final Collection<ModifiedNode> children = node.getChildren();
220 if (!children.isEmpty()) {
221 cursor.enter(node.getIdentifier());
222 for (final ModifiedNode child : children) {
223 applyNode(cursor, child);
229 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
230 switch (node.getOperation()) {
234 cursor.delete(node.getIdentifier());
237 cursor.merge(node.getIdentifier(), node.getWrittenValue());
238 applyChildren(cursor, node);
241 // TODO: we could improve efficiency of cursor use if we could understand
242 // nested TOUCH operations. One way of achieving that would be a proxy
243 // cursor, which would keep track of consecutive enter and exit calls
244 // and coalesce them.
245 applyChildren(cursor, node);
248 cursor.write(node.getIdentifier(), node.getWrittenValue());
249 applyChildren(cursor, node);
252 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
257 public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
258 for (final ModifiedNode child : rootNode.getChildren()) {
259 applyNode(cursor, child);
263 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
264 checkArgument(arg.equals(data.getIdentifier()),
265 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
268 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
269 final NormalizedNode<?, ?> data) {
270 final PathArgument arg;
272 if (!path.isEmpty()) {
273 arg = path.getLastPathArgument();
274 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
276 arg = rootNode.getIdentifier();
279 checkIdentifierReferencesData(arg, data);
283 public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
284 final OperationWithModification op = resolveModificationFor(path);
285 return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
289 public void ready() {
290 final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
291 checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
293 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, getStrategy());
295 current = current.process(version);
296 } while (current != null);