df3ef8b7e128b2be29eb5473bd86d056cba218d2
[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         Entry<InstanceIdentifier, NodeModification> modification = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, NodeModification.IS_TERMINAL_PREDICATE);
92
93         Optional<StoreMetadataNode> result = resolveSnapshot(modification);
94         if (result.isPresent()) {
95             NormalizedNode<?, ?> data = result.get().getData();
96             return NormalizedNodeUtils.findNode(modification.getKey(), data, path);
97         }
98         return Optional.absent();
99     }
100
101     private Optional<StoreMetadataNode> resolveSnapshot(
102             final Entry<InstanceIdentifier, NodeModification> keyModification) {
103         InstanceIdentifier path = keyModification.getKey();
104         NodeModification modification = keyModification.getValue();
105         return resolveSnapshot(path, modification);
106     }
107
108     private Optional<StoreMetadataNode> resolveSnapshot(final InstanceIdentifier path,
109             final NodeModification modification) {
110         try {
111             Optional<Optional<StoreMetadataNode>> potentialSnapshot = modification.getSnapshotCache();
112             if(potentialSnapshot.isPresent()) {
113                 return potentialSnapshot.get();
114             }
115             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
116                     StoreUtils.increase(snapshot.getRootNode().getSubtreeVersion()));
117         } catch (Exception e) {
118             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
119             throw e;
120         }
121     }
122
123     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
124         LOG.trace("Resolving modification apply strategy for {}", path);
125         return TreeNodeUtils.findNodeChecked(strategyTree, path);
126     }
127
128     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
129         NodeModification modification = rootNode;
130         // We ensure strategy is present.
131         ModificationApplyOperation operation = resolveModificationStrategy(path);
132         for (PathArgument pathArg : path.getPath()) {
133             modification = modification.modifyChild(pathArg);
134         }
135         return OperationWithModification.from(operation, modification);
136     }
137
138     @Override
139     public void seal() {
140         final boolean success = SEALED_UPDATER.compareAndSet(this, 0, 1);
141         Preconditions.checkState(success, "Attempted to seal an already-sealed Data Tree.");
142         rootNode.seal();
143     }
144
145     private void checkSealed() {
146         checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
147     }
148
149     @Override
150     public String toString() {
151         return "MutableDataTree [modification=" + rootNode + "]";
152     }
153
154     @Override
155     public DataTreeModification newModification() {
156         // FIXME: transaction chaining
157         throw new UnsupportedOperationException("Implement this as part of transaction chaining");
158     }
159 }

©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.