Improve InMemoryDataTreeModification state management
[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 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     private volatile byte state;
58
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());
64
65         /*
66          * We could allocate version beforehand, since Version contract
67          * states two allocated version must be always different.
68          *
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.
73          */
74         version = snapshot.getRootNode().getSubtreeVersion().next();
75     }
76
77     ModifiedNode getRootModification() {
78         return rootNode;
79     }
80
81     ModificationApplyOperation getStrategy() {
82         final var ret = strategyTree.delegate();
83         if (ret == null) {
84             throw new IllegalStateException("Schema Context is not available.");
85         }
86         return ret;
87     }
88
89     @Override
90     public EffectiveModelContext getEffectiveModelContext() {
91         return snapshot.getEffectiveModelContext();
92     }
93
94     @Override
95     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
96         checkOpen();
97         checkIdentifierReferencesData(path, data);
98         resolveModificationFor(path).write(data);
99     }
100
101     @Override
102     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
103         checkOpen();
104         checkIdentifierReferencesData(path, data);
105         resolveModificationFor(path).merge(data, version);
106     }
107
108     @Override
109     public void delete(final YangInstanceIdentifier path) {
110         checkOpen();
111         resolveModificationFor(path).delete();
112     }
113
114     @Override
115     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
116         /*
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.
120          */
121         final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
122             input -> switch (input.getOperation()) {
123                 case DELETE, MERGE, WRITE -> true;
124                 case TOUCH, NONE -> false;
125             });
126         final var terminalPath = terminal.getKey();
127
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);
132         }
133
134         return Optional.empty();
135     }
136
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;
143         }
144
145         try {
146             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
147         } catch (Exception e) {
148             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
149             throw e;
150         }
151     }
152
153     void upgradeIfPossible() {
154         if (rootNode.getOperation() == LogicalOperation.NONE) {
155             strategyTree.upgradeIfPossible();
156         }
157     }
158
159     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
160         LOG.trace("Resolving modification apply strategy for {}", path);
161
162         upgradeIfPossible();
163         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
164     }
165
166     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
167         upgradeIfPossible();
168
169         /*
170          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
171          *
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.
175          *
176          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
177          * process.
178          */
179         var operation = getStrategy();
180         var modification = rootNode;
181
182         int depth = 1;
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)));
188             }
189             ++depth;
190
191             modification = modification.modifyChild(pathArg, operation, version);
192         }
193
194         return OperationWithModification.from(operation, modification);
195     }
196
197     @Override
198     public String toString() {
199         return "MutableDataTree [modification=" + rootNode + "]";
200     }
201
202     @Override
203     public InMemoryDataTreeModification newModification() {
204         checkState(isSealed(), "Attempted to chain on an unsealed modification");
205
206         if (rootNode.getOperation() == LogicalOperation.NONE) {
207             // Simple fast case: just use the underlying modification
208             return snapshot.newModification();
209         }
210
211         /*
212          * We will use preallocated version, this means returned snapshot will
213          * have same version each time this method is called.
214          */
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");
218
219         final var tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), tempRoot.orElseThrow(),
220             strategyTree);
221         return tempTree.newModification();
222     }
223
224     Version getVersion() {
225         return version;
226     }
227
228     boolean isSealed() {
229         // a quick check, synchronizes *only* on the sealed field
230         return (byte) STATE.getAcquire(this) == STATE_SEALED;
231     }
232
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);
237         }
238     }
239
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);
245             }
246             cursor.exit();
247         }
248     }
249
250     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
251         final var operation = node.getOperation();
252         switch (operation) {
253             case NONE -> {
254                 // No-op
255             }
256             case DELETE -> cursor.delete(node.getIdentifier());
257             case MERGE -> {
258                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
259                 applyChildren(cursor, node);
260             }
261             case TOUCH -> {
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);
266             }
267             case WRITE -> {
268                 cursor.write(node.getIdentifier(), node.getWrittenValue());
269                 applyChildren(cursor, node);
270             }
271             default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
272         }
273     }
274
275     @Override
276     public void applyToCursor(final DataTreeModificationCursor cursor) {
277         for (var child : rootNode.getChildren()) {
278             applyNode(cursor, child);
279         }
280     }
281
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);
286     }
287
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);
294         } else {
295             arg = rootNode.getIdentifier();
296         }
297
298         checkIdentifierReferencesData(arg, data);
299     }
300
301     @Override
302     public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
303         final var op = resolveModificationFor(path);
304         return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
305     }
306
307     @Override
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.");
313         }
314
315         var current = AbstractReadyIterator.create(rootNode, getStrategy());
316         do {
317             current = current.process(version);
318         } while (current != null);
319
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);
324     }
325 }