Renamed controller.md.sal.dom.store.impl -> mdsal.dom.store.inmemory
[mdsal.git] / dom / mdsal-dom-inmemory-datastore / src / main / java / org / opendaylight / mdsal / dom / store / inmemory / InMemoryDOMDataStore.java
1 /*
2  * Copyright (c) 2014 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.mdsal.dom.store.inmemory;
9
10 import org.opendaylight.mdsal.dom.store.inmemory.tree.ListenerTree;
11
12 import org.opendaylight.mdsal.dom.spi.store.DOMStore;
13 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
14 import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
15 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
16 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
17 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
18 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
19 import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedTransactions;
20 import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction;
21 import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction.TransactionReadyPrototype;
22 import org.opendaylight.mdsal.common.api.AsyncDataChangeListener;
23 import org.opendaylight.mdsal.common.api.AsyncDataBroker.DataChangeScope;
24 import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
25 import com.google.common.base.Optional;
26 import com.google.common.base.Preconditions;
27 import java.util.concurrent.ExecutorService;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.atomic.AtomicLong;
30 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
31 import org.opendaylight.yangtools.concepts.Identifiable;
32 import org.opendaylight.yangtools.concepts.ListenerRegistration;
33 import org.opendaylight.yangtools.util.ExecutorServiceUtil;
34 import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager;
35 import org.opendaylight.yangtools.util.concurrent.QueuedNotificationManager.Invoker;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
39 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
40 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
41 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
42 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
43 import org.opendaylight.yangtools.yang.data.impl.schema.tree.InMemoryDataTreeFactory;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * In-memory DOM Data Store
51  *
52  * Implementation of {@link DOMStore} which uses {@link DataTree} and other
53  * classes such as {@link SnapshotBackedWriteTransaction}.
54  * {@link org.opendaylight.mdsal.dom.spi.store.SnapshotBackedReadTransaction} and {@link ResolveDataChangeEventsTask}
55  * to implement {@link DOMStore} contract.
56  *
57  */
58 public class InMemoryDOMDataStore extends TransactionReadyPrototype<String> implements DOMStore, Identifiable<String>, SchemaContextListener, AutoCloseable, DOMStoreTreeChangePublisher {
59     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
60
61     private static final Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> DCL_NOTIFICATION_MGR_INVOKER =
62             new Invoker<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent>() {
63                 @Override
64                 public void invokeListener(final DataChangeListenerRegistration<?> listener,
65                                            final DOMImmutableDataChangeEvent notification ) {
66                     final AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> inst = listener.getInstance();
67                     if (inst != null) {
68                         inst.onDataChanged(notification);
69                     }
70                 }
71             };
72
73     private final DataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
74     private final ListenerTree listenerTree = ListenerTree.create();
75     private final AtomicLong txCounter = new AtomicLong(0);
76
77     private final QueuedNotificationManager<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent> dataChangeListenerNotificationManager;
78     private final InMemoryDOMStoreTreeChangePublisher changePublisher;
79     private final ExecutorService dataChangeListenerExecutor;
80     private final boolean debugTransactions;
81     private final String name;
82
83     private volatile AutoCloseable closeable;
84
85     public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor) {
86         this(name, dataChangeListenerExecutor, InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE, false);
87     }
88
89     public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor,
90             final int maxDataChangeListenerQueueSize, final boolean debugTransactions) {
91         this.name = Preconditions.checkNotNull(name);
92         this.dataChangeListenerExecutor = Preconditions.checkNotNull(dataChangeListenerExecutor);
93         this.debugTransactions = debugTransactions;
94
95         dataChangeListenerNotificationManager =
96                 new QueuedNotificationManager<>(this.dataChangeListenerExecutor,
97                         DCL_NOTIFICATION_MGR_INVOKER, maxDataChangeListenerQueueSize,
98                         "DataChangeListenerQueueMgr");
99         changePublisher = new InMemoryDOMStoreTreeChangePublisher(this.dataChangeListenerExecutor, maxDataChangeListenerQueueSize);
100     }
101
102     public void setCloseable(final AutoCloseable closeable) {
103         this.closeable = closeable;
104     }
105
106     public QueuedNotificationManager<?, ?> getDataChangeListenerNotificationManager() {
107         return dataChangeListenerNotificationManager;
108     }
109
110     @Override
111     public final String getIdentifier() {
112         return name;
113     }
114
115     @Override
116     public DOMStoreReadTransaction newReadOnlyTransaction() {
117         return SnapshotBackedTransactions.newReadTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot());
118     }
119
120     @Override
121     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
122         return SnapshotBackedTransactions.newReadWriteTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot(), this);
123     }
124
125     @Override
126     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
127         return SnapshotBackedTransactions.newWriteTransaction(nextIdentifier(), debugTransactions, dataTree.takeSnapshot(), this);
128     }
129
130     @Override
131     public DOMStoreTransactionChain createTransactionChain() {
132         return new DOMStoreTransactionChainImpl(this);
133     }
134
135     @Override
136     public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
137         dataTree.setSchemaContext(ctx);
138     }
139
140     @Override
141     public void close() {
142         ExecutorServiceUtil.tryGracefulShutdown(dataChangeListenerExecutor, 30, TimeUnit.SECONDS);
143
144         if(closeable != null) {
145             try {
146                 closeable.close();
147             } catch(Exception e) {
148                 LOG.debug("Error closing instance", e);
149             }
150         }
151     }
152
153     public final boolean getDebugTransactions() {
154         return debugTransactions;
155     }
156
157     final DataTreeSnapshot takeSnapshot() {
158         return dataTree.takeSnapshot();
159     }
160
161     @Override
162     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
163             final YangInstanceIdentifier path, final L listener, final DataChangeScope scope) {
164
165         /*
166          * Make sure commit is not occurring right now. Listener has to be
167          * registered and its state capture enqueued at a consistent point.
168          *
169          * FIXME: improve this to read-write lock, such that multiple listener
170          * registrations can occur simultaneously
171          */
172         final DataChangeListenerRegistration<L> reg;
173         synchronized (this) {
174             LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
175
176             reg = listenerTree.registerDataChangeListener(path, listener, scope);
177
178             Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
179             if (currentState.isPresent()) {
180                 final NormalizedNode<?, ?> data = currentState.get();
181
182                 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
183                         .setAfter(data) //
184                         .addCreated(path, data) //
185                         .build();
186
187                 dataChangeListenerNotificationManager.submitNotification(reg, event);
188             }
189         }
190
191         return new AbstractListenerRegistration<L>(listener) {
192             @Override
193             protected void removeRegistration() {
194                 synchronized (InMemoryDOMDataStore.this) {
195                     reg.close();
196                 }
197             }
198         };
199     }
200
201     @Override
202     public synchronized <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(final YangInstanceIdentifier treeId, final L listener) {
203         /*
204          * Make sure commit is not occurring right now. Listener has to be
205          * registered and its state capture enqueued at a consistent point.
206          */
207         return changePublisher.registerTreeChangeListener(treeId, listener, dataTree.takeSnapshot());
208     }
209
210     @Override
211     protected void transactionAborted(final SnapshotBackedWriteTransaction<String> tx) {
212         LOG.debug("Tx: {} is closed.", tx.getIdentifier());
213     }
214
215     @Override
216     protected DOMStoreThreePhaseCommitCohort transactionReady(final SnapshotBackedWriteTransaction<String> tx, final DataTreeModification modification) {
217         LOG.debug("Tx: {} is submitted. Modifications: {}", tx.getIdentifier(), modification);
218         return new InMemoryDOMStoreThreePhaseCommitCohort(this, tx, modification);
219     }
220
221     String nextIdentifier() {
222         return name + "-" + txCounter.getAndIncrement();
223     }
224
225     void validate(final DataTreeModification modification) throws DataValidationFailedException {
226         dataTree.validate(modification);
227     }
228
229     DataTreeCandidate prepare(final DataTreeModification modification) {
230         return dataTree.prepare(modification);
231     }
232
233     synchronized void commit(final DataTreeCandidate candidate) {
234         dataTree.commit(candidate);
235         changePublisher.publishChange(candidate);
236         ResolveDataChangeEventsTask.create(candidate, listenerTree).resolve(dataChangeListenerNotificationManager);
237     }
238 }