Remove EffectiveModelContext{Listener,Provider}
[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 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.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
34     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
35
36     private static final byte STATE_OPEN    = 0;
37     private static final byte STATE_SEALING = 1;
38     private static final byte STATE_SEALED  = 2;
39
40     private static final VarHandle STATE;
41
42     static {
43         try {
44             STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
45         } catch (NoSuchFieldException | IllegalAccessException e) {
46             throw new ExceptionInInitializerError(e);
47         }
48     }
49
50     private final RootApplyStrategy strategyTree;
51     private final InMemoryDataTreeSnapshot snapshot;
52     private final ModifiedNode rootNode;
53     private final Version version;
54
55     // All access needs to go through STATE
56     @SuppressWarnings("unused")
57     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
58     private volatile byte state;
59
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());
65
66         /*
67          * We could allocate version beforehand, since Version contract
68          * states two allocated version must be always different.
69          *
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.
74          */
75         version = snapshot.getRootNode().getSubtreeVersion().next();
76     }
77
78     ModifiedNode getRootModification() {
79         return rootNode;
80     }
81
82     ModificationApplyOperation getStrategy() {
83         final var ret = strategyTree.delegate();
84         if (ret == null) {
85             throw new IllegalStateException("Schema Context is not available.");
86         }
87         return ret;
88     }
89
90     @Override
91     public EffectiveModelContext modelContext() {
92         return snapshot.modelContext();
93     }
94
95     @Override
96     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
97         checkOpen();
98         checkIdentifierReferencesData(path, data);
99         resolveModificationFor(path).write(data);
100     }
101
102     @Override
103     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
104         checkOpen();
105         checkIdentifierReferencesData(path, data);
106         resolveModificationFor(path).merge(data, version);
107     }
108
109     @Override
110     public void delete(final YangInstanceIdentifier path) {
111         checkOpen();
112         resolveModificationFor(path).delete();
113     }
114
115     @Override
116     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
117         /*
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.
121          */
122         final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
123             input -> switch (input.getOperation()) {
124                 case DELETE, MERGE, WRITE -> true;
125                 case TOUCH, NONE -> false;
126             });
127         final var terminalPath = terminal.getKey();
128
129         final var result = resolveSnapshot(terminalPath, terminal.getValue());
130         return result == null ? Optional.empty() : NormalizedNodes.findNode(terminalPath, result.getData(), path);
131     }
132
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);
138         }
139
140         try {
141             return resolveModificationStrategy(path).apply(modification, modification.original(), version);
142         } catch (Exception e) {
143             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
144             throw e;
145         }
146     }
147
148     void upgradeIfPossible() {
149         if (rootNode.getOperation() == LogicalOperation.NONE) {
150             strategyTree.upgradeIfPossible();
151         }
152     }
153
154     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
155         LOG.trace("Resolving modification apply strategy for {}", path);
156
157         upgradeIfPossible();
158         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
159     }
160
161     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
162         upgradeIfPossible();
163
164         /*
165          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
166          *
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.
170          *
171          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
172          * process.
173          */
174         var operation = getStrategy();
175         var modification = rootNode;
176
177         int depth = 1;
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)));
183             }
184             ++depth;
185
186             modification = modification.modifyChild(pathArg, operation, version);
187         }
188
189         return OperationWithModification.from(operation, modification);
190     }
191
192     @Override
193     public String toString() {
194         return "MutableDataTree [modification=" + rootNode + "]";
195     }
196
197     @Override
198     public InMemoryDataTreeModification newModification() {
199         checkState(isSealed(), "Attempted to chain on an unsealed modification");
200
201         if (rootNode.getOperation() == LogicalOperation.NONE) {
202             // Simple fast case: just use the underlying modification
203             return snapshot.newModification();
204         }
205
206         /*
207          * We will use preallocated version, this means returned snapshot will
208          * have same version each time this method is called.
209          */
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");
214         }
215         return new InMemoryDataTreeSnapshot(snapshot.modelContext(), newRoot, strategyTree).newModification();
216     }
217
218     Version getVersion() {
219         return version;
220     }
221
222     boolean isSealed() {
223         // a quick check, synchronizes *only* on the sealed field
224         return (byte) STATE.getAcquire(this) == STATE_SEALED;
225     }
226
227     private void checkOpen() {
228         final var local = (byte) STATE.getAcquire(this);
229         if (local != STATE_OPEN) {
230             throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
231         }
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 for everything,
304         // including whatever user code works.
305         if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
306             throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
307         }
308
309         var current = AbstractReadyIterator.create(rootNode, getStrategy());
310         do {
311             current = current.process(version);
312         } while (current != null);
313
314         // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
315         // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
316         // only the equivalent of an acquireFence()
317         STATE.setRelease(this, STATE_SEALED);
318     }
319 }