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