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