BUG 2970 : Create a PruningDataTreeModification
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / ShardDataTree.java
1 /*
2  * Copyright (c) 2015 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.cluster.datastore;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Strings;
14 import java.net.URI;
15 import java.util.AbstractMap.SimpleEntry;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import java.util.Set;
20 import javax.annotation.concurrent.NotThreadSafe;
21 import org.opendaylight.controller.cluster.datastore.node.utils.transformer.NormalizedNodePruner;
22 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
23 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
25 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent;
26 import org.opendaylight.controller.md.sal.dom.store.impl.ResolveDataChangeEventsTask;
27 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
28 import org.opendaylight.yangtools.concepts.ListenerRegistration;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
32 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidates;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
34 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
36 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Internal shard state, similar to a DOMStore, but optimized for use in the actor system,
43  * e.g. it does not expose public interfaces and assumes it is only ever called from a
44  * single thread.
45  *
46  * This class is not part of the API contract and is subject to change at any time.
47  */
48 @NotThreadSafe
49 public final class ShardDataTree extends ShardDataTreeTransactionParent {
50     private static final Logger LOG = LoggerFactory.getLogger(ShardDataTree.class);
51     private static final ShardDataTreeNotificationManager MANAGER = new ShardDataTreeNotificationManager();
52     private final Map<String, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
53     private final ShardDataTreeChangePublisher treeChangePublisher = new ShardDataTreeChangePublisher();
54     private final ListenerTree listenerTree = ListenerTree.create();
55     private final TipProducingDataTree dataTree;
56     private Set<URI> validNamespaces;
57     private ShardDataTreeTransactionFactory transactionFactory = new RecoveryShardDataTreeTransactionFactory();
58
59     ShardDataTree(final SchemaContext schemaContext) {
60         dataTree = InMemoryDataTreeFactory.getInstance().create();
61         updateSchemaContext(schemaContext);
62
63     }
64
65     TipProducingDataTree getDataTree() {
66         return dataTree;
67     }
68
69     void updateSchemaContext(final SchemaContext schemaContext) {
70         Preconditions.checkNotNull(schemaContext);
71         dataTree.setSchemaContext(schemaContext);
72         validNamespaces = NormalizedNodePruner.namespaces(schemaContext);
73     }
74
75     private ShardDataTreeTransactionChain ensureTransactionChain(final String chainId) {
76         ShardDataTreeTransactionChain chain = transactionChains.get(chainId);
77         if (chain == null) {
78             chain = new ShardDataTreeTransactionChain(chainId, this);
79             transactionChains.put(chainId, chain);
80         }
81
82         return chain;
83     }
84
85     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final String txId, final String chainId) {
86         if (Strings.isNullOrEmpty(chainId)) {
87             return transactionFactory.newReadOnlyTransaction(txId, chainId);
88         }
89
90         return ensureTransactionChain(chainId).newReadOnlyTransaction(txId);
91     }
92
93     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final String txId, final String chainId) {
94         if (Strings.isNullOrEmpty(chainId)) {
95             return transactionFactory.newReadWriteTransaction(txId, chainId);
96         }
97
98         return ensureTransactionChain(chainId).newReadWriteTransaction(txId);
99     }
100
101     void notifyListeners(final DataTreeCandidate candidate) {
102         LOG.debug("Notifying listeners on candidate {}", candidate);
103
104         // DataTreeChanges first, as they are more light-weight
105         treeChangePublisher.publishChanges(candidate);
106
107         // DataChanges second, as they are heavier
108         ResolveDataChangeEventsTask.create(candidate, listenerTree).resolve(MANAGER);
109     }
110
111     void closeAllTransactionChains() {
112         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
113             chain.close();
114         }
115
116         transactionChains.clear();
117     }
118
119     void closeTransactionChain(final String transactionChainId) {
120         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
121         if (chain != null) {
122             chain.close();
123         } else {
124             LOG.debug("Closing non-existent transaction chain {}", transactionChainId);
125         }
126     }
127
128     Entry<ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>, DOMImmutableDataChangeEvent> registerChangeListener(
129             final YangInstanceIdentifier path,
130             final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener, final DataChangeScope scope) {
131         final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
132                 listenerTree.registerDataChangeListener(path, listener, scope);
133
134         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
135         final DOMImmutableDataChangeEvent event;
136         if (currentState.isPresent()) {
137             final NormalizedNode<?, ?> data = currentState.get();
138             event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE).setAfter(data).addCreated(path, data).build();
139         } else {
140             event = null;
141         }
142
143         return new SimpleEntry<>(reg, event);
144     }
145
146     Entry<ListenerRegistration<DOMDataTreeChangeListener>, DataTreeCandidate> registerTreeChangeListener(final YangInstanceIdentifier path,
147             final DOMDataTreeChangeListener listener) {
148         final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangePublisher.registerTreeChangeListener(path, listener);
149
150         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
151         final DataTreeCandidate event;
152         if (currentState.isPresent()) {
153             event = DataTreeCandidates.fromNormalizedNode(path, currentState.get());
154         } else {
155             event = null;
156         }
157         return new SimpleEntry<>(reg, event);
158     }
159
160     void applyForeignCandidate(final String identifier, final DataTreeCandidate foreign) throws DataValidationFailedException {
161         LOG.debug("Applying foreign transaction {}", identifier);
162
163         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
164         DataTreeCandidates.applyToModification(mod, foreign);
165         mod.ready();
166
167         LOG.trace("Applying foreign modification {}", mod);
168         dataTree.validate(mod);
169         final DataTreeCandidate candidate = dataTree.prepare(mod);
170         dataTree.commit(candidate);
171         notifyListeners(candidate);
172     }
173
174     @Override
175     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
176         // Intentional no-op
177     }
178
179     @Override
180     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
181         final DataTreeModification snapshot = transaction.getSnapshot();
182         snapshot.ready();
183         return new SimpleShardDataTreeCohort(this, snapshot);
184     }
185
186     void recoveryDone(){
187         transactionFactory = new RegularShardDataTreeTransactionFactory();
188     }
189
190     @VisibleForTesting
191     ShardDataTreeTransactionFactory getTransactionFactory(){
192         return transactionFactory;
193     }
194
195     @VisibleForTesting
196     static interface ShardDataTreeTransactionFactory {
197         ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final String txId, final String chainId);
198
199         ReadWriteShardDataTreeTransaction newReadWriteTransaction(final String txId, final String chainId);
200     }
201
202     @VisibleForTesting
203     class RecoveryShardDataTreeTransactionFactory implements ShardDataTreeTransactionFactory {
204
205         @Override
206         public ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(String txId, String chainId) {
207             return new ReadOnlyShardDataTreeTransaction(txId,
208                     new ShardDataTreeSnapshot(dataTree.takeSnapshot(), validNamespaces));
209         }
210
211         @Override
212         public ReadWriteShardDataTreeTransaction newReadWriteTransaction(String txId, String chainId) {
213             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId,
214                     new ShardDataTreeSnapshot(dataTree.takeSnapshot(), validNamespaces).newModification());
215         }
216     }
217
218     @VisibleForTesting
219     class RegularShardDataTreeTransactionFactory implements ShardDataTreeTransactionFactory {
220
221         @Override
222         public ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(String txId, String chainId) {
223             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
224
225         }
226
227         @Override
228         public ReadWriteShardDataTreeTransaction newReadWriteTransaction(String txId, String chainId) {
229             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
230                     .newModification());
231         }
232     }
233 }