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 static final byte STATE_OPEN = 0;
37 private static final byte STATE_SEALING = 1;
38 private static final byte STATE_SEALED = 2;
40 private static final VarHandle STATE;
44 STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
45 } catch (NoSuchFieldException | IllegalAccessException e) {
46 throw new ExceptionInInitializerError(e);
50 private final RootApplyStrategy strategyTree;
51 private final InMemoryDataTreeSnapshot snapshot;
52 private final ModifiedNode rootNode;
53 private final Version version;
55 // All access needs to go through STATE
56 @SuppressWarnings("unused")
57 private volatile byte state;
59 InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
60 final RootApplyStrategy resolver) {
61 this.snapshot = requireNonNull(snapshot);
62 strategyTree = requireNonNull(resolver).snapshot();
63 rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
66 * We could allocate version beforehand, since Version contract
67 * states two allocated version must be always different.
69 * Preallocating version simplifies scenarios such as
70 * chaining of modifications, since version for particular
71 * node in modification and in data tree (if successfully
72 * committed) will be same and will not change.
74 version = snapshot.getRootNode().getSubtreeVersion().next();
77 ModifiedNode getRootModification() {
81 ModificationApplyOperation getStrategy() {
82 final var ret = strategyTree.delegate();
84 throw new IllegalStateException("Schema Context is not available.");
90 public EffectiveModelContext getEffectiveModelContext() {
91 return snapshot.getEffectiveModelContext();
95 public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
97 checkIdentifierReferencesData(path, data);
98 resolveModificationFor(path).write(data);
102 public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
104 checkIdentifierReferencesData(path, data);
105 resolveModificationFor(path).merge(data, version);
109 public void delete(final YangInstanceIdentifier path) {
111 resolveModificationFor(path).delete();
115 public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
117 * Walk the tree from the top, looking for the first node between root and
118 * the requested path which has been modified. If no such node exists,
119 * we use the node itself.
121 final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
122 input -> switch (input.getOperation()) {
123 case DELETE, MERGE, WRITE -> true;
124 case TOUCH, NONE -> false;
126 final var terminalPath = terminal.getKey();
128 final var result = resolveSnapshot(terminalPath, terminal.getValue());
129 if (result.isPresent()) {
130 final var data = result.orElseThrow().getData();
131 return NormalizedNodes.findNode(terminalPath, data, path);
134 return Optional.empty();
137 @SuppressWarnings("checkstyle:illegalCatch")
138 private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
139 final ModifiedNode modification) {
140 final var potentialSnapshot = modification.getSnapshot();
141 if (potentialSnapshot != null) {
142 return potentialSnapshot;
146 return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
147 } catch (Exception e) {
148 LOG.error("Could not create snapshot for {}:{}", path, modification, e);
153 void upgradeIfPossible() {
154 if (rootNode.getOperation() == LogicalOperation.NONE) {
155 strategyTree.upgradeIfPossible();
159 private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
160 LOG.trace("Resolving modification apply strategy for {}", path);
163 return StoreTreeNodes.findNodeChecked(getStrategy(), path);
166 private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
170 * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
172 * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
173 * ending with an empty one, as we will throw the exception below. This fact could end up
174 * being a problem, as we'd have bunch of phantom operations.
176 * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
179 var operation = getStrategy();
180 var modification = rootNode;
183 for (var pathArg : path.getPathArguments()) {
184 operation = operation.childByArg(pathArg);
185 if (operation == null) {
186 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
187 path.getAncestor(depth)));
191 modification = modification.modifyChild(pathArg, operation, version);
194 return OperationWithModification.from(operation, modification);
198 public String toString() {
199 return "MutableDataTree [modification=" + rootNode + "]";
203 public InMemoryDataTreeModification newModification() {
204 checkState(isSealed(), "Attempted to chain on an unsealed modification");
206 if (rootNode.getOperation() == LogicalOperation.NONE) {
207 // Simple fast case: just use the underlying modification
208 return snapshot.newModification();
212 * We will use preallocated version, this means returned snapshot will
213 * have same version each time this method is called.
215 final var originalSnapshotRoot = snapshot.getRootNode();
216 final var tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
217 checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
219 final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
221 return tempTree.newModification();
224 Version getVersion() {
229 // a quick check, synchronizes *only* on the sealed field
230 return (byte) STATE.getAcquire(this) == STATE_SEALED;
233 private void checkOpen() {
234 final var local = (byte) STATE.getAcquire(this);
235 if (local != STATE_OPEN) {
236 throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
240 private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
241 if (!node.isEmpty()) {
242 cursor.enter(node.getIdentifier());
243 for (var child : node.getChildren()) {
244 applyNode(cursor, child);
250 private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
251 final var operation = node.getOperation();
256 case DELETE -> cursor.delete(node.getIdentifier());
258 cursor.merge(node.getIdentifier(), node.getWrittenValue());
259 applyChildren(cursor, node);
262 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
263 // way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
264 // exit calls and coalesce them.
265 applyChildren(cursor, node);
268 cursor.write(node.getIdentifier(), node.getWrittenValue());
269 applyChildren(cursor, node);
271 default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
276 public void applyToCursor(final DataTreeModificationCursor cursor) {
277 for (var child : rootNode.getChildren()) {
278 applyNode(cursor, child);
282 static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
283 final var dataName = data.name();
284 checkArgument(arg.equals(dataName),
285 "Instance identifier references %s but data identifier is %s", arg, dataName);
288 private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
289 final NormalizedNode data) {
290 final PathArgument arg;
291 if (!path.isEmpty()) {
292 arg = path.getLastPathArgument();
293 checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
295 arg = rootNode.getIdentifier();
298 checkIdentifierReferencesData(arg, data);
302 public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
303 final var op = resolveModificationFor(path);
304 return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
308 public void ready() {
309 // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
310 // including whatever user code works.
311 if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
312 throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
315 var current = AbstractReadyIterator.create(rootNode, getStrategy());
317 current = current.process(version);
318 } while (current != null);
320 // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
321 // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
322 // only the equivalent of an acquireFence()
323 STATE.setRelease(this, STATE_SEALED);