BUG-614: migrate RuntimeGeneratedInvoker
[controller.git] / opendaylight / md-sal / sal-dom-broker / 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 static com.google.common.base.Preconditions.checkState;
11
12 import java.util.Collections;
13 import java.util.concurrent.Callable;
14 import java.util.concurrent.atomic.AtomicLong;
15
16 import javax.annotation.concurrent.GuardedBy;
17
18 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
19 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
20 import org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction.TransactionReadyPrototype;
21 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataPreconditionFailedException;
22 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTree;
23 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeCandidate;
24 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeModification;
25 import org.opendaylight.controller.md.sal.dom.store.impl.tree.DataTreeSnapshot;
26 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
27 import org.opendaylight.controller.md.sal.dom.store.impl.tree.data.InMemoryDataTreeFactory;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
31 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
32 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
33 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
34 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
35 import org.opendaylight.yangtools.concepts.Identifiable;
36 import org.opendaylight.yangtools.concepts.ListenerRegistration;
37 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import com.google.common.base.Optional;
45 import com.google.common.base.Preconditions;
46 import com.google.common.util.concurrent.FutureCallback;
47 import com.google.common.util.concurrent.Futures;
48 import com.google.common.util.concurrent.ListenableFuture;
49 import com.google.common.util.concurrent.ListeningExecutorService;
50
51 /**
52  * In-memory DOM Data Store
53  * 
54  * Implementation of {@link DOMStore} which uses {@link DataTree} and other
55  * classes such as {@link SnapshotBackedWriteTransaction}.
56  * {@link SnapshotBackedReadTransaction} and {@link ResolveDataChangeEventsTask}
57  * to implement {@link DOMStore} contract.
58  * 
59  */
60 public class InMemoryDOMDataStore implements DOMStore, Identifiable<String>, SchemaContextListener,
61         TransactionReadyPrototype {
62     private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
63     private final DataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
64     private final ListenerTree listenerTree = ListenerTree.create();
65     private final AtomicLong txCounter = new AtomicLong(0);
66     private final ListeningExecutorService executor;
67     private final String name;
68
69     public InMemoryDOMDataStore(final String name, final ListeningExecutorService executor) {
70         this.name = Preconditions.checkNotNull(name);
71         this.executor = Preconditions.checkNotNull(executor);
72     }
73
74     @Override
75     public final String getIdentifier() {
76         return name;
77     }
78
79     @Override
80     public DOMStoreReadTransaction newReadOnlyTransaction() {
81         return new SnapshotBackedReadTransaction(nextIdentifier(), dataTree.takeSnapshot());
82     }
83
84     @Override
85     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
86         return new SnapshotBackedReadWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
87     }
88
89     @Override
90     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
91         return new SnapshotBackedWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
92     }
93
94     @Override
95     public DOMStoreTransactionChain createTransactionChain() {
96         return new DOMStoreTransactionChainImpl();
97     }
98
99     @Override
100     public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
101         dataTree.setSchemaContext(ctx);
102     }
103
104     @Override
105     public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
106             final InstanceIdentifier path, final L listener, final DataChangeScope scope) {
107
108         /*
109          * Make sure commit is not occurring right now. Listener has to be
110          * registered and its state capture enqueued at a consistent point.
111          * 
112          * FIXME: improve this to read-write lock, such that multiple listener
113          * registrations can occur simultaneously
114          */
115         final DataChangeListenerRegistration<L> reg;
116         synchronized (this) {
117             LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
118
119             reg = listenerTree.registerDataChangeListener(path, listener, scope);
120
121             Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
122             if (currentState.isPresent()) {
123                 final NormalizedNode<?, ?> data = currentState.get();
124
125                 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
126                         .setAfter(data) //
127                         .addCreated(path, data) //
128                         .build();
129                 executor.submit(new ChangeListenerNotifyTask(Collections.singletonList(reg), event));
130             }
131         }
132
133         return new AbstractListenerRegistration<L>(listener) {
134             @Override
135             protected void removeRegistration() {
136                 synchronized (InMemoryDOMDataStore.this) {
137                     reg.close();
138                 }
139             }
140         };
141     }
142
143     @Override
144     public synchronized DOMStoreThreePhaseCommitCohort ready(final SnapshotBackedWriteTransaction writeTx) {
145         LOG.debug("Tx: {} is submitted. Modifications: {}", writeTx.getIdentifier(), writeTx.getMutatedView());
146         return new ThreePhaseCommitImpl(writeTx);
147     }
148
149     private Object nextIdentifier() {
150         return name + "-" + txCounter.getAndIncrement();
151     }
152
153     private class DOMStoreTransactionChainImpl implements DOMStoreTransactionChain, TransactionReadyPrototype {
154
155         @GuardedBy("this")
156         private SnapshotBackedWriteTransaction latestOutstandingTx;
157
158         private boolean chainFailed = false;
159
160         private void checkFailed() {
161             Preconditions.checkState(!chainFailed, "Transaction chain is failed.");
162         }
163
164         @Override
165         public synchronized DOMStoreReadTransaction newReadOnlyTransaction() {
166             final DataTreeSnapshot snapshot;
167             checkFailed();
168             if (latestOutstandingTx != null) {
169                 checkState(latestOutstandingTx.isReady(), "Previous transaction in chain must be ready.");
170                 snapshot = latestOutstandingTx.getMutatedView();
171             } else {
172                 snapshot = dataTree.takeSnapshot();
173             }
174             return new SnapshotBackedReadTransaction(nextIdentifier(), snapshot);
175         }
176
177         @Override
178         public synchronized DOMStoreReadWriteTransaction newReadWriteTransaction() {
179             final DataTreeSnapshot snapshot;
180             checkFailed();
181             if (latestOutstandingTx != null) {
182                 checkState(latestOutstandingTx.isReady(), "Previous transaction in chain must be ready.");
183                 snapshot = latestOutstandingTx.getMutatedView();
184             } else {
185                 snapshot = dataTree.takeSnapshot();
186             }
187             final SnapshotBackedReadWriteTransaction ret = new SnapshotBackedReadWriteTransaction(nextIdentifier(),
188                     snapshot, this);
189             latestOutstandingTx = ret;
190             return ret;
191         }
192
193         @Override
194         public synchronized DOMStoreWriteTransaction newWriteOnlyTransaction() {
195             final DataTreeSnapshot snapshot;
196             checkFailed();
197             if (latestOutstandingTx != null) {
198                 checkState(latestOutstandingTx.isReady(), "Previous transaction in chain must be ready.");
199                 snapshot = latestOutstandingTx.getMutatedView();
200             } else {
201                 snapshot = dataTree.takeSnapshot();
202             }
203             final SnapshotBackedWriteTransaction ret = new SnapshotBackedWriteTransaction(nextIdentifier(), snapshot,
204                     this);
205             latestOutstandingTx = ret;
206             return ret;
207         }
208
209         @Override
210         public DOMStoreThreePhaseCommitCohort ready(final SnapshotBackedWriteTransaction tx) {
211             DOMStoreThreePhaseCommitCohort storeCohort = InMemoryDOMDataStore.this.ready(tx);
212             return new ChainedTransactionCommitImpl(tx, storeCohort, this);
213         }
214
215         @Override
216         public void close() {
217
218         }
219
220         protected synchronized void onTransactionFailed(final SnapshotBackedWriteTransaction transaction,
221                 final Throwable t) {
222             chainFailed = true;
223
224         }
225
226         public synchronized void onTransactionCommited(final SnapshotBackedWriteTransaction transaction) {
227             // If commited transaction is latestOutstandingTx we clear
228             // latestOutstandingTx
229             // field in order to base new transactions on Datastore Data Tree
230             // directly.
231             if (transaction.equals(latestOutstandingTx)) {
232                 latestOutstandingTx = null;
233             }
234         }
235
236     }
237
238     private static class ChainedTransactionCommitImpl implements DOMStoreThreePhaseCommitCohort {
239
240         private final SnapshotBackedWriteTransaction transaction;
241         private final DOMStoreThreePhaseCommitCohort delegate;
242
243         private final DOMStoreTransactionChainImpl txChain;
244
245         protected ChainedTransactionCommitImpl(final SnapshotBackedWriteTransaction transaction,
246                 final DOMStoreThreePhaseCommitCohort delegate, final DOMStoreTransactionChainImpl txChain) {
247             super();
248             this.transaction = transaction;
249             this.delegate = delegate;
250             this.txChain = txChain;
251         }
252
253         @Override
254         public ListenableFuture<Boolean> canCommit() {
255             return delegate.canCommit();
256         }
257
258         @Override
259         public ListenableFuture<Void> preCommit() {
260             return delegate.preCommit();
261         }
262
263         @Override
264         public ListenableFuture<Void> abort() {
265             return delegate.abort();
266         }
267
268         @Override
269         public ListenableFuture<Void> commit() {
270             ListenableFuture<Void> commitFuture = delegate.commit();
271             Futures.addCallback(commitFuture, new FutureCallback<Void>() {
272                 @Override
273                 public void onFailure(final Throwable t) {
274                     txChain.onTransactionFailed(transaction, t);
275                 }
276
277                 @Override
278                 public void onSuccess(final Void result) {
279                     txChain.onTransactionCommited(transaction);
280                 }
281
282             });
283             return commitFuture;
284         }
285
286     }
287
288     private class ThreePhaseCommitImpl implements DOMStoreThreePhaseCommitCohort {
289
290         private final SnapshotBackedWriteTransaction transaction;
291         private final DataTreeModification modification;
292
293         private ResolveDataChangeEventsTask listenerResolver;
294         private DataTreeCandidate candidate;
295
296         public ThreePhaseCommitImpl(final SnapshotBackedWriteTransaction writeTransaction) {
297             this.transaction = writeTransaction;
298             this.modification = transaction.getMutatedView();
299         }
300
301         @Override
302         public ListenableFuture<Boolean> canCommit() {
303             return executor.submit(new Callable<Boolean>() {
304                 @Override
305                 public Boolean call() {
306                     try {
307                         dataTree.validate(modification);
308                         LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
309                         return true;
310                     } catch (DataPreconditionFailedException e) {
311                         LOG.warn("Store Tx: {} Data Precondition failed for {}.", transaction.getIdentifier(),
312                                 e.getPath(), e);
313                         return false;
314                     }
315                 }
316             });
317         }
318
319         @Override
320         public ListenableFuture<Void> preCommit() {
321             return executor.submit(new Callable<Void>() {
322                 @Override
323                 public Void call() {
324                     candidate = dataTree.prepare(modification);
325                     listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
326                     return null;
327                 }
328             });
329         }
330
331         @Override
332         public ListenableFuture<Void> abort() {
333             candidate = null;
334             return Futures.immediateFuture(null);
335         }
336
337         @Override
338         public ListenableFuture<Void> commit() {
339             checkState(candidate != null, "Proposed subtree must be computed");
340
341             /*
342              * The commit has to occur atomically with regard to listener
343              * registrations.
344              */
345             synchronized (this) {
346                 dataTree.commit(candidate);
347
348                 for (ChangeListenerNotifyTask task : listenerResolver.call()) {
349                     LOG.trace("Scheduling invocation of listeners: {}", task);
350                     executor.submit(task);
351                 }
352             }
353
354             return Futures.immediateFuture(null);
355         }
356     }
357 }