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