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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.