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