2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.md.sal.dom.store.impl;
10 import static com.google.common.base.Preconditions.checkNotNull;
11 import static com.google.common.base.Preconditions.checkState;
13 import java.util.Collections;
14 import java.util.concurrent.Callable;
15 import java.util.concurrent.atomic.AtomicLong;
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.DOMStoreWriteTransaction;
32 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
33 import org.opendaylight.yangtools.concepts.Identifiable;
34 import org.opendaylight.yangtools.concepts.ListenerRegistration;
35 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import com.google.common.base.Objects;
43 import com.google.common.base.Objects.ToStringHelper;
44 import com.google.common.base.Optional;
45 import com.google.common.base.Preconditions;
46 import com.google.common.util.concurrent.Futures;
47 import com.google.common.util.concurrent.ListenableFuture;
48 import com.google.common.util.concurrent.ListeningExecutorService;
50 public class InMemoryDOMDataStore implements DOMStore, Identifiable<String>, SchemaContextListener {
51 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
52 private final DataTree dataTree = InMemoryDataTreeFactory.getInstance().create();
53 private final ListenerTree listenerTree = ListenerTree.create();
54 private final AtomicLong txCounter = new AtomicLong(0);
55 private final ListeningExecutorService executor;
56 private final String name;
58 public InMemoryDOMDataStore(final String name, final ListeningExecutorService executor) {
59 this.name = Preconditions.checkNotNull(name);
60 this.executor = Preconditions.checkNotNull(executor);
64 public final String getIdentifier() {
69 public DOMStoreReadTransaction newReadOnlyTransaction() {
70 return new SnapshotBackedReadTransaction(nextIdentifier(), dataTree.takeSnapshot());
74 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
75 return new SnapshotBackedReadWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
79 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
80 return new SnapshotBackedWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
84 public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
85 dataTree.setSchemaContext(ctx);
89 public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
90 final InstanceIdentifier path, final L listener, final DataChangeScope scope) {
93 * Make sure commit is not occurring right now. Listener has to be
94 * registered and its state capture enqueued at a consistent point.
96 * FIXME: improve this to read-write lock, such that multiple listener
97 * registrations can occur simultaneously
99 final DataChangeListenerRegistration<L> reg;
100 synchronized (this) {
101 LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
103 reg = listenerTree.registerDataChangeListener(path, listener, scope);
105 Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
106 if (currentState.isPresent()) {
107 final NormalizedNode<?, ?> data = currentState.get();
109 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
111 .addCreated(path, data) //
113 executor.submit(new ChangeListenerNotifyTask(Collections.singletonList(reg), event));
117 return new AbstractListenerRegistration<L>(listener) {
119 protected void removeRegistration() {
120 synchronized (InMemoryDOMDataStore.this) {
127 private synchronized DOMStoreThreePhaseCommitCohort submit(final SnapshotBackedWriteTransaction writeTx) {
128 LOG.debug("Tx: {} is submitted. Modifications: {}", writeTx.getIdentifier(), writeTx.getMutatedView());
129 return new ThreePhaseCommitImpl(writeTx);
132 private Object nextIdentifier() {
133 return name + "-" + txCounter.getAndIncrement();
136 private static abstract class AbstractDOMStoreTransaction implements DOMStoreTransaction {
137 private final Object identifier;
139 protected AbstractDOMStoreTransaction(final Object identifier) {
140 this.identifier = identifier;
144 public final Object getIdentifier() {
149 public final String toString() {
150 return addToStringAttributes(Objects.toStringHelper(this)).toString();
154 * Add class-specific toString attributes.
156 * @param toStringHelper
157 * ToStringHelper instance
158 * @return ToStringHelper instance which was passed in
160 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
161 return toStringHelper.add("id", identifier);
165 private static final class SnapshotBackedReadTransaction extends AbstractDOMStoreTransaction implements
166 DOMStoreReadTransaction {
167 private DataTreeSnapshot stableSnapshot;
169 public SnapshotBackedReadTransaction(final Object identifier, final DataTreeSnapshot snapshot) {
171 this.stableSnapshot = Preconditions.checkNotNull(snapshot);
172 LOG.debug("ReadOnly Tx: {} allocated with snapshot {}", identifier, snapshot);
176 public void close() {
177 LOG.debug("Store transaction: {} : Closed", getIdentifier());
178 stableSnapshot = null;
182 public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
183 checkNotNull(path, "Path must not be null.");
184 checkState(stableSnapshot != null, "Transaction is closed");
185 return Futures.immediateFuture(stableSnapshot.readNode(path));
189 private static class SnapshotBackedWriteTransaction extends AbstractDOMStoreTransaction implements
190 DOMStoreWriteTransaction {
191 private DataTreeModification mutableTree;
192 private InMemoryDOMDataStore store;
193 private boolean ready = false;
195 public SnapshotBackedWriteTransaction(final Object identifier, final DataTreeSnapshot snapshot,
196 final InMemoryDOMDataStore store) {
198 mutableTree = snapshot.newModification();
200 LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
204 public void close() {
205 LOG.debug("Store transaction: {} : Closed", getIdentifier());
206 this.mutableTree = null;
211 public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
214 LOG.trace("Tx: {} Write: {}:{}", getIdentifier(), path, data);
215 mutableTree.write(path, data);
216 // FIXME: Add checked exception
217 } catch (Exception e) {
218 LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, mutableTree, e);
223 public void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
226 LOG.trace("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
227 mutableTree.merge(path, data);
228 // FIXME: Add checked exception
229 } catch (Exception e) {
230 LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, mutableTree, e);
235 public void delete(final InstanceIdentifier path) {
238 LOG.trace("Tx: {} Delete: {}", getIdentifier(), path);
239 mutableTree.delete(path);
240 // FIXME: Add checked exception
241 } catch (Exception e) {
242 LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, mutableTree, e);
246 protected final boolean isReady() {
250 protected final void checkNotReady() {
251 checkState(!ready, "Transaction %s is ready. No further modifications allowed.", getIdentifier());
255 public synchronized DOMStoreThreePhaseCommitCohort ready() {
256 checkState(!ready, "Transaction %s is already ready.", getIdentifier());
259 LOG.debug("Store transaction: {} : Ready", getIdentifier());
261 return store.submit(this);
264 protected DataTreeModification getMutatedView() {
269 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
270 return toStringHelper.add("ready", isReady());
274 private static class SnapshotBackedReadWriteTransaction extends SnapshotBackedWriteTransaction implements
275 DOMStoreReadWriteTransaction {
277 protected SnapshotBackedReadWriteTransaction(final Object identifier, final DataTreeSnapshot snapshot,
278 final InMemoryDOMDataStore store) {
279 super(identifier, snapshot, store);
283 public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
284 LOG.trace("Tx: {} Read: {}", getIdentifier(), path);
286 return Futures.immediateFuture(getMutatedView().readNode(path));
287 } catch (Exception e) {
288 LOG.error("Tx: {} Failed Read of {}", getIdentifier(), path, e);
294 private class ThreePhaseCommitImpl implements DOMStoreThreePhaseCommitCohort {
296 private final SnapshotBackedWriteTransaction transaction;
297 private final DataTreeModification modification;
299 private ResolveDataChangeEventsTask listenerResolver;
300 private DataTreeCandidate candidate;
302 public ThreePhaseCommitImpl(final SnapshotBackedWriteTransaction writeTransaction) {
303 this.transaction = writeTransaction;
304 this.modification = transaction.getMutatedView();
308 public ListenableFuture<Boolean> canCommit() {
309 return executor.submit(new Callable<Boolean>() {
311 public Boolean call() {
313 dataTree.validate(modification);
314 LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
316 } catch (DataPreconditionFailedException e) {
317 LOG.warn("Store Tx: {} Data Precondition failed for {}.",transaction.getIdentifier(),e.getPath(),e);
325 public ListenableFuture<Void> preCommit() {
326 return executor.submit(new Callable<Void>() {
329 candidate = dataTree.prepare(modification);
330 listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
337 public ListenableFuture<Void> abort() {
339 return Futures.immediateFuture(null);
343 public ListenableFuture<Void> commit() {
344 checkState(candidate != null, "Proposed subtree must be computed");
347 * The commit has to occur atomically with regard to listener
350 synchronized (this) {
351 dataTree.commit(candidate);
353 for (ChangeListenerNotifyTask task : listenerResolver.call()) {
354 LOG.trace("Scheduling invocation of listeners: {}", task);
355 executor.submit(task);
359 return Futures.immediateFuture(null);