Bug 3189 Special case of checking root node QName.
[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.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.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 implements DataTreeModification {
31     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> 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);
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, 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         } else {
104             return Optional.absent();
105         }
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(),
116                     version);
117         } catch (final Exception e) {
118             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
119             throw e;
120         }
121     }
122
123     private 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 IllegalArgumentException(String.format("Child %s is not present in schema tree.",
157                         Iterables.toString(Iterables.limit(path.getPathArguments(), i))));
158             }
159             operation = potential.get();
160             ++i;
161
162             modification = modification.modifyChild(pathArg, operation.getChildPolicy());
163         }
164
165         return OperationWithModification.from(operation, modification);
166     }
167
168     @Override
169     public void ready() {
170         final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
171         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
172
173         rootNode.seal();
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 DataTreeModification 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(), "Data tree root is not present, possibly removed by previous modification");
201
202         final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
203         return tempTree.newModification();
204     }
205
206     Version getVersion() {
207         return version;
208     }
209
210     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
211         final Collection<ModifiedNode> children = node.getChildren();
212         if (!children.isEmpty()) {
213             cursor.enter(node.getIdentifier());
214             for (final ModifiedNode child : children) {
215                 applyNode(cursor, child);
216             }
217             cursor.exit();
218         }
219     }
220
221     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
222         switch (node.getOperation()) {
223         case NONE:
224             break;
225         case DELETE:
226             cursor.delete(node.getIdentifier());
227             break;
228         case MERGE:
229             cursor.merge(node.getIdentifier(), node.getWrittenValue());
230             applyChildren(cursor, node);
231             break;
232         case TOUCH:
233             // TODO: we could improve efficiency of cursor use if we could understand
234             //       nested TOUCH operations. One way of achieving that would be a proxy
235             //       cursor, which would keep track of consecutive enter and exit calls
236             //       and coalesce them.
237             applyChildren(cursor, node);
238             break;
239         case WRITE:
240             cursor.write(node.getIdentifier(), node.getWrittenValue());
241             applyChildren(cursor, node);
242             break;
243         default:
244             throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
245         }
246     }
247
248     @Override
249     public void applyToCursor(final DataTreeModificationCursor cursor) {
250         for (final ModifiedNode child : rootNode.getChildren()) {
251             applyNode(cursor, child);
252         }
253     }
254
255     private static void checkIdentifierReferencesData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
256         if (!path.isEmpty()) {
257             final PathArgument lastArg = path.getLastPathArgument();
258             Preconditions.checkArgument(lastArg != null, "Instance identifier %s has invalid null path argument", path);
259             Preconditions.checkArgument(lastArg.equals(data.getIdentifier()),
260                     "Instance identifier references %s but data identifier is %s", lastArg, data.getIdentifier());
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 }