Refactor ModificationApplyOperation
[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.original(), 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         return new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(),
217             getStrategy().apply(rootNode, originalSnapshotRoot, version)
218                 .orElseThrow(() -> new IllegalStateException(
219                     "Data tree root is not present, possibly removed by previous modification")), strategyTree)
220             .newModification();
221     }
222
223     Version getVersion() {
224         return version;
225     }
226
227     boolean isSealed() {
228         // a quick check, synchronizes *only* on the sealed field
229         return (byte) STATE.getAcquire(this) == STATE_SEALED;
230     }
231
232     private void checkOpen() {
233         final var local = (byte) STATE.getAcquire(this);
234         if (local != STATE_OPEN) {
235             throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
236         }
237     }
238
239     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
240         if (!node.isEmpty()) {
241             cursor.enter(node.getIdentifier());
242             for (var child : node.getChildren()) {
243                 applyNode(cursor, child);
244             }
245             cursor.exit();
246         }
247     }
248
249     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
250         final var operation = node.getOperation();
251         switch (operation) {
252             case NONE -> {
253                 // No-op
254             }
255             case DELETE -> cursor.delete(node.getIdentifier());
256             case MERGE -> {
257                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
258                 applyChildren(cursor, node);
259             }
260             case TOUCH -> {
261                 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
262                 //       way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
263                 //       exit calls and coalesce them.
264                 applyChildren(cursor, node);
265             }
266             case WRITE -> {
267                 cursor.write(node.getIdentifier(), node.getWrittenValue());
268                 applyChildren(cursor, node);
269             }
270             default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
271         }
272     }
273
274     @Override
275     public void applyToCursor(final DataTreeModificationCursor cursor) {
276         for (var child : rootNode.getChildren()) {
277             applyNode(cursor, child);
278         }
279     }
280
281     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
282         final var dataName = data.name();
283         checkArgument(arg.equals(dataName),
284             "Instance identifier references %s but data identifier is %s", arg, dataName);
285     }
286
287     private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
288             final NormalizedNode data) {
289         final PathArgument arg;
290         if (!path.isEmpty()) {
291             arg = path.getLastPathArgument();
292             checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
293         } else {
294             arg = rootNode.getIdentifier();
295         }
296
297         checkIdentifierReferencesData(arg, data);
298     }
299
300     @Override
301     public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
302         final var op = resolveModificationFor(path);
303         return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
304     }
305
306     @Override
307     public void ready() {
308         // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
309         // including whatever user code works.
310         if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
311             throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
312         }
313
314         var current = AbstractReadyIterator.create(rootNode, getStrategy());
315         do {
316             current = current.process(version);
317         } while (current != null);
318
319         // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
320         // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
321         // only the equivalent of an acquireFence()
322         STATE.setRelease(this, STATE_SEALED);
323     }
324 }