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