e0e136545803a902dc643fce86284ffa88c8c2a9
[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.Map.Entry;
14 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
15 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
16 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
17 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
18 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
19 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
20 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 final class InMemoryDataTreeModification implements DataTreeModification {
27     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> UPDATER =
28             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
29     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
30
31     private final RootModificationApplyOperation strategyTree;
32     private final InMemoryDataTreeSnapshot snapshot;
33     private final ModifiedNode rootNode;
34     private final Version version;
35
36     private volatile int sealed = 0;
37
38     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final RootModificationApplyOperation resolver) {
39         this.snapshot = Preconditions.checkNotNull(snapshot);
40         this.strategyTree = Preconditions.checkNotNull(resolver).snapshot();
41         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode(), strategyTree.getChildPolicy());
42
43         /*
44          * We could allocate version beforehand, since Version contract
45          * states two allocated version must be always different.
46          *
47          * Preallocating version simplifies scenarios such as
48          * chaining of modifications, since version for particular
49          * node in modification and in data tree (if successfully
50          * committed) will be same and will not change.
51          */
52         this.version = snapshot.getRootNode().getSubtreeVersion().next();
53     }
54
55     ModifiedNode getRootModification() {
56         return rootNode;
57     }
58
59     ModificationApplyOperation getStrategy() {
60         return strategyTree;
61     }
62
63     @Override
64     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
65         checkSealed();
66
67         resolveModificationFor(path).write(data);
68     }
69
70     @Override
71     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
72         checkSealed();
73
74         resolveModificationFor(path).merge(data);
75     }
76
77     @Override
78     public void delete(final YangInstanceIdentifier path) {
79         checkSealed();
80
81         resolveModificationFor(path).delete();
82     }
83
84     @Override
85     public Optional<NormalizedNode<?, ?>> readNode(final YangInstanceIdentifier path) {
86         /*
87          * Walk the tree from the top, looking for the first node between root and
88          * the requested path which has been modified. If no such node exists,
89          * we use the node itself.
90          */
91         final Entry<YangInstanceIdentifier, ModifiedNode> entry = StoreTreeNodes.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
92         final YangInstanceIdentifier key = entry.getKey();
93         final ModifiedNode mod = entry.getValue();
94
95         final Optional<TreeNode> result = resolveSnapshot(key, mod);
96         if (result.isPresent()) {
97             NormalizedNode<?, ?> data = result.get().getData();
98             return NormalizedNodes.findNode(key, data, path);
99         } else {
100             return Optional.absent();
101         }
102     }
103
104     private Optional<TreeNode> resolveSnapshot(final YangInstanceIdentifier path, final ModifiedNode modification) {
105         final Optional<TreeNode> potentialSnapshot = modification.getSnapshot();
106         if (potentialSnapshot != null) {
107             return potentialSnapshot;
108         }
109
110         try {
111             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
112                     version);
113         } catch (Exception e) {
114             LOG.error("Could not create snapshot for {}:{}", path, modification, e);
115             throw e;
116         }
117     }
118
119     private void upgradeIfPossible() {
120         if (rootNode.getOperation() == LogicalOperation.NONE) {
121             strategyTree.upgradeIfPossible();
122         }
123     }
124
125     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
126         LOG.trace("Resolving modification apply strategy for {}", path);
127
128         upgradeIfPossible();
129         return StoreTreeNodes.<ModificationApplyOperation>findNodeChecked(strategyTree, path);
130     }
131
132     private OperationWithModification resolveModificationFor(final YangInstanceIdentifier path) {
133         upgradeIfPossible();
134
135         /*
136          * Walk the strategy and modification trees in-sync, creating modification nodes as needed.
137          *
138          * If the user has provided wrong input, we may end up with a bunch of TOUCH nodes present
139          * ending with an empty one, as we will throw the exception below. This fact could end up
140          * being a problem, as we'd have bunch of phantom operations.
141          *
142          * That is fine, as we will prune any empty TOUCH nodes in the last phase of the ready
143          * process.
144          */
145         ModificationApplyOperation operation = strategyTree;
146         ModifiedNode modification = rootNode;
147
148         int i = 1;
149         for(PathArgument pathArg : path.getPathArguments()) {
150             Optional<ModificationApplyOperation> potential = operation.getChild(pathArg);
151             if (!potential.isPresent()) {
152                 throw new IllegalArgumentException(String.format("Child %s is not present in schema tree.",
153                         Iterables.toString(Iterables.limit(path.getPathArguments(), i))));
154             }
155             operation = potential.get();
156             ++i;
157
158             modification = modification.modifyChild(pathArg, operation.getChildPolicy());
159         }
160
161         return OperationWithModification.from(operation, modification);
162     }
163
164     @Override
165     public void ready() {
166         final boolean wasRunning = UPDATER.compareAndSet(this, 0, 1);
167         Preconditions.checkState(wasRunning, "Attempted to seal an already-sealed Data Tree.");
168
169         rootNode.seal();
170     }
171
172     private void checkSealed() {
173         Preconditions.checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
174     }
175
176     @Override
177     public String toString() {
178         return "MutableDataTree [modification=" + rootNode + "]";
179     }
180
181     @Override
182     public DataTreeModification newModification() {
183         Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
184
185         if (rootNode.getOperation() == LogicalOperation.NONE) {
186             // Simple fast case: just use the underlying modification
187             return snapshot.newModification();
188         }
189
190         /*
191          * We will use preallocated version, this means returned snapshot will
192          * have same version each time this method is called.
193          */
194         TreeNode originalSnapshotRoot = snapshot.getRootNode();
195         Optional<TreeNode> tempRoot = strategyTree.apply(rootNode, Optional.of(originalSnapshotRoot), version);
196
197         InMemoryDataTreeSnapshot tempTree = new InMemoryDataTreeSnapshot(snapshot.getSchemaContext(), tempRoot.get(), strategyTree);
198         return tempTree.newModification();
199     }
200
201     Version getVersion() {
202         return version;
203     }
204 }