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) {
108 resolveModificationFor(path).delete();
112 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
114 * Walk the tree from the top, looking for the first node between root and
115 * the requested path which has been modified. If no such node exists,
116 * we use the node itself.
118 final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
119 input -> switch (input.getOperation()) {
120 case DELETE, MERGE, WRITE -> true;
121 case TOUCH, NONE -> false;
123 final var terminalPath = terminal.getKey();
125 final var result = resolveSnapshot(terminalPath, terminal.getValue());
126 if (result.isPresent()) {
127 final var data = result.orElseThrow().getData();
128 return NormalizedNodes.findNode(terminalPath, data, path);
131 return Optional.empty();
134 @SuppressWarnings("checkstyle:illegalCatch")
135 private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
136 final ModifiedNode modification) {
137 final var potentialSnapshot = modification.getSnapshot();
138 if (potentialSnapshot != null) {
139 return potentialSnapshot;
143 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
144 } catch (Exception e) {
145 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
150 void upgradeIfPossible() {
151 if (rootNode.getOperation() == LogicalOperation.NONE) {
152 strategyTree.upgradeIfPossible();
156 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
157 LOG.trace("Resolving modification apply strategy for {}", path);
160 return StoreTreeNodes.findNodeChecked(getStrategy(), path);
163 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
167 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
169 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
170 * ending with an empty one, as we will throw the exception below. This fact could end up
171 * being a problem, as we'd have bunch of phantom operations.
173 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
176 var operation = getStrategy();
177 var modification = rootNode;
180 for (var pathArg : path.getPathArguments()) {
181 operation = operation.childByArg(pathArg);
182 if (operation == null) {
183 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
184 path.getAncestor(depth)));
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 var originalSnapshotRoot = snapshot.getRootNode();
217 final var tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
218 checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
220 final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
222 return tempTree.newModification();
225 Version getVersion() {
230 // a quick check, synchronizes *only* on the sealed field
231 return (int) SEALED.getAcquire(this) != 0;
234 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
235 if (!node.isEmpty()) {
236 cursor.enter(node.getIdentifier());
237 for (var child : node.getChildren()) {
238 applyNode(cursor, child);
244 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
245 final var operation = node.getOperation();
250 case DELETE -> cursor.delete(node.getIdentifier());
252 cursor.merge(node.getIdentifier(), node.getWrittenValue());
253 applyChildren(cursor, node);
256 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
257 // way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
258 // exit calls and coalesce them.
259 applyChildren(cursor, node);
262 cursor.write(node.getIdentifier(), node.getWrittenValue());
263 applyChildren(cursor, node);
265 default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
270 public void applyToCursor(final DataTreeModificationCursor cursor) {
271 for (var child : rootNode.getChildren()) {
272 applyNode(cursor, child);
276 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
277 final var dataName = data.name();
278 checkArgument(arg.equals(dataName),
279 "Instance identifier references %s but data identifier is %s", arg, dataName);
282 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
283 final NormalizedNode data) {
284 final PathArgument arg;
285 if (!path.isEmpty()) {
286 arg = path.getLastPathArgument();
287 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
289 arg = rootNode.getIdentifier();
292 checkIdentifierReferencesData(arg, data);
296 public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
297 final var op = resolveModificationFor(path);
298 return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
302 public void ready() {
303 // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before
304 // for everything, including whatever user code works.
305 final boolean wasRunning = SEALED.compareAndSet(this, 0, 1);
306 checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
308 var current = AbstractReadyIterator.create(rootNode, getStrategy());
310 current = current.process(version);
311 } while (current != null);