BUG-5280: implement message queueing
[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         this.treeChangeListenerPublisher = treeChangeListenerPublisher;
64         this.dataChangeListenerPublisher = dataChangeListenerPublisher;
65         this.logContext = logContext;
66     }
67
68     public ShardDataTree(final SchemaContext schemaContext, final TreeType treeType) {
69         this(schemaContext, treeType, new DefaultShardDataTreeChangeListenerPublisher(),
70                 new DefaultShardDataChangeListenerPublisher(), "");
71     }
72
73     public TipProducingDataTree getDataTree() {
74         return dataTree;
75     }
76
77     SchemaContext getSchemaContext() {
78         return schemaContext;
79     }
80
81     void updateSchemaContext(final SchemaContext schemaContext) {
82         Preconditions.checkNotNull(schemaContext);
83         this.schemaContext = schemaContext;
84         dataTree.setSchemaContext(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(DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
120             NormalizedNode<?, ?>>> listenerReg, Optional<DataTreeCandidate> currentState) {
121
122         if(currentState.isPresent()) {
123             ShardDataChangeListenerPublisher localPublisher = dataChangeListenerPublisher.newInstance();
124             localPublisher.registerDataChangeListener(listenerReg.getPath(), listenerReg.getInstance(),
125                     listenerReg.getScope());
126             localPublisher.publishChanges(currentState.get(), logContext);
127         }
128     }
129
130     void notifyOfInitialData(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
131             final Optional<DataTreeCandidate> currentState) {
132         if(currentState.isPresent()) {
133             ShardDataTreeChangeListenerPublisher localPublisher = treeChangeListenerPublisher.newInstance();
134             localPublisher.registerTreeChangeListener(path, listener);
135             localPublisher.publishChanges(currentState.get(), logContext);
136         }
137     }
138
139     void closeAllTransactionChains() {
140         for (ShardDataTreeTransactionChain chain : transactionChains.values()) {
141             chain.close();
142         }
143
144         transactionChains.clear();
145     }
146
147     void closeTransactionChain(final LocalHistoryIdentifier transactionChainId) {
148         final ShardDataTreeTransactionChain chain = transactionChains.remove(transactionChainId);
149         if (chain != null) {
150             chain.close();
151         } else {
152             LOG.debug("{}: Closing non-existent transaction chain {}", logContext, transactionChainId);
153         }
154     }
155
156     Entry<DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>,
157             Optional<DataTreeCandidate>> registerChangeListener(final YangInstanceIdentifier path,
158                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener,
159                     final DataChangeScope scope) {
160         final DataChangeListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> reg =
161                 dataChangeListenerPublisher.registerDataChangeListener(path, listener, scope);
162
163         return new SimpleEntry<>(reg, readCurrentData());
164     }
165
166     private Optional<DataTreeCandidate> readCurrentData() {
167         final Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.EMPTY);
168         return currentState.isPresent() ? Optional.of(DataTreeCandidates.fromNormalizedNode(
169             YangInstanceIdentifier.EMPTY, currentState.get())) : Optional.<DataTreeCandidate>absent();
170     }
171
172     public Entry<ListenerRegistration<DOMDataTreeChangeListener>, Optional<DataTreeCandidate>> registerTreeChangeListener(
173             final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener) {
174         final ListenerRegistration<DOMDataTreeChangeListener> reg = treeChangeListenerPublisher.registerTreeChangeListener(
175                 path, listener);
176
177         return new SimpleEntry<>(reg, readCurrentData());
178     }
179
180     void applyForeignCandidate(final Identifier identifier, final DataTreeCandidate foreign) throws DataValidationFailedException {
181         LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
182
183         final DataTreeModification mod = dataTree.takeSnapshot().newModification();
184         DataTreeCandidates.applyToModification(mod, foreign);
185         mod.ready();
186
187         LOG.trace("{}: Applying foreign modification {}", logContext, mod);
188         dataTree.validate(mod);
189         final DataTreeCandidate candidate = dataTree.prepare(mod);
190         dataTree.commit(candidate);
191         notifyListeners(candidate);
192     }
193
194     @Override
195     void abortTransaction(final AbstractShardDataTreeTransaction<?> transaction) {
196         // Intentional no-op
197     }
198
199     @Override
200     ShardDataTreeCohort finishTransaction(final ReadWriteShardDataTreeTransaction transaction) {
201         final DataTreeModification snapshot = transaction.getSnapshot();
202         snapshot.ready();
203         return new SimpleShardDataTreeCohort(this, snapshot, transaction.getId());
204     }
205
206     public Optional<NormalizedNode<?, ?>> readNode(YangInstanceIdentifier path) {
207         return dataTree.takeSnapshot().readNode(path);
208     }
209
210     public DataTreeSnapshot takeSnapshot() {
211         return dataTree.takeSnapshot();
212     }
213
214     public DataTreeModification newModification() {
215         return dataTree.takeSnapshot().newModification();
216     }
217
218     // FIXME: This should be removed, it violates encapsulation
219     public DataTreeCandidate commit(DataTreeModification modification) throws DataValidationFailedException {
220         modification.ready();
221         dataTree.validate(modification);
222         DataTreeCandidateTip candidate = dataTree.prepare(modification);
223         dataTree.commit(candidate);
224         return candidate;
225     }
226 }