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.lang.invoke.MethodHandles;
15 import java.lang.invoke.VarHandle;
16 import java.util.Collection;
17 import java.util.Map.Entry;
18 import java.util.Optional;
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.EffectiveModelContext;
29 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
34 EffectiveModelContextProvider {
35 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
37 private final RootApplyStrategy strategyTree;
38 private final InMemoryDataTreeSnapshot snapshot;
39 private final ModifiedNode rootNode;
40 private final Version version;
42 private static final VarHandle SEALED;
46 SEALED = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "sealed", int.class);
47 } catch (ReflectiveOperationException e) {
48 throw new ExceptionInInitializerError(e);
52 // All access needs to go through this handle
53 @SuppressWarnings("unused")
54 private volatile int sealed;
56 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
57 final RootApplyStrategy resolver) {
58 this.snapshot = requireNonNull(snapshot);
59 this.strategyTree = requireNonNull(resolver).snapshot();
60 this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
63 * We could allocate version beforehand, since Version contract
64 * states two allocated version must be always different.
66 * Preallocating version simplifies scenarios such as
67 * chaining of modifications, since version for particular
68 * node in modification and in data tree (if successfully
69 * committed) will be same and will not change.
71 this.version = snapshot.getRootNode().getSubtreeVersion().next();
74 ModifiedNode getRootModification() {
78 ModificationApplyOperation getStrategy() {
79 final ModificationApplyOperation ret = strategyTree.delegate();
81 throw new IllegalStateException("Schema Context is not available.");
87 public EffectiveModelContext getEffectiveModelContext() {
88 return snapshot.getEffectiveModelContext();
92 public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
94 checkIdentifierReferencesData(path, data);
95 resolveModificationFor(path).write(data);
99 public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
101 checkIdentifierReferencesData(path, data);
102 resolveModificationFor(path).merge(data, version);
106 public void delete(final YangInstanceIdentifier path) {
109 resolveModificationFor(path).delete();
113 public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
115 * Walk the tree from the top, looking for the first node between root and
116 * the requested path which has been modified. If no such node exists,
117 * we use the node itself.
119 final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
120 path, ModifiedNode.IS_TERMINAL_PREDICATE);
121 final YangInstanceIdentifier key = entry.getKey();
122 final ModifiedNode mod = entry.getValue();
124 final Optional<? extends TreeNode> result = resolveSnapshot(key, mod);
125 if (result.isPresent()) {
126 final NormalizedNode<?, ?> data = result.get().getData();
127 return NormalizedNodes.findNode(key, data, path);
130 return Optional.empty();
133 @SuppressWarnings("checkstyle:illegalCatch")
134 private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
135 final ModifiedNode modification) {
136 final Optional<? extends TreeNode> potentialSnapshot = modification.getSnapshot();
137 if (potentialSnapshot != null) {
138 return potentialSnapshot;
142 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
143 } catch (final Exception e) {
144 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
149 void upgradeIfPossible() {
150 if (rootNode.getOperation() == LogicalOperation.NONE) {
151 strategyTree.upgradeIfPossible();
155 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
156 LOG.trace("Resolving modification apply strategy for {}", path);
159 return StoreTreeNodes.findNodeChecked(getStrategy(), path);
162 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
166 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
168 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
169 * ending with an empty one, as we will throw the exception below. This fact could end up
170 * being a problem, as we'd have bunch of phantom operations.
172 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
175 ModificationApplyOperation operation = getStrategy();
176 ModifiedNode modification = rootNode;
179 for (final PathArgument pathArg : path.getPathArguments()) {
180 final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
181 if (!potential.isPresent()) {
182 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
183 path.getAncestor(depth)));
185 operation = potential.get();
188 modification = modification.modifyChild(pathArg, operation, version);
191 return OperationWithModification.from(operation, modification);
194 private void checkSealed() {
195 checkState(!isSealed(), "Data Tree is sealed. No further modifications allowed.");
199 public String toString() {
200 return "MutableDataTree [modification=" + rootNode + "]";
204 public InMemoryDataTreeModification newModification() {
205 checkState(isSealed(), "Attempted to chain on an unsealed modification");
207 if (rootNode.getOperation() == LogicalOperation.NONE) {
208 // Simple fast case: just use the underlying modification
209 return snapshot.newModification();
213 * We will use preallocated version, this means returned snapshot will
214 * have same version each time this method is called.
216 final TreeNode originalSnapshotRoot = snapshot.getRootNode();
217 final Optional<? extends TreeNode> tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot),
219 checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
221 final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(),
222 tempRoot.get(), strategyTree);
223 return tempTree.newModification();
226 Version getVersion() {
231 // a quick check, synchronizes *only* on the sealed field
232 return (int) SEALED.getAcquire(this) != 0;
235 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
236 final Collection<ModifiedNode> children = node.getChildren();
237 if (!children.isEmpty()) {
238 cursor.enter(node.getIdentifier());
239 for (final ModifiedNode child : children) {
240 applyNode(cursor, child);
246 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
247 switch (node.getOperation()) {
251 cursor.delete(node.getIdentifier());
254 cursor.merge(node.getIdentifier(), node.getWrittenValue());
255 applyChildren(cursor, node);
258 // TODO: we could improve efficiency of cursor use if we could understand
259 // nested TOUCH operations. One way of achieving that would be a proxy
260 // cursor, which would keep track of consecutive enter and exit calls
261 // and coalesce them.
262 applyChildren(cursor, node);
265 cursor.write(node.getIdentifier(), node.getWrittenValue());
266 applyChildren(cursor, node);
269 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
274 public void applyToCursor(final DataTreeModificationCursor cursor) {
275 for (final ModifiedNode child : rootNode.getChildren()) {
276 applyNode(cursor, child);
280 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
281 checkArgument(arg.equals(data.getIdentifier()),
282 "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
285 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
286 final NormalizedNode<?, ?> data) {
287 final PathArgument arg;
289 if (!path.isEmpty()) {
290 arg = path.getLastPathArgument();
291 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
293 arg = rootNode.getIdentifier();
296 checkIdentifierReferencesData(arg, data);
300 public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
301 final OperationWithModification op = resolveModificationFor(path);
302 return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
306 public void ready() {
307 // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before
308 // for everything, including whatever user code works.
309 final boolean wasRunning = SEALED.compareAndSet(this, 0, 1);
310 checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
312 AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, getStrategy());
314 current = current.process(version);
315 } while (current != null);