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