Bump odlparent to 13.0.9
[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.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
35         EffectiveModelContextProvider {
36     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
37
38     private static final byte STATE_OPEN    = 0;
39     private static final byte STATE_SEALING = 1;
40     private static final byte STATE_SEALED  = 2;
41
42     private static final VarHandle STATE;
43
44     static {
45         try {
46             STATE = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "state", byte.class);
47         } catch (NoSuchFieldException | IllegalAccessException e) {
48             throw new ExceptionInInitializerError(e);
49         }
50     }
51
52     private final RootApplyStrategy strategyTree;
53     private final InMemoryDataTreeSnapshot snapshot;
54     private final ModifiedNode rootNode;
55     private final Version version;
56
57     // All access needs to go through STATE
58     @SuppressWarnings("unused")
59     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
60     private volatile byte state;
61
62     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
63             final RootApplyStrategy resolver) {
64         this.snapshot = requireNonNull(snapshot);
65         strategyTree = requireNonNull(resolver).snapshot();
66         rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
67
68         /*
69          * We could allocate version beforehand, since Version contract
70          * states two allocated version must be always different.
71          *
72          * Preallocating version simplifies scenarios such as
73          * chaining of modifications, since version for particular
74          * node in modification and in data tree (if successfully
75          * committed) will be same and will not change.
76          */
77         version = snapshot.getRootNode().getSubtreeVersion().next();
78     }
79
80     ModifiedNode getRootModification() {
81         return rootNode;
82     }
83
84     ModificationApplyOperation getStrategy() {
85         final var ret = strategyTree.delegate();
86         if (ret == null) {
87             throw new IllegalStateException("Schema Context is not available.");
88         }
89         return ret;
90     }
91
92     @Override
93     public EffectiveModelContext getEffectiveModelContext() {
94         return snapshot.getEffectiveModelContext();
95     }
96
97     @Override
98     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
99         checkOpen();
100         checkIdentifierReferencesData(path, data);
101         resolveModificationFor(path).write(data);
102     }
103
104     @Override
105     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
106         checkOpen();
107         checkIdentifierReferencesData(path, data);
108         resolveModificationFor(path).merge(data, version);
109     }
110
111     @Override
112     public void delete(final YangInstanceIdentifier path) {
113         checkOpen();
114         resolveModificationFor(path).delete();
115     }
116
117     @Override
118     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
119         /*
120          * Walk the tree from the top, looking for the first node between root and
121          * the requested path which has been modified. If no such node exists,
122          * we use the node itself.
123          */
124         final var terminal = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path,
125             input -> switch (input.getOperation()) {
126                 case DELETE, MERGE, WRITE -> true;
127                 case TOUCH, NONE -> false;
128             });
129         final var terminalPath = terminal.getKey();
130
131         final var result = resolveSnapshot(terminalPath, terminal.getValue());
132         return result == null ? Optional.empty() : NormalizedNodes.findNode(terminalPath, result.getData(), path);
133     }
134
135     @SuppressWarnings("checkstyle:illegalCatch")
136     private @Nullable TreeNode resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
137         final var potentialSnapshot = modification.getSnapshot();
138         if (potentialSnapshot != null) {
139             return potentialSnapshot.orElse(null);
140         }
141
142         try {
143             return resolveModificationStrategy(path).apply(modification, modification.original(), version);
144         } catch (Exception e) {
145             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
146             throw e;
147         }
148     }
149
150     void upgradeIfPossible() {
151         if (rootNode.getOperation() == LogicalOperation.NONE) {
152             strategyTree.upgradeIfPossible();
153         }
154     }
155
156     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
157         LOG.trace("Resolving modification apply strategy for {}", path);
158
159         upgradeIfPossible();
160         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
161     }
162
163     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
164         upgradeIfPossible();
165
166         /*
167          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
168          *
169          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
170          * ending with an empty one, as we will throw the exception below. This fact could end up
171          * being a problem, as we'd have bunch of phantom operations.
172          *
173          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
174          * process.
175          */
176         var operation = getStrategy();
177         var modification = rootNode;
178
179         int depth = 1;
180         for (var pathArg : path.getPathArguments()) {
181             operation = operation.childByArg(pathArg);
182             if (operation == null) {
183                 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
184                         path.getAncestor(depth)));
185             }
186             ++depth;
187
188             modification = modification.modifyChild(pathArg, operation, version);
189         }
190
191         return OperationWithModification.from(operation, modification);
192     }
193
194     @Override
195     public String toString() {
196         return "MutableDataTree [modification=" + rootNode + "]";
197     }
198
199     @Override
200     public InMemoryDataTreeModification newModification() {
201         checkState(isSealed(), "Attempted to chain on an unsealed modification");
202
203         if (rootNode.getOperation() == LogicalOperation.NONE) {
204             // Simple fast case: just use the underlying modification
205             return snapshot.newModification();
206         }
207
208         /*
209          * We will use preallocated version, this means returned snapshot will
210          * have same version each time this method is called.
211          */
212         final var originalSnapshotRoot = snapshot.getRootNode();
213         final var newRoot = getStrategy().apply(rootNode, originalSnapshotRoot, version);
214         if (newRoot == null) {
215             throw new IllegalStateException("Data tree root is not present, possibly removed by previous modification");
216         }
217         return new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(), newRoot, strategyTree)
218             .newModification();
219     }
220
221     Version getVersion() {
222         return version;
223     }
224
225     boolean isSealed() {
226         // a quick check, synchronizes *only* on the sealed field
227         return (byte) STATE.getAcquire(this) == STATE_SEALED;
228     }
229
230     private void checkOpen() {
231         final var local = (byte) STATE.getAcquire(this);
232         if (local != STATE_OPEN) {
233             throw new IllegalStateException("Data Tree is sealed. No further modifications allowed in state " + local);
234         }
235     }
236
237     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
238         if (!node.isEmpty()) {
239             cursor.enter(node.getIdentifier());
240             for (var child : node.getChildren()) {
241                 applyNode(cursor, child);
242             }
243             cursor.exit();
244         }
245     }
246
247     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
248         final var operation = node.getOperation();
249         switch (operation) {
250             case NONE -> {
251                 // No-op
252             }
253             case DELETE -> cursor.delete(node.getIdentifier());
254             case MERGE -> {
255                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
256                 applyChildren(cursor, node);
257             }
258             case TOUCH -> {
259                 // TODO: we could improve efficiency of cursor use if we could understand nested TOUCH operations. One
260                 //       way of achieving that would be a proxy cursor, which would keep track of consecutive enter and
261                 //       exit calls and coalesce them.
262                 applyChildren(cursor, node);
263             }
264             case WRITE -> {
265                 cursor.write(node.getIdentifier(), node.getWrittenValue());
266                 applyChildren(cursor, node);
267             }
268             default -> throw new IllegalArgumentException("Unhandled node operation " + operation);
269         }
270     }
271
272     @Override
273     public void applyToCursor(final DataTreeModificationCursor cursor) {
274         for (var child : rootNode.getChildren()) {
275             applyNode(cursor, child);
276         }
277     }
278
279     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
280         final var dataName = data.name();
281         checkArgument(arg.equals(dataName),
282             "Instance identifier references %s but data identifier is %s", arg, dataName);
283     }
284
285     private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
286             final NormalizedNode data) {
287         final PathArgument arg;
288         if (!path.isEmpty()) {
289             arg = path.getLastPathArgument();
290             checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
291         } else {
292             arg = rootNode.getIdentifier();
293         }
294
295         checkIdentifierReferencesData(arg, data);
296     }
297
298     @Override
299     public Optional<DataTreeModificationCursor> openCursor(final YangInstanceIdentifier path) {
300         final var op = resolveModificationFor(path);
301         return Optional.of(openCursor(new InMemoryDataTreeModificationCursor(this, path, op)));
302     }
303
304     @Override
305     public void ready() {
306         // We want a full CAS with setVolatile() memory semantics, as we want to force happen-before for everything,
307         // including whatever user code works.
308         if (!STATE.compareAndSet(this, STATE_OPEN, STATE_SEALING)) {
309             throw new IllegalStateException("Attempted to seal an already-sealed Data Tree.");
310         }
311
312         var current = AbstractReadyIterator.create(rootNode, getStrategy());
313         do {
314             current = current.process(version);
315         } while (current != null);
316
317         // Make sure all affects are visible before returning, as this object may be handed off to another thread, which
318         // needs to see any HashMap.modCount mutations completed. This is needed because isSealed() is now performing
319         // only the equivalent of an acquireFence()
320         STATE.setRelease(this, STATE_SEALED);
321     }
322 }