5c6ec36e424ad3b86b3c982c16bdbaf53039c7fa
[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.Collection;
17 import java.util.Map.Entry;
18 import java.util.Optional;
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.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 final RootApplyStrategy strategyTree;
38     private final InMemoryDataTreeSnapshot snapshot;
39     private final ModifiedNode rootNode;
40     private final Version version;
41
42     private static final VarHandle SEALED;
43
44     static {
45         try {
46             SEALED = MethodHandles.lookup().findVarHandle(InMemoryDataTreeModification.class, "sealed", int.class);
47         } catch (ReflectiveOperationException e) {
48             throw new ExceptionInInitializerError(e);
49         }
50     }
51
52     // All access needs to go through this handle
53     @SuppressWarnings("unused")
54     private volatile int sealed;
55
56     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
57             final RootApplyStrategy resolver) {
58         this.snapshot = requireNonNull(snapshot);
59         this.strategyTree = requireNonNull(resolver).snapshot();
60         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), getStrategy().getChildPolicy());
61
62         /*
63          * We could allocate version beforehand, since Version contract
64          * states two allocated version must be always different.
65          *
66          * Preallocating version simplifies scenarios such as
67          * chaining of modifications, since version for particular
68          * node in modification and in data tree (if successfully
69          * committed) will be same and will not change.
70          */
71         this.version = snapshot.getRootNode().getSubtreeVersion().next();
72     }
73
74     ModifiedNode getRootModification() {
75         return rootNode;
76     }
77
78     ModificationApplyOperation getStrategy() {
79         final ModificationApplyOperation ret = strategyTree.delegate();
80         if (ret == null) {
81             throw new IllegalStateException("Schema Context is not available.");
82         }
83         return ret;
84     }
85
86     @Override
87     public EffectiveModelContext getEffectiveModelContext() {
88         return snapshot.getEffectiveModelContext();
89     }
90
91     @Override
92     public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
93         checkSealed();
94         checkIdentifierReferencesData(path, data);
95         resolveModificationFor(path).write(data);
96     }
97
98     @Override
99     public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
100         checkSealed();
101         checkIdentifierReferencesData(path, data);
102         resolveModificationFor(path).merge(data, version);
103     }
104
105     @Override
106     public void delete(final YangInstanceIdentifier path) {
107         checkSealed();
108
109         resolveModificationFor(path).delete();
110     }
111
112     @Override
113     public Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
114         /*
115          * Walk the tree from the top, looking for the first node between root and
116          * the requested path which has been modified. If no such node exists,
117          * we use the node itself.
118          */
119         final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
120             path, ModifiedNode.IS_TERMINAL_PREDICATE);
121         final YangInstanceIdentifier key = entry.getKey();
122         final ModifiedNode mod = entry.getValue();
123
124         final Optional<? extends TreeNode> result = resolveSnapshot(key, mod);
125         if (result.isPresent()) {
126             final NormalizedNode data = result.get().getData();
127             return NormalizedNodes.findNode(key, data, path);
128         }
129
130         return Optional.empty();
131     }
132
133     @SuppressWarnings("checkstyle:illegalCatch")
134     private Optional<? extends TreeNode> resolveSnapshot(final YangInstanceIdentifier path,
135             final ModifiedNode modification) {
136         final Optional<? extends TreeNode> potentialSnapshot = modification.getSnapshot();
137         if (potentialSnapshot != null) {
138             return potentialSnapshot;
139         }
140
141         try {
142             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
143         } catch (final Exception e) {
144             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
145             throw e;
146         }
147     }
148
149     void upgradeIfPossible() {
150         if (rootNode.getOperation() == LogicalOperation.NONE) {
151             strategyTree.upgradeIfPossible();
152         }
153     }
154
155     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
156         LOG.trace("Resolving modification apply strategy for {}", path);
157
158         upgradeIfPossible();
159         return StoreTreeNodes.findNodeChecked(getStrategy(), path);
160     }
161
162     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
163         upgradeIfPossible();
164
165         /*
166          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
167          *
168          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
169          * ending with an empty one, as we will throw the exception below. This fact could end up
170          * being a problem, as we'd have bunch of phantom operations.
171          *
172          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
173          * process.
174          */
175         ModificationApplyOperation operation = getStrategy();
176         ModifiedNode modification = rootNode;
177
178         int depth = 1;
179         for (final PathArgument pathArg : path.getPathArguments()) {
180             operation = operation.childByArg(pathArg);
181             if (operation == null) {
182                 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
183                         path.getAncestor(depth)));
184             }
185             ++depth;
186
187             modification = modification.modifyChild(pathArg, operation, version);
188         }
189
190         return OperationWithModification.from(operation, modification);
191     }
192
193     private void checkSealed() {
194         checkState(!isSealed(), "Data Tree is sealed. No further modifications allowed.");
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 TreeNode originalSnapshotRoot = snapshot.getRootNode();
216         final Optional<? extends TreeNode> tempRoot = getStrategy().apply(rootNode, Optional.of(originalSnapshotRoot),
217             version);
218         checkState(tempRoot.isPresent(), "Data tree root is not present, possibly removed by previous modification");
219
220         final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getEffectiveModelContext(),
221             tempRoot.get(), strategyTree);
222         return tempTree.newModification();
223     }
224
225     Version getVersion() {
226         return version;
227     }
228
229     boolean isSealed() {
230         // a quick check, synchronizes *only* on the sealed field
231         return (int) SEALED.getAcquire(this) != 0;
232     }
233
234     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
235         final Collection<ModifiedNode> children = node.getChildren();
236         if (!children.isEmpty()) {
237             cursor.enter(node.getIdentifier());
238             for (final ModifiedNode child : children) {
239                 applyNode(cursor, child);
240             }
241             cursor.exit();
242         }
243     }
244
245     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
246         switch (node.getOperation()) {
247             case NONE:
248                 break;
249             case DELETE:
250                 cursor.delete(node.getIdentifier());
251                 break;
252             case MERGE:
253                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
254                 applyChildren(cursor, node);
255                 break;
256             case TOUCH:
257                 // TODO: we could improve efficiency of cursor use if we could understand
258                 //       nested TOUCH operations. One way of achieving that would be a proxy
259                 //       cursor, which would keep track of consecutive enter and exit calls
260                 //       and coalesce them.
261                 applyChildren(cursor, node);
262                 break;
263             case WRITE:
264                 cursor.write(node.getIdentifier(), node.getWrittenValue());
265                 applyChildren(cursor, node);
266                 break;
267             default:
268                 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
269         }
270     }
271
272     @Override
273     public void applyToCursor(final DataTreeModificationCursor cursor) {
274         for (final ModifiedNode child : rootNode.getChildren()) {
275             applyNode(cursor, child);
276         }
277     }
278
279     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode data) {
280         checkArgument(arg.equals(data.getIdentifier()),
281             "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
282     }
283
284     private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
285             final NormalizedNode data) {
286         final PathArgument arg;
287
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 OperationWithModification 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
307         // for everything, including whatever user code works.
308         final boolean wasRunning = SEALED.compareAndSet(this, 0, 1);
309         checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
310
311         AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, getStrategy());
312         do {
313             current = current.process(version);
314         } while (current != null);
315     }
316 }