Fix checkstyle violations in sal-inmemory-datastore
[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                 if (inst != null) {
71                     inst.onDataChanged(notification);
72                 }
73             };
74
75     private final DataTree dataTree;
76     private final ListenerTree listenerTree = ListenerTree.create();
77     private final AtomicLong txCounter = new AtomicLong(0);
78
79     private final QueuedNotificationManager<DataChangeListenerRegistration<?>, DOMImmutableDataChangeEvent>
80             dataChangeListenerNotificationManager;
81     private final InMemoryDOMStoreTreeChangePublisher changePublisher;
82     private final ExecutorService dataChangeListenerExecutor;
83     private final boolean debugTransactions;
84     private final String name;
85
86     private volatile AutoCloseable closeable;
87
88     public InMemoryDOMDataStore(final String name, final ExecutorService dataChangeListenerExecutor) {
89         this(name, LogicalDatastoreType.OPERATIONAL, dataChangeListenerExecutor,
90             InMemoryDOMDataStoreConfigProperties.DEFAULT_MAX_DATA_CHANGE_LISTENER_QUEUE_SIZE, false);
91     }
92
93     public InMemoryDOMDataStore(final String name, final LogicalDatastoreType type,
94             final ExecutorService dataChangeListenerExecutor,
95             final int maxDataChangeListenerQueueSize, final boolean debugTransactions) {
96         this.name = Preconditions.checkNotNull(name);
97         this.dataChangeListenerExecutor = Preconditions.checkNotNull(dataChangeListenerExecutor);
98         this.debugTransactions = debugTransactions;
99
100         dataChangeListenerNotificationManager =
101                 new QueuedNotificationManager<>(this.dataChangeListenerExecutor,
102                         DCL_NOTIFICATION_MGR_INVOKER, maxDataChangeListenerQueueSize,
103                         "DataChangeListenerQueueMgr");
104         changePublisher = new InMemoryDOMStoreTreeChangePublisher(this.dataChangeListenerExecutor,
105                 maxDataChangeListenerQueueSize);
106
107         switch (type) {
108             case CONFIGURATION:
109                 dataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_CONFIGURATION);
110                 break;
111             case OPERATIONAL:
112                 dataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL);
113                 break;
114             default:
115                 throw new IllegalArgumentException("Data store " + type + " not supported");
116         }
117     }
118
119     public void setCloseable(final AutoCloseable closeable) {
120         this.closeable = closeable;
121     }
122
123     public QueuedNotificationManager<?, ?> getDataChangeListenerNotificationManager() {
124         return dataChangeListenerNotificationManager;
125     }
126
127     @Override
128     public final String getIdentifier() {
129         return name;
130     }
131
132     @Override
133     public DOMStoreReadTransaction newReadOnlyTransaction() {
134         return SnapshotBackedTransactions.newReadTransaction(nextIdentifier(), debugTransactions,
135                 dataTree.takeSnapshot());
136     }
137
138     @Override
139     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
140         return SnapshotBackedTransactions.newReadWriteTransaction(nextIdentifier(), debugTransactions,
141                 dataTree.takeSnapshot(), this);
142     }
143
144     @Override
145     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
146         return SnapshotBackedTransactions.newWriteTransaction(nextIdentifier(), debugTransactions,
147                 dataTree.takeSnapshot(), this);
148     }
149
150     @Override
151     public DOMStoreTransactionChain createTransactionChain() {
152         return new DOMStoreTransactionChainImpl(this);
153     }
154
155     @Override
156     public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
157         dataTree.setSchemaContext(ctx);
158     }
159
160     @Override
161     @SuppressWarnings("checkstyle:IllegalCatch")
162     public void close() {
163         ExecutorServiceUtil.tryGracefulShutdown(dataChangeListenerExecutor, 30, TimeUnit.SECONDS);
164
165         if (closeable != null) {
166             try {
167                 closeable.close();
168             } catch (Exception e) {
169                 LOG.debug("Error closing instance", e);
170             }
171         }
172     }
173
174     public final boolean getDebugTransactions() {
175         return debugTransactions;
176     }
177
178     final DataTreeSnapshot takeSnapshot() {
179         return dataTree.takeSnapshot();
180     }
181
182     @Override
183     public <L extends AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L>
184             registerChangeListener(final YangInstanceIdentifier path, final L listener, final DataChangeScope scope) {
185
186         /*
187          * Make sure commit is not occurring right now. Listener has to be
188          * registered and its state capture enqueued at a consistent point.
189          *
190          * FIXME: improve this to read-write lock, such that multiple listener
191          * registrations can occur simultaneously
192          */
193         final DataChangeListenerRegistration<L> reg;
194         synchronized (this) {
195             LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
196
197             reg = listenerTree.registerDataChangeListener(path, listener, scope);
198
199             Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
200             if (currentState.isPresent()) {
201                 final NormalizedNode<?, ?> data = currentState.get();
202
203                 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
204                         .setAfter(data) //
205                         .addCreated(path, data) //
206                         .build();
207
208                 dataChangeListenerNotificationManager.submitNotification(reg, event);
209             }
210         }
211
212         return new AbstractListenerRegistration<L>(listener) {
213             @Override
214             protected void removeRegistration() {
215                 synchronized (InMemoryDOMDataStore.this) {
216                     reg.close();
217                 }
218             }
219         };
220     }
221
222     @Override
223     public synchronized <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
224             final YangInstanceIdentifier treeId, final L listener) {
225         /*
226          * Make sure commit is not occurring right now. Listener has to be
227          * registered and its state capture enqueued at a consistent point.
228          */
229         return changePublisher.registerTreeChangeListener(treeId, listener, dataTree.takeSnapshot());
230     }
231
232     @Override
233     protected void transactionAborted(final SnapshotBackedWriteTransaction<String> tx) {
234         LOG.debug("Tx: {} is closed.", tx.getIdentifier());
235     }
236
237     @Override
238     protected DOMStoreThreePhaseCommitCohort transactionReady(final SnapshotBackedWriteTransaction<String> tx,
239                                                               final DataTreeModification modification,
240                                                               final Exception readyError) {
241         LOG.debug("Tx: {} is submitted. Modifications: {}", tx.getIdentifier(), modification);
242         return new InMemoryDOMStoreThreePhaseCommitCohort(this, tx, modification, readyError);
243     }
244
245     String nextIdentifier() {
246         return name + "-" + txCounter.getAndIncrement();
247     }
248
249     void validate(final DataTreeModification modification) throws DataValidationFailedException {
250         dataTree.validate(modification);
251     }
252
253     DataTreeCandidate prepare(final DataTreeModification modification) {
254         return dataTree.prepare(modification);
255     }
256
257     synchronized void commit(final DataTreeCandidate candidate) {
258         dataTree.commit(candidate);
259         changePublisher.publishChange(candidate);
260         ResolveDataChangeEventsTask.create(candidate, listenerTree).resolve(dataChangeListenerNotificationManager);
261     }
262 }