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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.