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