d3e4bf07144e0e99ebe3be6e8e322c5fb9cf4b1d
[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 java.util.Map.Entry;
11
12 import javax.annotation.concurrent.GuardedBy;
13
14 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeModification;
15 import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreUtils;
16 import org.opendaylight.controller.md.sal.dom.store.impl.tree.TreeNodeUtils;
17 import org.opendaylight.controller.md.sal.dom.store.impl.tree.spi.TreeNode;
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     private final ModificationApplyOperation strategyTree;
32     private final InMemoryDataTreeSnapshot snapshot;
33     private final ModifiedNode rootNode;
34
35     @GuardedBy("this")
36     private boolean sealed = false;
37
38     InMemoryDataTreeModification(final InMemoryDataTreeSnapshot snapshot, final ModificationApplyOperation resolver) {
39         this.snapshot = Preconditions.checkNotNull(snapshot);
40         this.strategyTree = Preconditions.checkNotNull(resolver);
41         this.rootNode = ModifiedNode.createUnmodified(snapshot.getRootNode());
42     }
43
44     ModifiedNode getRootModification() {
45         return rootNode;
46     }
47
48     ModificationApplyOperation getStrategy() {
49         return strategyTree;
50     }
51
52     @Override
53     public synchronized void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
54         checkSealed();
55         resolveModificationFor(path).write(value);
56     }
57
58     @Override
59     public synchronized void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
60         checkSealed();
61         mergeImpl(resolveModificationFor(path),data);
62     }
63
64     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
65
66         if(data instanceof NormalizedNodeContainer<?,?,?>) {
67             @SuppressWarnings({ "rawtypes", "unchecked" })
68             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
69             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
70                 PathArgument childId = child.getIdentifier();
71                 mergeImpl(op.forChild(childId), child);
72             }
73         }
74         op.merge(data);
75     }
76
77     @Override
78     public synchronized void delete(final InstanceIdentifier path) {
79         checkSealed();
80         resolveModificationFor(path).delete();
81     }
82
83     @Override
84     public synchronized Optional<NormalizedNode<?, ?>> readNode(final InstanceIdentifier 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<InstanceIdentifier, ModifiedNode> entry = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, ModifiedNode.IS_TERMINAL_PREDICATE);
91         final InstanceIdentifier 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 NormalizedNodeUtils.findNode(key, data, path);
98         } else {
99             return Optional.absent();
100         }
101     }
102
103     private Optional<TreeNode> resolveSnapshot(final InstanceIdentifier path,
104             final ModifiedNode modification) {
105         final Optional<Optional<TreeNode>> potentialSnapshot = modification.getSnapshotCache();
106         if(potentialSnapshot.isPresent()) {
107             return potentialSnapshot.get();
108         }
109
110         try {
111             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
112                     StoreUtils.increase(snapshot.getRootNode().getSubtreeVersion()));
113         } catch (Exception e) {
114             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
115             throw e;
116         }
117     }
118
119     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
120         LOG.trace("Resolving modification apply strategy for {}", path);
121         return TreeNodeUtils.findNodeChecked(strategyTree, path);
122     }
123
124     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
125         ModifiedNode modification = rootNode;
126         // We ensure strategy is present.
127         ModificationApplyOperation operation = resolveModificationStrategy(path);
128         for (PathArgument pathArg : path.getPath()) {
129             modification = modification.modifyChild(pathArg);
130         }
131         return OperationWithModification.from(operation, modification);
132     }
133
134     @Override
135     public synchronized void seal() {
136         Preconditions.checkState(!sealed, "Attempted to seal an already-sealed Data Tree.");
137         sealed = true;
138         rootNode.seal();
139     }
140
141     @GuardedBy("this")
142     private void checkSealed() {
143         Preconditions.checkState(!sealed, "Data Tree is sealed. No further modifications allowed.");
144     }
145
146     @Override
147     public String toString() {
148         return "MutableDataTree [modification=" + rootNode + "]";
149     }
150
151     @Override
152     public synchronized DataTreeModification newModification() {
153         Preconditions.checkState(sealed, "Attempted to chain on an unsealed modification");
154
155         // FIXME: transaction chaining
156         throw new UnsupportedOperationException("Implement this as part of transaction chaining");
157     }
158 }