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