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.tree.impl;
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.Optional;
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.StoreTreeNodes;
22 import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
23 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModificationCursor;
24 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
25 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
26 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
27 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
28 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
33 EffectiveModelContextProvider {
34 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
36 private final RootApplyStrategy strategyTree;
37 private final InMemoryDataTreeSnapshot snapshot;
38 private final ModifiedNode rootNode;
39 private final Version version;
41 private static final VarHandle SEALED;
45 SEALED = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "sealed", int.class);
46 } catch (NoSuchFieldException | IllegalAccessException e) {
47 throw new ExceptionInInitializerError(e);
51 // All access needs to go through this handle
52 @SuppressWarnings("unused")
53 private volatile int sealed;
55 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
56 final RootApplyStrategy resolver) {
57 this.snapshot = requireNonNull(snapshot);
58 strategyTree = requireNonNull(resolver).snapshot();
59 rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
62 * We could allocate version beforehand, since Version contract
63 * states two allocated version must be always different.
65 * Preallocating version simplifies scenarios such as
66 * chaining of modifications, since version for particular
67 * node in modification and in data tree (if successfully
68 * committed) will be same and will not change.
70 version = snapshot.getRootNode().getSubtreeVersion().next();
73 ModifiedNode getRootModification() {
77 ModificationApplyOperation getStrategy() {
78 final var ret = strategyTree.delegate();
80 throw new IllegalStateException("Schema Context is not available.");
86 public EffectiveModelContext getEffectiveModelContext() {
87 return snapshot.getEffectiveModelContext();
91 public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
93 checkIdentifierReferencesData(path, data);
94 resolveModificationFor(path).write(data);
98 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
100 checkIdentifierReferencesData(path, data);
101 resolveModificationFor(path).merge(data, version);
105 public void delete(final YangInstanceIdentifier path) {
107 resolveModificationFor(path).delete();
111 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
113 * Walk the tree from the top, looking for the first node between root and
114 * the requested path which has been modified. If no such node exists,
115 * we use the node itself.
117 final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
118 input -> switch (input.getOperation()) {
119 case DELETE, MERGE, WRITE -> true;
120 case TOUCH, NONE -> false;
122 final var terminalPath = terminal.getKey();
124 final var result = resolveSnapshot(terminalPath, terminal.getValue());
125 if (result.isPresent()) {
126 final var data = result.orElseThrow().getData();
127 return NormalizedNodes.findNode(terminalPath, 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 var potentialSnapshot = modification.getSnapshot();
137 if (potentialSnapshot != null) {
138 return potentialSnapshot;
142 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
143 } catch (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 var operation = getStrategy();
176 var modification = rootNode;
179 for (var pathArg : path.getPathArguments()) {
180 operation = operation.childByArg(pathArg);
181 if (operation == null) {
182 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
183 path.getAncestor(depth)));
187 modification = modification.modifyChild(pathArg, operation, version);
190 return OperationWithModification.from(operation, modification);
194 public String toString() {
195 return "MutableDataTree [modification=" + rootNode + "]";
199 public InMemoryDataTreeModification newModification() {
200 checkState(isSealed(), "Attempted to chain on an unsealed modification");
202 if (rootNode.getOperation() == LogicalOperation.NONE) {
203 // Simple fast case: just use the underlying modification
204 return snapshot.newModification();
208 * We will use preallocated version, this means returned snapshot will
209 * have same version each time this method is called.
211 final var originalSnapshotRoot = snapshot.getRootNode();
212 final var tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
213 checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
215 final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
217 return tempTree.newModification();
220 Version getVersion() {
225 // a quick check, synchronizes *only* on the sealed field
226 return (int) SEALED.getAcquire(this) != 0;
229 private void checkOpen() {
231 throw new IllegalStateException("Data Tree is sealed. No further modifications allowed.");
235 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
236 if (!node.isEmpty()) {
237 cursor.enter(node.getIdentifier());
238 for (var child : node.getChildren()) {
239 applyNode(cursor, child);
245 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
246 final var operation = node.getOperation();
251 case DELETE -> cursor.delete(node.getIdentifier());
253 cursor.merge(node.getIdentifier(), node.getWrittenValue());
254 applyChildren(cursor, node);
257 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
258 // way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
259 // exit calls and coalesce them.
260 applyChildren(cursor, node);
263 cursor.write(node.getIdentifier(), node.getWrittenValue());
264 applyChildren(cursor, node);
266 default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
271 public void applyToCursor(final DataTreeModificationCursor cursor) {
272 for (var child : rootNode.getChildren()) {
273 applyNode(cursor, child);
277 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
278 final var dataName = data.name();
279 checkArgument(arg.equals(dataName),
280 "Instance identifier references %s but data identifier is %s", arg, dataName);
283 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
284 final NormalizedNode data) {
285 final PathArgument arg;
286 if (!path.isEmpty()) {
287 arg = path.getLastPathArgument();
288 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
290 arg = rootNode.getIdentifier();
293 checkIdentifierReferencesData(arg, data);
297 public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
298 final var op = resolveModificationFor(path);
299 return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
303 public void ready() {
304 // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
305 // including whatever user code works.
306 if (!SEALED.compareAndSet(this, 0, 1)) {
307 throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
310 var current = AbstractReadyIterator.create(rootNode, getStrategy());
312 current = current.process(version);
313 } while (current != null);
315 // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
316 // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
317 // only the equivalent of an acquireFence()
318 VarHandle.releaseFence();