BUG-509: migrate to TreeNodes
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / tree / data / 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.controller.md.sal.dom.store.impl.tree.data;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.util.Map.Entry;
13 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
14
15 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeModification;
16 import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreUtils;
17 import org.opendaylight.controller.md.sal.dom.store.impl.tree.TreeNodeUtils;
18 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.TreeNode;
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
21 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
23 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeUtils;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 import com.google.common.base.Optional;
28 import com.google.common.base.Preconditions;
29
30 final class InMemoryDataTreeModification implements DataTreeModification {
31     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDataTreeModification.class);
32
33     /*
34      * FIXME: the thread safety of concurrent write/delete/read/seal operations
35      *        needs to be evaluated.
36      */
37     private static final AtomicIntegerFieldUpdater<InMemoryDataTreeModification> SEALED_UPDATER =
38             AtomicIntegerFieldUpdater.newUpdater(InMemoryDataTreeModification.class, "sealed");
39     private volatile int sealed = 0;
40
41     private final ModificationApplyOperation strategyTree;
42     private final InMemoryDataTreeSnapshot snapshot;
43     private final ModifiedNode rootNode;
44
45     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final ModificationApplyOperation resolver) {
46         this.snapshot = Preconditions.checkNotNull(snapshot);
47         this.strategyTree = Preconditions.checkNotNull(resolver);
48         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode());
49     }
50
51     ModifiedNode getRootModification() {
52         return rootNode;
53     }
54
55     ModificationApplyOperation getStrategy() {
56         return strategyTree;
57     }
58
59     @Override
60     public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
61         checkSealed();
62         resolveModificationFor(path).write(value);
63     }
64
65     @Override
66     public void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
67         checkSealed();
68         mergeImpl(resolveModificationFor(path),data);
69     }
70
71     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
72
73         if(data instanceof NormalizedNodeContainer<?,?,?>) {
74             @SuppressWarnings({ "rawtypes", "unchecked" })
75             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
76             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
77                 PathArgument childId = child.getIdentifier();
78                 mergeImpl(op.forChild(childId), child);
79             }
80         }
81         op.merge(data);
82     }
83
84     @Override
85     public void delete(final InstanceIdentifier path) {
86         checkSealed();
87         resolveModificationFor(path).delete();
88     }
89
90     @Override
91     public Optional<NormalizedNode<?, ?>> readNode(final InstanceIdentifier path) {
92         /*
93          * Walk the tree from the top, looking for the first node between root and
94          * the requested path which has been modified. If no such node exists,
95          * we use the node itself.
96          */
97         final Entry<InstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
98         final InstanceIdentifier key = entry.getKey();
99         final ModifiedNode mod = entry.getValue();
100
101         final Optional<TreeNode> result = resolveSnapshot(key, mod);
102         if (result.isPresent()) {
103             NormalizedNode<?, ?> data = result.get().getData();
104             return NormalizedNodeUtils.findNode(key, data, path);
105         } else {
106             return Optional.absent();
107         }
108     }
109
110     private Optional<TreeNode> resolveSnapshot(final InstanceIdentifier path,
111             final ModifiedNode modification) {
112         final Optional<Optional<TreeNode>> potentialSnapshot = modification.getSnapshotCache();
113         if(potentialSnapshot.isPresent()) {
114             return potentialSnapshot.get();
115         }
116
117         try {
118             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
119                     StoreUtils.increase(snapshot.getRootNode().getSubtreeVersion()));
120         } catch (Exception e) {
121             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
122             throw e;
123         }
124     }
125
126     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
127         LOG.trace("Resolving modification apply strategy for {}", path);
128         return TreeNodeUtils.findNodeChecked(strategyTree, path);
129     }
130
131     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
132         ModifiedNode modification = rootNode;
133         // We ensure strategy is present.
134         ModificationApplyOperation operation = resolveModificationStrategy(path);
135         for (PathArgument pathArg : path.getPath()) {
136             modification = modification.modifyChild(pathArg);
137         }
138         return OperationWithModification.from(operation, modification);
139     }
140
141     @Override
142     public void seal() {
143         final boolean success = SEALED_UPDATER.compareAndSet(this, 0, 1);
144         Preconditions.checkState(success, "Attempted to seal an already-sealed Data Tree.");
145         rootNode.seal();
146     }
147
148     private void checkSealed() {
149         checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
150     }
151
152     @Override
153     public String toString() {
154         return "MutableDataTree [modification=" + rootNode + "]";
155     }
156
157     @Override
158     public DataTreeModification newModification() {
159         // FIXME: transaction chaining
160         throw new UnsupportedOperationException("Implement this as part of transaction chaining");
161     }
162 }