Apply SchemaContext to dataTree first
[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 java.util.AbstractMap.SimpleEntry;
13 import java.util.HashMap;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import javax.annotation.concurrent.NotThreadSafe;
17 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
18 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
19 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
20 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
21 import org.opendaylight.controller.md.sal.dom.api.DOMDataTreeChangeListener;
22 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
23 import org.opendaylight.yangtools.concepts.Identifier;
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
51     private final Map<LocalHistoryIdentifier, ShardDataTreeTransactionChain> transactionChains = new HashMap<>();
52     private final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher;
53     private final ShardDataChangeListenerPublisher dataChangeListenerPublisher;
54     private final TipProducingDataTree dataTree;
55     private final String logContext;
56     private SchemaContext schemaContext;
57
58     public ShardDataTree(final SchemaContext schemaContext, final TreeType treeType,
59             final ShardDataTreeChangeListenerPublisher treeChangeListenerPublisher,
60             final ShardDataChangeListenerPublisher dataChangeListenerPublisher, final String logContext) {
61         dataTree = InMemoryDataTreeFactory.getInstance().create(treeType);
62         updateSchemaContext(schemaContext);
63
64         this.treeChangeListenerPublisher = Preconditions.checkNotNull(treeChangeListenerPublisher);
65         this.dataChangeListenerPublisher = Preconditions.checkNotNull(dataChangeListenerPublisher);
66         this.logContext = Preconditions.checkNotNull(logContext);
67     }
68
69     public ShardDataTree(final SchemaContext schemaContext, final TreeType treeType) {
70         this(schemaContext, treeType, new DefaultShardDataTreeChangeListenerPublisher(),
71                 new DefaultShardDataChangeListenerPublisher(), "");
72     }
73
74     public TipProducingDataTree getDataTree() {
75         return dataTree;
76     }
77
78     SchemaContext getSchemaContext() {
79         return schemaContext;
80     }
81
82     void updateSchemaContext(final SchemaContext schemaContext) {
83         dataTree.setSchemaContext(schemaContext);
84         this.schemaContext = Preconditions.checkNotNull(schemaContext);
85     }
86
87     private ShardDataTreeTransactionChain ensureTransactionChain(final LocalHistoryIdentifier localHistoryIdentifier) {
88         ShardDataTreeTransactionChain chain = transactionChains.get(localHistoryIdentifier);
89         if (chain == null) {
90             chain = new ShardDataTreeTransactionChain(localHistoryIdentifier, this);
91             transactionChains.put(localHistoryIdentifier, chain);
92         }
93
94         return chain;
95     }
96
97     ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
98         if (txId.getHistoryId().getHistoryId() == 0) {
99             return new ReadOnlyShardDataTreeTransaction(txId, dataTree.takeSnapshot());
100         }
101
102         return ensureTransactionChain(txId.getHistoryId()).newReadOnlyTransaction(txId);
103     }
104
105     ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
106         if (txId.getHistoryId().getHistoryId() == 0) {
107             return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
108                     .newModification());
109         }
110
111         return ensureTransactionChain(txId.getHistoryId()).newReadWriteTransaction(txId);
112     }
113
114     public void notifyListeners(final DataTreeCandidate candidate) {
115         treeChangeListenerPublisher.publishChanges(candidate, logContext);
116         dataChangeListenerPublisher.publishChanges(candidate, logContext);
117     }
118
119     void notifyOfInitialData(final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
120             NormalizedNode<?, ?>>> listenerReg, final Optional<DataTreeCandidate> currentState) {
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 LocalHistoryIdentifier 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(final 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(final 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 }