64eb6c87dc9bc4cf571058994665042da489d8d9
[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     public TipProducingDataTree getDataTree() {
64         return dataTree;
65     }
66
67     SchemaContext getSchemaContext() {
68         return schemaContext;
69     }
70
71     void updateSchemaContext(final SchemaContext schemaContext) {
72         Preconditions.checkNotNull(schemaContext);
73         this.schemaContext = schemaContext;
74         dataTree.setSchemaContext(schemaContext);
75     }
76
77     private ShardDataTreeTransactionChain ensureTransactionChain(final String chainId) {
78         ShardDataTreeTransactionChain chain = transactionChains.get(chainId);
79         if (chain == null) {
80             chain = new ShardDataTreeTransactionChain(chainId, this);
81             transactionChains.put(chainId, chain);
82         }
83
84         return chain;
85     }
86
87     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final String txId, final String chainId) {
88         if (Strings.isNullOrEmpty(chainId)) {
89             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
90         }
91
92         return ensureTransactionChain(chainId).newReadOnlyTransaction(txId);
93     }
94
95     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final String txId, final String chainId) {
96         if (Strings.isNullOrEmpty(chainId)) {
97             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
98                     .newModification());
99         }
100
101         return ensureTransactionChain(chainId).newReadWriteTransaction(txId);
102     }
103
104     public void notifyListeners(final DataTreeCandidate candidate) {
105         LOG.debug("Notifying listeners on candidate {}", candidate);
106
107         // DataTreeChanges first, as they are more light-weight
108         treeChangePublisher.publishChanges(candidate);
109
110         // DataChanges second, as they are heavier
111         ResolveDataChangeEventsTask.create(candidate, listenerTree).resolve(MANAGER);
112     }
113
114     void notifyOfInitialData(DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
115             NormalizedNode<?, ?>>> listenerReg, Optional<DataTreeCandidate> currentState) {
116
117         if(currentState.isPresent()) {
118             ListenerTree localListenerTree = ListenerTree.create();
119             localListenerTree.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
120                     listenerReg.getScope());
121
122             ResolveDataChangeEventsTask.create(currentState.get(), localListenerTree).resolve(MANAGER);
123         }
124     }
125
126     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
127             final Optional<DataTreeCandidate> currentState) {
128         if(currentState.isPresent()) {
129             ShardDataTreeChangePublisher localTreeChangePublisher = new ShardDataTreeChangePublisher();
130             localTreeChangePublisher.registerTreeChangeListener(path, listener);
131             localTreeChangePublisher.publishChanges(currentState.get());
132         }
133     }
134
135     void closeAllTransactionChains() {
136         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
137             chain.close();
138         }
139
140         transactionChains.clear();
141     }
142
143     void closeTransactionChain(final String transactionChainId) {
144         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
145         if (chain != null) {
146             chain.close();
147         } else {
148             LOG.debug("Closing non-existent transaction chain {}", transactionChainId);
149         }
150     }
151
152     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
153             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
154                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
155                     final DataChangeScope scope) {
156         final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
157                 listenerTree.registerDataChangeListener(path, listener, scope);
158
159         return new SimpleEntry<>(reg, readCurrentData());
160     }
161
162     private Optional<DataTreeCandidate> readCurrentData() {
163         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(ROOT_PATH);
164         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
165                 ROOT_PATH, currentState.get())) : Optional.<DataTreeCandidate>absent();
166     }
167
168     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>> registerTreeChangeListener(
169             final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
170         final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangePublisher.registerTreeChangeListener(
171                 path, listener);
172
173         return new SimpleEntry<>(reg, readCurrentData());
174     }
175
176     void applyForeignCandidate(final String identifier, final DataTreeCandidate foreign) throws DataValidationFailedException {
177         LOG.debug("Applying foreign transaction {}", identifier);
178
179         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
180         DataTreeCandidates.applyToModification(mod, foreign);
181         mod.ready();
182
183         LOG.trace("Applying foreign modification {}", mod);
184         dataTree.validate(mod);
185         final DataTreeCandidate candidate = dataTree.prepare(mod);
186         dataTree.commit(candidate);
187         notifyListeners(candidate);
188     }
189
190     @Override
191     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
192         // Intentional no-op
193     }
194
195     @Override
196     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
197         final DataTreeModification snapshot = transaction.getSnapshot();
198         snapshot.ready();
199         return new SimpleShardDataTreeCohort(this, snapshot, transaction.getId());
200     }
201
202     public Optional<NormalizedNode<?, ?>> readNode(YangInstanceIdentifier path) {
203         return dataTree.takeSnapshot().readNode(path);
204     }
205
206     public DataTreeSnapshot takeSnapshot() {
207         return dataTree.takeSnapshot();
208     }
209
210     public DataTreeModification newModification() {
211         return dataTree.takeSnapshot().newModification();
212     }
213
214     public DataTreeCandidate commit(DataTreeModification modification) throws DataValidationFailedException {
215         modification.ready();
216         dataTree.validate(modification);
217         DataTreeCandidateTip candidate = dataTree.prepare(modification);
218         dataTree.commit(candidate);
219         return candidate;
220     }
221 }