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