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