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.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;
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;
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;
59 public InMemoryDOMDataStore(final String name, final ListeningExecutorService executor) {
60 this.name = Preconditions.checkNotNull(name);
61 this.executor = Preconditions.checkNotNull(executor);
65 public final String getIdentifier() {
70 public DOMStoreReadTransaction newReadOnlyTransaction() {
71 return new SnapshotBackedReadTransaction(nextIdentifier(), dataTree.takeSnapshot());
75 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
76 return new SnapshotBackedReadWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
80 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
81 return new SnapshotBackedWriteTransaction(nextIdentifier(), dataTree.takeSnapshot(), this);
85 public DOMStoreTransactionChain createTransactionChain() {
86 throw new UnsupportedOperationException("Not implemented yet.");
90 public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
91 dataTree.setSchemaContext(ctx);
95 public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
96 final InstanceIdentifier path, final L listener, final DataChangeScope scope) {
99 * Make sure commit is not occurring right now. Listener has to be
100 * registered and its state capture enqueued at a consistent point.
102 * FIXME: improve this to read-write lock, such that multiple listener
103 * registrations can occur simultaneously
105 final DataChangeListenerRegistration<L> reg;
106 synchronized (this) {
107 LOG.debug("{}: Registering data change listener {} for {}", name, listener, path);
109 reg = listenerTree.registerDataChangeListener(path, listener, scope);
111 Optional<NormalizedNode<?, ?>> currentState = dataTree.takeSnapshot().readNode(path);
112 if (currentState.isPresent()) {
113 final NormalizedNode<?, ?> data = currentState.get();
115 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
117 .addCreated(path, data) //
119 executor.submit(new ChangeListenerNotifyTask(Collections.singletonList(reg), event));
123 return new AbstractListenerRegistration<L>(listener) {
125 protected void removeRegistration() {
126 synchronized (InMemoryDOMDataStore.this) {
133 private synchronized DOMStoreThreePhaseCommitCohort submit(final SnapshotBackedWriteTransaction writeTx) {
134 LOG.debug("Tx: {} is submitted. Modifications: {}", writeTx.getIdentifier(), writeTx.getMutatedView());
135 return new ThreePhaseCommitImpl(writeTx);
138 private Object nextIdentifier() {
139 return name + "-" + txCounter.getAndIncrement();
142 private static abstract class AbstractDOMStoreTransaction implements DOMStoreTransaction {
143 private final Object identifier;
145 protected AbstractDOMStoreTransaction(final Object identifier) {
146 this.identifier = identifier;
150 public final Object getIdentifier() {
155 public final String toString() {
156 return addToStringAttributes(Objects.toStringHelper(this)).toString();
160 * Add class-specific toString attributes.
162 * @param toStringHelper
163 * ToStringHelper instance
164 * @return ToStringHelper instance which was passed in
166 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
167 return toStringHelper.add("id", identifier);
171 private static final class SnapshotBackedReadTransaction extends AbstractDOMStoreTransaction implements
172 DOMStoreReadTransaction {
173 private DataTreeSnapshot stableSnapshot;
175 public SnapshotBackedReadTransaction(final Object identifier, final DataTreeSnapshot snapshot) {
177 this.stableSnapshot = Preconditions.checkNotNull(snapshot);
178 LOG.debug("ReadOnly Tx: {} allocated with snapshot {}", identifier, snapshot);
182 public void close() {
183 LOG.debug("Store transaction: {} : Closed", getIdentifier());
184 stableSnapshot = null;
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));
195 private static class SnapshotBackedWriteTransaction extends AbstractDOMStoreTransaction implements
196 DOMStoreWriteTransaction {
197 private DataTreeModification mutableTree;
198 private InMemoryDOMDataStore store;
199 private boolean ready = false;
201 public SnapshotBackedWriteTransaction(final Object identifier, final DataTreeSnapshot snapshot,
202 final InMemoryDOMDataStore store) {
204 mutableTree = snapshot.newModification();
206 LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
210 public void close() {
211 LOG.debug("Store transaction: {} : Closed", getIdentifier());
212 this.mutableTree = null;
217 public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
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);
229 public void merge(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
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);
241 public void delete(final InstanceIdentifier path) {
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);
252 protected final boolean isReady() {
256 protected final void checkNotReady() {
257 checkState(!ready, "Transaction %s is ready. No further modifications allowed.", getIdentifier());
261 public synchronized DOMStoreThreePhaseCommitCohort ready() {
262 checkState(!ready, "Transaction %s is already ready.", getIdentifier());
265 LOG.debug("Store transaction: {} : Ready", getIdentifier());
267 return store.submit(this);
270 protected DataTreeModification getMutatedView() {
275 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
276 return toStringHelper.add("ready", isReady());
280 private static class SnapshotBackedReadWriteTransaction extends SnapshotBackedWriteTransaction implements
281 DOMStoreReadWriteTransaction {
283 protected SnapshotBackedReadWriteTransaction(final Object identifier, final DataTreeSnapshot snapshot,
284 final InMemoryDOMDataStore store) {
285 super(identifier, snapshot, store);
289 public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
290 LOG.trace("Tx: {} Read: {}", getIdentifier(), path);
292 return Futures.immediateFuture(getMutatedView().readNode(path));
293 } catch (Exception e) {
294 LOG.error("Tx: {} Failed Read of {}", getIdentifier(), path, e);
300 private class ThreePhaseCommitImpl implements DOMStoreThreePhaseCommitCohort {
302 private final SnapshotBackedWriteTransaction transaction;
303 private final DataTreeModification modification;
305 private ResolveDataChangeEventsTask listenerResolver;
306 private DataTreeCandidate candidate;
308 public ThreePhaseCommitImpl(final SnapshotBackedWriteTransaction writeTransaction) {
309 this.transaction = writeTransaction;
310 this.modification = transaction.getMutatedView();
314 public ListenableFuture<Boolean> canCommit() {
315 return executor.submit(new Callable<Boolean>() {
317 public Boolean call() {
319 dataTree.validate(modification);
320 LOG.debug("Store Transaction: {} can be committed", transaction.getIdentifier());
322 } catch (DataPreconditionFailedException e) {
323 LOG.warn("Store Tx: {} Data Precondition failed for {}.",transaction.getIdentifier(),e.getPath(),e);
331 public ListenableFuture<Void> preCommit() {
332 return executor.submit(new Callable<Void>() {
335 candidate = dataTree.prepare(modification);
336 listenerResolver = ResolveDataChangeEventsTask.create(candidate, listenerTree);
343 public ListenableFuture<Void> abort() {
345 return Futures.immediateFuture(null);
349 public ListenableFuture<Void> commit() {
350 checkState(candidate != null, "Proposed subtree must be computed");
353 * The commit has to occur atomically with regard to listener
356 synchronized (this) {
357 dataTree.commit(candidate);
359 for (ChangeListenerNotifyTask task : listenerResolver.call()) {
360 LOG.trace("Scheduling invocation of listeners: {}", task);
361 executor.submit(task);
365 return Futures.immediateFuture(null);