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