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