Clean up checkSealed()
[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         checkOpen();
93         checkIdentifierReferencesData(path, data);
94         resolveModificationFor(path).write(data);
95     }
96
97     @Override
98     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
99         checkOpen();
100         checkIdentifierReferencesData(path, data);
101         resolveModificationFor(path).merge(data, version);
102     }
103
104     @Override
105     public void delete(final YangInstanceIdentifier path) {
106         checkOpen();
107         resolveModificationFor(path).delete();
108     }
109
110     @Override
111     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
112         /*
113          * Walk the tree from the top, looking for the first node between root and
114          * the requested path which has been modified. If no such node exists,
115          * we use the node itself.
116          */
117         final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
118             input -> switch (input.getOperation()) {
119                 case DELETE, MERGE, WRITE -> true;
120                 case TOUCH, NONE -> false;
121             });
122         final var terminalPath = terminal.getKey();
123
124         final var result = resolveSnapshot(terminalPath, terminal.getValue());
125         if (result.isPresent()) {
126             final var data = result.orElseThrow().getData();
127             return NormalizedNodes.findNode(terminalPath, data, path);
128         }
129
130         return Optional.empty();
131     }
132
133     @SuppressWarnings("checkstyle:illegalCatch")
134     private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
135             final ModifiedNode modification) {
136         final var potentialSnapshot = modification.getSnapshot();
137         if (potentialSnapshot != null) {
138             return potentialSnapshot;
139         }
140
141         try {
142             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
143         } catch (Exception e) {
144             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
145             throw e;
146         }
147     }
148
149     void upgradeIfPossible() {
150         if (rootNode.getOperation() == LogicalOperation.NONE) {
151             strategyTree.upgradeIfPossible();
152         }
153     }
154
155     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
156         LOG.trace("Resolving modification apply strategy for {}", path);
157
158         upgradeIfPossible();
159         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
160     }
161
162     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
163         upgradeIfPossible();
164
165         /*
166          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
167          *
168          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
169          * ending with an empty one, as we will throw the exception below. This fact could end up
170          * being a problem, as we'd have bunch of phantom operations.
171          *
172          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
173          * process.
174          */
175         var operation = getStrategy();
176         var modification = rootNode;
177
178         int depth = 1;
179         for (var pathArg : path.getPathArguments()) {
180             operation = operation.childByArg(pathArg);
181             if (operation == null) {
182                 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
183                         path.getAncestor(depth)));
184             }
185             ++depth;
186
187             modification = modification.modifyChild(pathArg, operation, version);
188         }
189
190         return OperationWithModification.from(operation, modification);
191     }
192
193     @Override
194     public String toString() {
195         return "MutableDataTree [modification=" + rootNode + "]";
196     }
197
198     @Override
199     public InMemoryDataTreeModification newModification() {
200         checkState(isSealed(), "Attempted to chain on an unsealed modification");
201
202         if (rootNode.getOperation() == LogicalOperation.NONE) {
203             // Simple fast case: just use the underlying modification
204             return snapshot.newModification();
205         }
206
207         /*
208          * We will use preallocated version, this means returned snapshot will
209          * have same version each time this method is called.
210          */
211         final var originalSnapshotRoot = snapshot.getRootNode();
212         final var tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot), version);
213         checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
214
215         final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
216             strategyTree);
217         return tempTree.newModification();
218     }
219
220     Version getVersion() {
221         return version;
222     }
223
224     boolean isSealed() {
225         // a quick check, synchronizes *only* on the sealed field
226         return (int) SEALED.getAcquire(this) != 0;
227     }
228
229     private void checkOpen() {
230         if (isSealed()) {
231             throw new IllegalStateException("Data Tree is sealed. No further modifications allowed.");
232         }
233     }
234
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);
240             }
241             cursor.exit();
242         }
243     }
244
245     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
246         final var operation = node.getOperation();
247         switch (operation) {
248             case NONE -> {
249                 // No-op
250             }
251             case DELETE -> cursor.delete(node.getIdentifier());
252             case MERGE -> {
253                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
254                 applyChildren(cursor, node);
255             }
256             case TOUCH -> {
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);
261             }
262             case WRITE -> {
263                 cursor.write(node.getIdentifier(), node.getWrittenValue());
264                 applyChildren(cursor, node);
265             }
266             default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
267         }
268     }
269
270     @Override
271     public void applyToCursor(final DataTreeModificationCursor cursor) {
272         for (var child : rootNode.getChildren()) {
273             applyNode(cursor, child);
274         }
275     }
276
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);
281     }
282
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);
289         } else {
290             arg = rootNode.getIdentifier();
291         }
292
293         checkIdentifierReferencesData(arg, data);
294     }
295
296     @Override
297     public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
298         final var op = resolveModificationFor(path);
299         return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
300     }
301
302     @Override
303     public void ready() {
304         // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before
305         // for everything, including whatever user code works.
306         final boolean wasRunning = SEALED.compareAndSet(this, 0, 1);
307         checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
308
309         var current = AbstractReadyIterator.create(rootNode, getStrategy());
310         do {
311             current = current.process(version);
312         } while (current != null);
313     }
314 }