cd361ce32852eba5aff6fe1286f4bbb8adec4393
[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.DataTreeModification;
23 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModificationCursor;
24 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
25 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 final class InMemoryDataTreeModification extends AbstractCursorAware implements CursorAwareDataTreeModification {
32     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
33             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
34     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
35
36     private final RootModificationApplyOperation strategyTree;
37     private final InMemoryDataTreeSnapshot snapshot;
38     private final ModifiedNode rootNode;
39     private final Version version;
40
41     private volatile int sealed = 0;
42
43     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, 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         } else {
106             return Optional.absent();
107         }
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 DataTreeModification 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(), "Data tree root is not present, possibly removed by previous modification");
194
195         final InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
196         return tempTree.newModification();
197     }
198
199     Version getVersion() {
200         return version;
201     }
202
203     boolean isSealed() {
204         return sealed == 1;
205     }
206
207     private static void applyChildren(final DataTreeModificationCursor cursor, final ModifiedNode node) {
208         final Collection<ModifiedNode> children = node.getChildren();
209         if (!children.isEmpty()) {
210             cursor.enter(node.getIdentifier());
211             for (final ModifiedNode child : children) {
212                 applyNode(cursor, child);
213             }
214             cursor.exit();
215         }
216     }
217
218     private static void applyNode(final DataTreeModificationCursor cursor, final ModifiedNode node) {
219         switch (node.getOperation()) {
220         case NONE:
221             break;
222         case DELETE:
223             cursor.delete(node.getIdentifier());
224             break;
225         case MERGE:
226             cursor.merge(node.getIdentifier(), node.getWrittenValue());
227             applyChildren(cursor, node);
228             break;
229         case TOUCH:
230             // TODO: we could improve efficiency of cursor use if we could understand
231             //       nested TOUCH operations. One way of achieving that would be a proxy
232             //       cursor, which would keep track of consecutive enter and exit calls
233             //       and coalesce them.
234             applyChildren(cursor, node);
235             break;
236         case WRITE:
237             cursor.write(node.getIdentifier(), node.getWrittenValue());
238             applyChildren(cursor, node);
239             break;
240         default:
241             throw new IllegalArgumentException("Unhandled node operation " + node.getOperation());
242         }
243     }
244
245     @Override
246     public void applyToCursor(@Nonnull final DataTreeModificationCursor cursor) {
247         for (final ModifiedNode child : rootNode.getChildren()) {
248             applyNode(cursor, child);
249         }
250     }
251
252     static void checkIdentifierReferencesData(final PathArgument arg, final NormalizedNode<?, ?> data) {
253         Preconditions.checkArgument(arg.equals(data.getIdentifier()),
254             "Instance identifier references %s but data identifier is %s", arg, data.getIdentifier());
255     }
256
257     private static void checkIdentifierReferencesData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
258         if (!path.isEmpty()) {
259             final PathArgument lastArg = path.getLastPathArgument();
260             Preconditions.checkArgument(lastArg != null, "Instance identifier %s has invalid null path argument", path);
261             checkIdentifierReferencesData(lastArg, data);
262         } else {
263             final QName type = data.getNodeType();
264             Preconditions.checkArgument(SchemaContext.NAME.equals(type), "Incorrect name %s of root node", type);
265         }
266     }
267
268     @Override
269     public DataTreeModificationCursor createCursor(@Nonnull final YangInstanceIdentifier path) {
270         final OperationWithModification op = resolveModificationFor(path);
271         return openCursor(new InMemoryDataTreeModificationCursor(this, path, op));
272     }
273
274     @Override
275     public void ready() {
276         final boolean wasRunning = SEALED_UPDATER.compareAndSet(this, 0, 1);
277         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
278
279         AbstractReadyIterator current = AbstractReadyIterator.create(rootNode, strategyTree);
280         do {
281             current = current.process(version);
282         } while (current != null);
283     }
284 }