Merge "Bug 624 - Separate netty and exi specific classes from netconf-util."
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / DataTreeModification.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;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.util.Map.Entry;
13 import java.util.concurrent.atomic.AtomicBoolean;
14
15 import org.opendaylight.controller.md.sal.dom.store.impl.tree.NodeModification;
16 import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
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 /**
30  * Class encapsulation of set of modifications to a base tree. This tree is backed
31  * by a read-only snapshot and tracks modifications on top of that. The modification
32  * has the ability to rebase itself on a new snapshot.
33  */
34 /*
35  * FIXME: the thread safety of concurrent write/delete/read/seal operations
36  *        needs to be evaluated.
37  */
38 class DataTreeModification {
39     private static final Logger LOG = LoggerFactory.getLogger(DataTreeModification.class);
40     private final AtomicBoolean sealed = new AtomicBoolean();
41     private final ModificationApplyOperation strategyTree;
42     private final NodeModification rootModification;
43     private final DataTree.Snapshot snapshot;
44
45     private DataTreeModification(final DataTree.Snapshot snapshot, final ModificationApplyOperation strategyTree) {
46         this.snapshot = Preconditions.checkNotNull(snapshot);
47         this.strategyTree = Preconditions.checkNotNull(strategyTree);
48         this.rootModification = NodeModification.createUnmodified(snapshot.getRootNode());
49     }
50
51     public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
52         checkSealed();
53         resolveModificationFor(path).write(value);
54     }
55
56     public void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
57         checkSealed();
58         mergeImpl(resolveModificationFor(path),data);
59     }
60
61     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
62
63         if(data instanceof NormalizedNodeContainer<?,?,?>) {
64             @SuppressWarnings({ "rawtypes", "unchecked" })
65             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
66             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
67                 PathArgument childId = child.getIdentifier();
68                 mergeImpl(op.forChild(childId), child);
69             }
70         }
71         op.merge(data);
72     }
73
74     public void delete(final InstanceIdentifier path) {
75         checkSealed();
76         resolveModificationFor(path).delete();
77     }
78
79     public Optional<NormalizedNode<?, ?>> read(final InstanceIdentifier path) {
80         Entry<InstanceIdentifier, NodeModification> modification = TreeNodeUtils.findClosestsOrFirstMatch(rootModification, path, NodeModification.IS_TERMINAL_PREDICATE);
81
82         Optional<StoreMetadataNode> result = resolveSnapshot(modification);
83         if (result.isPresent()) {
84             NormalizedNode<?, ?> data = result.get().getData();
85             return NormalizedNodeUtils.findNode(modification.getKey(), data, path);
86         }
87         return Optional.absent();
88     }
89
90     private Optional<StoreMetadataNode> resolveSnapshot(
91             final Entry<InstanceIdentifier, NodeModification> keyModification) {
92         InstanceIdentifier path = keyModification.getKey();
93         NodeModification modification = keyModification.getValue();
94         return resolveSnapshot(path, modification);
95     }
96
97     private Optional<StoreMetadataNode> resolveSnapshot(final InstanceIdentifier path,
98             final NodeModification modification) {
99         try {
100             Optional<Optional<StoreMetadataNode>> potentialSnapshot = modification.getSnapshotCache();
101             if(potentialSnapshot.isPresent()) {
102                 return potentialSnapshot.get();
103             }
104             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
105                     StoreUtils.increase(snapshot.getRootNode().getSubtreeVersion()));
106         } catch (Exception e) {
107             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
108             throw e;
109         }
110     }
111
112     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
113         LOG.trace("Resolving modification apply strategy for {}", path);
114         return TreeNodeUtils.findNodeChecked(strategyTree, path);
115     }
116
117     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
118         NodeModification modification = rootModification;
119         // We ensure strategy is present.
120         ModificationApplyOperation operation = resolveModificationStrategy(path);
121         for (PathArgument pathArg : path.getPath()) {
122             modification = modification.modifyChild(pathArg);
123         }
124         return OperationWithModification.from(operation, modification);
125     }
126
127     public static DataTreeModification from(final DataTree.Snapshot snapshot, final ModificationApplyOperation resolver) {
128         return new DataTreeModification(snapshot, resolver);
129     }
130
131     public void seal() {
132         final boolean success = sealed.compareAndSet(false, true);
133         Preconditions.checkState(success, "Attempted to seal an already-sealed Data Tree.");
134         rootModification.seal();
135     }
136
137     private void checkSealed() {
138         checkState(!sealed.get(), "Data Tree is sealed. No further modifications allowed.");
139     }
140
141     protected NodeModification getRootModification() {
142         return rootModification;
143     }
144
145     @Override
146     public String toString() {
147         return "MutableDataTree [modification=" + rootModification + "]";
148     }
149 }