15dcc964cb47d55edd19da29d6446a0051d7ea02
[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.AtomicIntegerFieldUpdater;
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 class DataTreeModification {
35     private static final Logger LOG = LoggerFactory.getLogger(DataTreeModification.class);
36
37     /*
38      * FIXME: the thread safety of concurrent write/delete/read/seal operations
39      *        needs to be evaluated.
40      */
41     private static final AtomicIntegerFieldUpdater<DataTreeModification> SEALED_UPDATER =
42             AtomicIntegerFieldUpdater.newUpdater(DataTreeModification.class, "sealed");
43     private volatile int sealed = 0;
44
45     private final ModificationApplyOperation strategyTree;
46     private final DataTree.Snapshot snapshot;
47     private final NodeModification rootNode;
48
49     private DataTreeModification(final DataTree.Snapshot snapshot, final ModificationApplyOperation strategyTree) {
50         this.snapshot = Preconditions.checkNotNull(snapshot);
51         this.strategyTree = Preconditions.checkNotNull(strategyTree);
52         this.rootNode = NodeModification.createUnmodified(snapshot.getRootNode());
53     }
54
55     public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> value) {
56         checkSealed();
57         resolveModificationFor(path).write(value);
58     }
59
60     public void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
61         checkSealed();
62         mergeImpl(resolveModificationFor(path),data);
63     }
64
65     private void mergeImpl(final OperationWithModification op,final NormalizedNode<?,?> data) {
66
67         if(data instanceof NormalizedNodeContainer<?,?,?>) {
68             @SuppressWarnings({ "rawtypes", "unchecked" })
69             NormalizedNodeContainer<?,?,NormalizedNode<PathArgument, ?>> dataContainer = (NormalizedNodeContainer) data;
70             for(NormalizedNode<PathArgument, ?> child : dataContainer.getValue()) {
71                 PathArgument childId = child.getIdentifier();
72                 mergeImpl(op.forChild(childId), child);
73             }
74         }
75         op.merge(data);
76     }
77
78     public void delete(final InstanceIdentifier path) {
79         checkSealed();
80         resolveModificationFor(path).delete();
81     }
82
83     public Optional<NormalizedNode<?, ?>> read(final InstanceIdentifier path) {
84         Entry<InstanceIdentifier, NodeModification> modification = TreeNodeUtils.findClosestsOrFirstMatch(rootNode, path, NodeModification.IS_TERMINAL_PREDICATE);
85
86         Optional<StoreMetadataNode> result = resolveSnapshot(modification);
87         if (result.isPresent()) {
88             NormalizedNode<?, ?> data = result.get().getData();
89             return NormalizedNodeUtils.findNode(modification.getKey(), data, path);
90         }
91         return Optional.absent();
92     }
93
94     private Optional<StoreMetadataNode> resolveSnapshot(
95             final Entry<InstanceIdentifier, NodeModification> keyModification) {
96         InstanceIdentifier path = keyModification.getKey();
97         NodeModification modification = keyModification.getValue();
98         return resolveSnapshot(path, modification);
99     }
100
101     private Optional<StoreMetadataNode> resolveSnapshot(final InstanceIdentifier path,
102             final NodeModification modification) {
103         try {
104             Optional<Optional<StoreMetadataNode>> potentialSnapshot = modification.getSnapshotCache();
105             if(potentialSnapshot.isPresent()) {
106                 return potentialSnapshot.get();
107             }
108             return resolveModificationStrategy(path).apply(modification, modification.getOriginal(),
109                     StoreUtils.increase(snapshot.getRootNode().getSubtreeVersion()));
110         } catch (Exception e) {
111             LOG.error("Could not create snapshot for {}:{}", path,modification,e);
112             throw e;
113         }
114     }
115
116     private ModificationApplyOperation resolveModificationStrategy(final InstanceIdentifier path) {
117         LOG.trace("Resolving modification apply strategy for {}", path);
118         return TreeNodeUtils.findNodeChecked(strategyTree, path);
119     }
120
121     private OperationWithModification resolveModificationFor(final InstanceIdentifier path) {
122         NodeModification modification = rootNode;
123         // We ensure strategy is present.
124         ModificationApplyOperation operation = resolveModificationStrategy(path);
125         for (PathArgument pathArg : path.getPath()) {
126             modification = modification.modifyChild(pathArg);
127         }
128         return OperationWithModification.from(operation, modification);
129     }
130
131     public static DataTreeModification from(final DataTree.Snapshot snapshot, final ModificationApplyOperation resolver) {
132         return new DataTreeModification(snapshot, resolver);
133     }
134
135     public void seal() {
136         final boolean success = SEALED_UPDATER.compareAndSet(this, 0, 1);
137         Preconditions.checkState(success, "Attempted to seal an already-sealed Data Tree.");
138         rootNode.seal();
139     }
140
141     private void checkSealed() {
142         checkState(sealed == 0, "Data Tree is sealed. No further modifications allowed.");
143     }
144
145     @Deprecated
146     protected NodeModification getRootModification() {
147         return rootNode;
148     }
149
150     @Override
151     public String toString() {
152         return "MutableDataTree [modification=" + rootNode + "]";
153     }
154 }