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.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
23 import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
24 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModificationCursor;
25 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
26 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
27 import org.opendaylight.yangtools.yang.data.tree.impl.node.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 static final byte STATE_OPEN = 0;
38 private static final byte STATE_SEALING = 1;
39 private static final byte STATE_SEALED = 2;
41 private static final VarHandle STATE;
45 STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
46 } catch (NoSuchFieldException | IllegalAccessException e) {
47 throw new ExceptionInInitializerError(e);
51 private final RootApplyStrategy strategyTree;
52 private final InMemoryDataTreeSnapshot snapshot;
53 private final ModifiedNode rootNode;
54 private final Version version;
56 // All access needs to go through STATE
57 @SuppressWarnings("unused")
58 private volatile byte state;
60 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
61 final RootApplyStrategy resolver) {
62 this.snapshot = requireNonNull(snapshot);
63 strategyTree = requireNonNull(resolver).snapshot();
64 rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
67 * We could allocate version beforehand, since Version contract
68 * states two allocated version must be always different.
70 * Preallocating version simplifies scenarios such as
71 * chaining of modifications, since version for particular
72 * node in modification and in data tree (if successfully
73 * committed) will be same and will not change.
75 version = snapshot.getRootNode().getSubtreeVersion().next();
78 ModifiedNode getRootModification() {
82 ModificationApplyOperation getStrategy() {
83 final var ret = strategyTree.delegate();
85 throw new IllegalStateException("Schema Context is not available.");
91 public EffectiveModelContext getEffectiveModelContext() {
92 return snapshot.getEffectiveModelContext();
96 public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
98 checkIdentifierReferencesData(path, data);
99 resolveModificationFor(path).write(data);
103 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
105 checkIdentifierReferencesData(path, data);
106 resolveModificationFor(path).merge(data, version);
110 public void delete(final YangInstanceIdentifier path) {
112 resolveModificationFor(path).delete();
116 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
118 * Walk the tree from the top, looking for the first node between root and
119 * the requested path which has been modified. If no such node exists,
120 * we use the node itself.
122 final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
123 input -> switch (input.getOperation()) {
124 case DELETE, MERGE, WRITE -> true;
125 case TOUCH, NONE -> false;
127 final var terminalPath = terminal.getKey();
129 final var result = resolveSnapshot(terminalPath, terminal.getValue());
130 return result == null ? Optional.empty() : NormalizedNodes.findNode(terminalPath, result.getData(), path);
133 @SuppressWarnings("checkstyle:illegalCatch")
134 private @Nullable TreeNode resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
135 final var potentialSnapshot = modification.getSnapshot();
136 if (potentialSnapshot != null) {
137 return potentialSnapshot.orElse(null);
141 return resolveModificationStrategy(path).apply(modification, modification.original(), version);
142 } catch (Exception e) {
143 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
148 void upgradeIfPossible() {
149 if (rootNode.getOperation() == LogicalOperation.NONE) {
150 strategyTree.upgradeIfPossible();
154 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
155 LOG.trace("Resolving modification apply strategy for {}", path);
158 return StoreTreeNodes.findNodeChecked(getStrategy(), path);
161 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
165 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
167 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
168 * ending with an empty one, as we will throw the exception below. This fact could end up
169 * being a problem, as we'd have bunch of phantom operations.
171 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
174 var operation = getStrategy();
175 var modification = rootNode;
178 for (var pathArg : path.getPathArguments()) {
179 operation = operation.childByArg(pathArg);
180 if (operation == null) {
181 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
182 path.getAncestor(depth)));
186 modification = modification.modifyChild(pathArg, operation, version);
189 return OperationWithModification.from(operation, modification);
193 public String toString() {
194 return "MutableDataTree [modification=" + rootNode + "]";
198 public InMemoryDataTreeModification newModification() {
199 checkState(isSealed(), "Attempted to chain on an unsealed modification");
201 if (rootNode.getOperation() == LogicalOperation.NONE) {
202 // Simple fast case: just use the underlying modification
203 return snapshot.newModification();
207 * We will use preallocated version, this means returned snapshot will
208 * have same version each time this method is called.
210 final var originalSnapshotRoot = snapshot.getRootNode();
211 final var newRoot = getStrategy().apply(rootNode, originalSnapshotRoot, version);
212 if (newRoot == null) {
213 throw new IllegalStateException("Data tree root is not present, possibly removed by previous modification");
215 return new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), newRoot, strategyTree)
219 Version getVersion() {
224 // a quick check, synchronizes *only* on the sealed field
225 return (byte) STATE.getAcquire(this) == STATE_SEALED;
228 private void checkOpen() {
229 final var local = (byte) STATE.getAcquire(this);
230 if (local != STATE_OPEN) {
231 throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
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 (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
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 STATE.setRelease(this, STATE_SEALED);