5d1012f5c80de06356ec7cd24e66990545a2f187
[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.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
23 import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
24 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModificationCursor;
25 import org.opendaylight.yangtools.yang.data.tree.api.SchemaValidationFailedException;
26 import org.opendaylight.yangtools.yang.data.tree.impl.node.TreeNode;
27 import org.opendaylight.yangtools.yang.data.tree.impl.node.Version;
28 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
29 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
34         EffectiveModelContextProvider {
35     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
36
37     private static final byte STATE_OPEN    = 0;
38     private static final byte STATE_SEALING = 1;
39     private static final byte STATE_SEALED  = 2;
40
41     private static final VarHandle STATE;
42
43     static {
44         try {
45             STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
46         } catch (NoSuchFieldException | IllegalAccessException e) {
47             throw new ExceptionInInitializerError(e);
48         }
49     }
50
51     private final RootApplyStrategy strategyTree;
52     private final InMemoryDataTreeSnapshot snapshot;
53     private final ModifiedNode rootNode;
54     private final Version version;
55
56     // All access needs to go through STATE
57     @SuppressWarnings("unused")
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 getEffectiveModelContext() {
92         return snapshot.getEffectiveModelContext();
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.getEffectiveModelContext(), newRoot, strategyTree)
216             .newModification();
217     }
218
219     Version getVersion() {
220         return version;
221     }
222
223     boolean isSealed() {
224         // a quick check, synchronizes *only* on the sealed field
225         return (byte) STATE.getAcquire(this) == STATE_SEALED;
226     }
227
228     private void checkOpen() {
229         final var local = (byte) STATE.getAcquire(this);
230         if (local != STATE_OPEN) {
231             throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
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 for everything,
305         // including whatever user code works.
306         if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
307             throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
308         }
309
310         var current = AbstractReadyIterator.create(rootNode, getStrategy());
311         do {
312             current = current.process(version);
313         } while (current != null);
314
315         // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
316         // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
317         // only the equivalent of an acquireFence()
318         STATE.setRelease(this, STATE_SEALED);
319     }
320 }