54a3b5a587bb30a56f4fc162b6a69a840f565efb
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / tree / 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.impl.schema.tree;
9
10 import com.google.common.base.Preconditions;
11 import java.util.Collection;
12 import java.util.Map.Entry;
13 import java.util.Optional;
14 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
17 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
19 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.CursorAwareDataTreeModification;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
25 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
26 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification,
31         SchemaContextProvider {
32     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
33             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
34     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
35
36     private final RootModificationApplyOperation strategyTree;
37     private final InMemoryDataTreeSnapshot snapshot;
38     private final ModifiedNode rootNode;
39     private final Version version;
40
41     private volatile int sealed = 0;
42
43     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot,
44             final RootModificationApplyOperation resolver) {
45         this.snapshot = Preconditions.checkNotNull(snapshot);
46         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
47         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
48
49         /*
50          * We could allocate version beforehand, since Version contract
51          * states two allocated version must be always different.
52          *
53          * Preallocating version simplifies scenarios such as
54          * chaining of modifications, since version for particular
55          * node in modification and in data tree (if successfully
56          * committed) will be same and will not change.
57          */
58         this.version = snapshot.getRootNode().getSubtreeVersion().next();
59     }
60
61     ModifiedNode getRootModification() {
62         return rootNode;
63     }
64
65     ModificationApplyOperation getStrategy() {
66         return strategyTree;
67     }
68
69     @Override
70     public SchemaContext getSchemaContext() {
71         return snapshot.getSchemaContext();
72     }
73
74     @Override
75     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
76         checkSealed();
77         checkIdentifierReferencesData(path, data);
78         resolveModificationFor(path).write(data);
79     }
80
81     @Override
82     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
83         checkSealed();
84         checkIdentifierReferencesData(path, data);
85         resolveModificationFor(path).merge(data, version);
86     }
87
88     @Override
89     public void delete(final YangInstanceIdentifier path) {
90         checkSealed();
91
92         resolveModificationFor(path).delete();
93     }
94
95     @Override
96     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
97         /*
98          * Walk the tree from the top, looking for the first node between root and
99          * the requested path which has been modified. If no such node exists,
100          * we use the node itself.
101          */
102         final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode,
103             path, ModifiedNode.IS_TERMINAL_PREDICATE);
104         final YangInstanceIdentifier key = entry.getKey();
105         final ModifiedNode mod = entry.getValue();
106
107         final Optional<TreeNode> result = resolveSnapshot(key, mod);
108         if (result.isPresent()) {
109             final NormalizedNode<?, ?> data = result.get().getData();
110             return NormalizedNodes.findNode(key, data, path);
111         }
112
113         return Optional.empty();
114     }
115
116     @SuppressWarnings("checkstyle:illegalCatch")
117     private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
118         final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
119         if (potentialSnapshot != null) {
120             return potentialSnapshot;
121         }
122
123         try {
124             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(), version);
125         } catch (final Exception e) {
126             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
127             throw e;
128         }
129     }
130
131     void upgradeIfPossible() {
132         if (rootNode.getOperation() == LogicalOperation.NONE) {
133             strategyTree.upgradeIfPossible();
134         }
135     }
136
137     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
138         LOG.trace("Resolving modification apply strategy for {}", path);
139
140         upgradeIfPossible();
141         return StoreTreeNodes.findNodeChecked(strategyTree, path);
142     }
143
144     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
145         upgradeIfPossible();
146
147         /*
148          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
149          *
150          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
151          * ending with an empty one, as we will throw the exception below. This fact could end up
152          * being a problem, as we'd have bunch of phantom operations.
153          *
154          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
155          * process.
156          */
157         ModificationApplyOperation operation = strategyTree;
158         ModifiedNode modification = rootNode;
159
160         int depth = 1;
161         for (final PathArgument pathArg : path.getPathArguments()) {
162             final Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
163             if (!potential.isPresent()) {
164                 throw new SchemaValidationFailedException(String.format("Child %s is not present in schema tree.",
165                         path.getAncestor(depth)));
166             }
167             operation = potential.get();
168             ++depth;
169
170             modification = modification.modifyChild(pathArg, operation, version);
171         }
172
173         return OperationWithModification.from(operation, modification);
174     }
175
176     private void checkSealed() {
177         Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
178     }
179
180     @Override
181     public String toString() {
182         return "MutableDataTree [modification=" + rootNode + "]";
183     }
184
185     @Override
186     public InMemoryDataTreeModification newModification() {
187         Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
188
189         if (rootNode.getOperation() == LogicalOperation.NONE) {
190             // Simple fast case: just use the underlying modification
191             return snapshot.newModification();
192         }
193
194         /*
195          * We will use preallocated version, this means returned snapshot will
196          * have same version each time this method is called.
197          */
198         final TreeNode originalSnapshotRoot = snapshot.getRootNode();
199         final Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
200         Preconditions.checkState(tempRoot.isPresent(),
201             "Data tree root is not present, possibly removed by previous modification");
202
203         final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
204             tempRoot.get(), strategyTree);
205         return tempTree.newModification();
206     }
207
208     Version getVersion() {
209         return version;
210     }
211
212     boolean isSealed() {
213         return sealed == 1;
214     }
215
216     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
217         final Collection<ModifiedNode> children = node.getChildren();
218         if (!children.isEmpty()) {
219             cursor.enter(node.getIdentifier());
220             for (final ModifiedNode child : children) {
221                 applyNode(cursor, child);
222             }
223             cursor.exit();
224         }
225     }
226
227     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
228         switch (node.getOperation()) {
229             case NONE:
230                 break;
231             case DELETE:
232                 cursor.delete(node.getIdentifier());
233                 break;
234             case MERGE:
235                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
236                 applyChildren(cursor, node);
237                 break;
238             case TOUCH:
239                 // TODO: we could improve efficiency of cursor use if we could understand
240                 //       nested TOUCH operations. One way of achieving that would be a proxy
241                 //       cursor, which would keep track of consecutive enter and exit calls
242                 //       and coalesce them.
243                 applyChildren(cursor, node);
244                 break;
245             case WRITE:
246                 cursor.write(node.getIdentifier(), node.getWrittenValue());
247                 applyChildren(cursor, node);
248                 break;
249             default:
250                 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
251         }
252     }
253
254     @Override
255     public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
256         for (final ModifiedNode child : rootNode.getChildren()) {
257             applyNode(cursor, child);
258         }
259     }
260
261     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
262         Preconditions.checkArgument(arg.equals(data.getIdentifier()),
263             "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
264     }
265
266     private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
267             final NormalizedNode<?, ?> data) {
268         final PathArgument arg;
269
270         if (!path.isEmpty()) {
271             arg = path.getLastPathArgument();
272             Preconditions.checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
273         } else {
274             arg = rootNode.getIdentifier();
275         }
276
277         checkIdentifierReferencesData(arg, data);
278     }
279
280     @Override
281     public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
282         final OperationWithModification op = resolveModificationFor(path);
283         return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
284     }
285
286     @Override
287     public void ready() {
288         final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
289         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
290
291         AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
292         do {
293             current = current.process(version);
294         } while (current != null);
295     }
296 }