Move ModifiedNode.IS_TERMINAL_PREDICATE
[yangtools.git] / data / yang-data-tree-ri / src / main / java / org / opendaylight / yangtools / yang / data / tree / impl / InMemoryDataTreeModification.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.tree.impl;
9
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;
13
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;
31
32 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
33         EffectiveModelContextProvider {
34     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
35
36     private final RootApplyStrategy strategyTree;
37     private final InMemoryDataTreeSnapshot snapshot;
38     private final ModifiedNode rootNode;
39     private final Version version;
40
41     private static final VarHandle SEALED;
42
43     static {
44         try {
45             SEALED = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "sealed", int.class);
46         } catch (NoSuchFieldException | IllegalAccessException e) {
47             throw new ExceptionInInitializerError(e);
48         }
49     }
50
51     // All access needs to go through this handle
52     @SuppressWarnings("unused")
53     private volatile int sealed;
54
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());
60
61         /*
62          * We could allocate version beforehand, since Version contract
63          * states two allocated version must be always different.
64          *
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.
69          */
70         version = snapshot.getRootNode().getSubtreeVersion().next();
71     }
72
73     ModifiedNode getRootModification() {
74         return rootNode;
75     }
76
77     ModificationApplyOperation getStrategy() {
78         final var ret = strategyTree.delegate();
79         if (ret == null) {
80             throw new IllegalStateException("Schema Context is not available.");
81         }
82         return ret;
83     }
84
85     @Override
86     public EffectiveModelContext getEffectiveModelContext() {
87         return snapshot.getEffectiveModelContext();
88     }
89
90     @Override
91     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
92         checkSealed();
93         checkIdentifierReferencesData(path, data);
94         resolveModificationFor(path).write(data);
95     }
96
97     @Override
98     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
99         checkSealed();
100         checkIdentifierReferencesData(path, data);
101         resolveModificationFor(path).merge(data, version);
102     }
103
104     @Override
105     public void delete(final YangInstanceIdentifier path) {
106         checkSealed();
107
108         resolveModificationFor(path).delete();
109     }
110
111     @Override
112     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
113         /*
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.
117          */
118         final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
119             input -> switch (input.getOperation()) {
120                 case DELETE, MERGE, WRITE -> true;
121                 case TOUCH, NONE -> false;
122             });
123         final var terminalPath = terminal.getKey();
124
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);
129         }
130
131         return Optional.empty();
132     }
133
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;
140         }
141
142         try {
143             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
144         } catch (Exception e) {
145             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
146             throw e;
147         }
148     }
149
150     void upgradeIfPossible() {
151         if (rootNode.getOperation() == LogicalOperation.NONE) {
152             strategyTree.upgradeIfPossible();
153         }
154     }
155
156     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
157         LOG.trace("Resolving modification apply strategy for {}", path);
158
159         upgradeIfPossible();
160         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
161     }
162
163     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
164         upgradeIfPossible();
165
166         /*
167          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
168          *
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.
172          *
173          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
174          * process.
175          */
176         var operation = getStrategy();
177         var modification = rootNode;
178
179         int depth = 1;
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)));
185             }
186             ++depth;
187
188             modification = modification.modifyChild(pathArg, operation, version);
189         }
190
191         return OperationWithModification.from(operation, modification);
192     }
193
194     private void checkSealed() {
195         checkState(!isSealed(), "Data Tree is sealed. No further modifications allowed.");
196     }
197
198     @Override
199     public String toString() {
200         return "MutableDataTree [modification=" + rootNode + "]";
201     }
202
203     @Override
204     public InMemoryDataTreeModification newModification() {
205         checkState(isSealed(), "Attempted to chain on an unsealed modification");
206
207         if (rootNode.getOperation() == LogicalOperation.NONE) {
208             // Simple fast case: just use the underlying modification
209             return snapshot.newModification();
210         }
211
212         /*
213          * We will use preallocated version, this means returned snapshot will
214          * have same version each time this method is called.
215          */
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");
219
220         final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
221             strategyTree);
222         return tempTree.newModification();
223     }
224
225     Version getVersion() {
226         return version;
227     }
228
229     boolean isSealed() {
230         // a quick check, synchronizes *only* on the sealed field
231         return (int) SEALED.getAcquire(this) != 0;
232     }
233
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);
239             }
240             cursor.exit();
241         }
242     }
243
244     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
245         final var operation = node.getOperation();
246         switch (operation) {
247             case NONE -> {
248                 // No-op
249             }
250             case DELETE -> cursor.delete(node.getIdentifier());
251             case MERGE -> {
252                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
253                 applyChildren(cursor, node);
254             }
255             case TOUCH -> {
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);
260             }
261             case WRITE -> {
262                 cursor.write(node.getIdentifier(), node.getWrittenValue());
263                 applyChildren(cursor, node);
264             }
265             default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
266         }
267     }
268
269     @Override
270     public void applyToCursor(final DataTreeModificationCursor cursor) {
271         for (var child : rootNode.getChildren()) {
272             applyNode(cursor, child);
273         }
274     }
275
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);
280     }
281
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);
288         } else {
289             arg = rootNode.getIdentifier();
290         }
291
292         checkIdentifierReferencesData(arg, data);
293     }
294
295     @Override
296     public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
297         final var op = resolveModificationFor(path);
298         return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
299     }
300
301     @Override
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.");
307
308         var current = AbstractReadyIterator.create(rootNode, getStrategy());
309         do {
310             current = current.process(version);
311         } while (current != null);
312     }
313 }