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