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