02e062add73f39af6cf382f873443fb3b9e6aa4c
[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     @SuppressWarnings("checkstyle:illegalCatch")
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.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 depth = 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(depth)));
158             }
159             operation = potential.get();
160             ++depth;
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 InMemoryDataTreeModification 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(),
193             "Data tree root is not present, possibly removed by previous modification");
194
195         final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(),
196             tempRoot.get(), strategyTree);
197         return tempTree.newModification();
198     }
199
200     Version getVersion() {
201         return version;
202     }
203
204     boolean isSealed() {
205         return sealed == 1;
206     }
207
208     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
209         final Collection<ModifiedNode> children = node.getChildren();
210         if (!children.isEmpty()) {
211             cursor.enter(node.getIdentifier());
212             for (final ModifiedNode child : children) {
213                 applyNode(cursor, child);
214             }
215             cursor.exit();
216         }
217     }
218
219     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
220         switch (node.getOperation()) {
221             case NONE:
222                 break;
223             case DELETE:
224                 cursor.delete(node.getIdentifier());
225                 break;
226             case MERGE:
227                 cursor.merge(node.getIdentifier(), node.getWrittenValue());
228                 applyChildren(cursor, node);
229                 break;
230             case TOUCH:
231                 // TODO: we could improve efficiency of cursor use if we could understand
232                 //       nested TOUCH operations. One way of achieving that would be a proxy
233                 //       cursor, which would keep track of consecutive enter and exit calls
234                 //       and coalesce them.
235                 applyChildren(cursor, node);
236                 break;
237             case WRITE:
238                 cursor.write(node.getIdentifier(), node.getWrittenValue());
239                 applyChildren(cursor, node);
240                 break;
241             default:
242                 throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
243         }
244     }
245
246     @Override
247     public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
248         for (final ModifiedNode child : rootNode.getChildren()) {
249             applyNode(cursor, child);
250         }
251     }
252
253     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
254         Preconditions.checkArgument(arg.equals(data.getIdentifier()),
255             "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
256     }
257
258     private void checkIdentifierReferencesData(final YangInstanceIdentifier path,
259             final NormalizedNode<?, ?> data) {
260         final PathArgument arg;
261
262         if (!path.isEmpty()) {
263             arg = path.getLastPathArgument();
264             Preconditions.checkArgument(arg != null, "Instance identifier %s has invalid null path argument", path);
265         } else {
266             arg = rootNode.getIdentifier();
267         }
268
269         checkIdentifierReferencesData(arg, data);
270     }
271
272     @Override
273     public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
274         final OperationWithModification op = resolveModificationFor(path);
275         return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
276     }
277
278     @Override
279     public void ready() {
280         final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
281         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
282
283         AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
284         do {
285             current = current.process(version);
286         } while (current != null);
287     }
288 }