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