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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
15 import java.lang.invoke.MethodHandles;
16 import java.lang.invoke.VarHandle;
17 import java.util.Optional;
18 import org.eclipse.jdt.annotation.Nullable;
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.StoreTreeNodes;
24 import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
25 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModificationCursor;
26 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
27 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
28 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
29 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
30 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
34 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
35 EffectiveModelContextProvider {
36 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
38 private static final byte STATE_OPEN = 0;
39 private static final byte STATE_SEALING = 1;
40 private static final byte STATE_SEALED = 2;
42 private static final VarHandle STATE;
46 STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
47 } catch (NoSuchFieldException | IllegalAccessException e) {
48 throw new ExceptionInInitializerError(e);
52 private final RootApplyStrategy strategyTree;
53 private final InMemoryDataTreeSnapshot snapshot;
54 private final ModifiedNode rootNode;
55 private final Version version;
57 // All access needs to go through STATE
58 @SuppressWarnings("unused")
59 @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
60 private volatile byte state;
62 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
63 final RootApplyStrategy resolver) {
64 this.snapshot = requireNonNull(snapshot);
65 strategyTree = requireNonNull(resolver).snapshot();
66 rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
69 * We could allocate version beforehand, since Version contract
70 * states two allocated version must be always different.
72 * Preallocating version simplifies scenarios such as
73 * chaining of modifications, since version for particular
74 * node in modification and in data tree (if successfully
75 * committed) will be same and will not change.
77 version = snapshot.getRootNode().getSubtreeVersion().next();
80 ModifiedNode getRootModification() {
84 ModificationApplyOperation getStrategy() {
85 final var ret = strategyTree.delegate();
87 throw new IllegalStateException("Schema Context is not available.");
93 public EffectiveModelContext getEffectiveModelContext() {
94 return snapshot.getEffectiveModelContext();
98 public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
100 checkIdentifierReferencesData(path, data);
101 resolveModificationFor(path).write(data);
105 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
107 checkIdentifierReferencesData(path, data);
108 resolveModificationFor(path).merge(data, version);
112 public void delete(final YangInstanceIdentifier path) {
114 resolveModificationFor(path).delete();
118 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
120 * Walk the tree from the top, looking for the first node between root and
121 * the requested path which has been modified. If no such node exists,
122 * we use the node itself.
124 final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
125 input -> switch (input.getOperation()) {
126 case DELETE, MERGE, WRITE -> true;
127 case TOUCH, NONE -> false;
129 final var terminalPath = terminal.getKey();
131 final var result = resolveSnapshot(terminalPath, terminal.getValue());
132 return result == null ? Optional.empty() : NormalizedNodes.findNode(terminalPath, result.getData(), path);
135 @SuppressWarnings("checkstyle:illegalCatch")
136 private @Nullable TreeNode resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
137 final var potentialSnapshot = modification.getSnapshot();
138 if (potentialSnapshot != null) {
139 return potentialSnapshot.orElse(null);
143 return resolveModificationStrategy(path).apply(modification, modification.original(), 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);
195 public String toString() {
196 return "MutableDataTree [modification=" + rootNode + "]";
200 public InMemoryDataTreeModification newModification() {
201 checkState(isSealed(), "Attempted to chain on an unsealed modification");
203 if (rootNode.getOperation() == LogicalOperation.NONE) {
204 // Simple fast case: just use the underlying modification
205 return snapshot.newModification();
209 * We will use preallocated version, this means returned snapshot will
210 * have same version each time this method is called.
212 final var originalSnapshotRoot = snapshot.getRootNode();
213 final var newRoot = getStrategy().apply(rootNode, originalSnapshotRoot, version);
214 if (newRoot == null) {
215 throw new IllegalStateException("Data tree root is not present, possibly removed by previous modification");
217 return new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), newRoot, strategyTree)
221 Version getVersion() {
226 // a quick check, synchronizes *only* on the sealed field
227 return (byte) STATE.getAcquire(this) == STATE_SEALED;
230 private void checkOpen() {
231 final var local = (byte) STATE.getAcquire(this);
232 if (local != STATE_OPEN) {
233 throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
237 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
238 if (!node.isEmpty()) {
239 cursor.enter(node.getIdentifier());
240 for (var child : node.getChildren()) {
241 applyNode(cursor, child);
247 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
248 final var operation = node.getOperation();
253 case DELETE -> cursor.delete(node.getIdentifier());
255 cursor.merge(node.getIdentifier(), node.getWrittenValue());
256 applyChildren(cursor, node);
259 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
260 // way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
261 // exit calls and coalesce them.
262 applyChildren(cursor, node);
265 cursor.write(node.getIdentifier(), node.getWrittenValue());
266 applyChildren(cursor, node);
268 default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
273 public void applyToCursor(final DataTreeModificationCursor cursor) {
274 for (var child : rootNode.getChildren()) {
275 applyNode(cursor, child);
279 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
280 final var dataName = data.name();
281 checkArgument(arg.equals(dataName),
282 "Instance identifier references %s but data identifier is %s", arg, dataName);
285 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
286 final NormalizedNode data) {
287 final PathArgument arg;
288 if (!path.isEmpty()) {
289 arg = path.getLastPathArgument();
290 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
292 arg = rootNode.getIdentifier();
295 checkIdentifierReferencesData(arg, data);
299 public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
300 final var op = resolveModificationFor(path);
301 return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
305 public void ready() {
306 // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
307 // including whatever user code works.
308 if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
309 throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
312 var current = AbstractReadyIterator.create(rootNode, getStrategy());
314 current = current.process(version);
315 } while (current != null);
317 // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
318 // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
319 // only the equivalent of an acquireFence()
320 STATE.setRelease(this, STATE_SEALED);