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;
12 import static org.opendaylight.controller.md.sal.dom.store.impl.StoreUtils.increase;
14 import java.util.Collections;
15 import java.util.concurrent.Callable;
16 import java.util.concurrent.atomic.AtomicLong;
17 import java.util.concurrent.atomic.AtomicReference;
19 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
20 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
21 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ListenerTree;
22 import org.opendaylight.controller.md.sal.dom.store.impl.tree.ModificationType;
23 import org.opendaylight.controller.md.sal.dom.store.impl.tree.NodeModification;
24 import org.opendaylight.controller.md.sal.dom.store.impl.tree.StoreMetadataNode;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
26 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
27 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
28 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
29 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
30 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
31 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
32 import org.opendaylight.yangtools.concepts.Identifiable;
33 import org.opendaylight.yangtools.concepts.ListenerRegistration;
34 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeUtils;
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.primitives.UnsignedLong;
48 import com.google.common.util.concurrent.Futures;
49 import com.google.common.util.concurrent.ListenableFuture;
50 import com.google.common.util.concurrent.ListeningExecutorService;
52 public class InMemoryDOMDataStore implements DOMStore, Identifiable<String>, SchemaContextListener {
54 private static final Logger LOG = LoggerFactory.getLogger(InMemoryDOMDataStore.class);
55 private static final InstanceIdentifier PUBLIC_ROOT_PATH = InstanceIdentifier.builder().build();
58 private final ListeningExecutorService executor;
59 private final String name;
60 private final AtomicLong txCounter = new AtomicLong(0);
61 private final ListenerTree listenerTree;
62 private final AtomicReference<DataAndMetadataSnapshot> snapshot;
64 private ModificationApplyOperation operationTree;
66 private SchemaContext schemaContext;
68 public InMemoryDOMDataStore(final String name, final ListeningExecutorService executor) {
69 this.name = Preconditions.checkNotNull(name);
70 this.executor = Preconditions.checkNotNull(executor);
71 this.listenerTree = ListenerTree.create();
72 this.snapshot = new AtomicReference<DataAndMetadataSnapshot>(DataAndMetadataSnapshot.createEmpty());
73 this.operationTree = new AlwaysFailOperation();
77 public final String getIdentifier() {
82 public DOMStoreReadTransaction newReadOnlyTransaction() {
83 return new SnapshotBackedReadTransaction(nextIdentifier(), snapshot.get());
87 public DOMStoreReadWriteTransaction newReadWriteTransaction() {
88 return new SnapshotBackedReadWriteTransaction(nextIdentifier(), snapshot.get(), this, operationTree);
92 public DOMStoreWriteTransaction newWriteOnlyTransaction() {
93 return new SnaphostBackedWriteTransaction(nextIdentifier(), snapshot.get(), this, operationTree);
97 public synchronized void onGlobalContextUpdated(final SchemaContext ctx) {
98 operationTree = SchemaAwareApplyOperationRoot.from(ctx);
103 public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
104 final InstanceIdentifier path, final L listener, final DataChangeScope scope) {
107 * Make sure commit is not occurring right now. Listener has to be registered and its
108 * state capture enqueued at a consistent point.
110 * FIXME: improve this to read-write lock, such that multiple listener registrations
111 * can occur simultaneously
113 final DataChangeListenerRegistration<L> reg;
114 synchronized (this) {
115 LOG.debug("{}: Registering data change listener {} for {}",name,listener,path);
117 reg = listenerTree.registerDataChangeListener(path, listener, scope);
119 Optional<StoreMetadataNode> currentState = snapshot.get().read(path);
120 if (currentState.isPresent()) {
121 final NormalizedNode<?, ?> data = currentState.get().getData();
123 final DOMImmutableDataChangeEvent event = DOMImmutableDataChangeEvent.builder(DataChangeScope.BASE) //
125 .addCreated(path, data) //
127 executor.submit(new ChangeListenerNotifyTask(Collections.singletonList(reg), event));
131 return new AbstractListenerRegistration<L>(listener) {
133 protected void removeRegistration() {
134 synchronized (InMemoryDOMDataStore.this) {
141 private synchronized DOMStoreThreePhaseCommitCohort submit(
142 final SnaphostBackedWriteTransaction writeTx) {
143 LOG.debug("Tx: {} is submitted. Modifications: {}",writeTx.getIdentifier(),writeTx.getMutatedView());
144 return new ThreePhaseCommitImpl(writeTx);
147 private Object nextIdentifier() {
148 return name + "-" + txCounter.getAndIncrement();
151 private void commit(final DataAndMetadataSnapshot currentSnapshot,
152 final StoreMetadataNode newDataTree, final ResolveDataChangeEventsTask listenerResolver) {
153 LOG.debug("Updating Store snaphot version: {} with version:{}",currentSnapshot.getMetadataTree().getSubtreeVersion(),newDataTree.getSubtreeVersion());
155 if(LOG.isTraceEnabled()) {
156 LOG.trace("Data Tree is {}",StoreUtils.toStringTree(newDataTree));
159 final DataAndMetadataSnapshot newSnapshot = DataAndMetadataSnapshot.builder() //
160 .setMetadataTree(newDataTree) //
161 .setSchemaContext(schemaContext) //
165 * The commit has to occur atomically with regard to listener registrations.
167 synchronized (this) {
168 final boolean success = snapshot.compareAndSet(currentSnapshot, newSnapshot);
169 checkState(success, "Store snapshot and transaction snapshot differ. This should never happen.");
171 for (ChangeListenerNotifyTask task : listenerResolver.call()) {
172 executor.submit(task);
177 private static abstract class AbstractDOMStoreTransaction implements DOMStoreTransaction {
178 private final Object identifier;
180 protected AbstractDOMStoreTransaction(final Object identifier) {
181 this.identifier = identifier;
185 public final Object getIdentifier() {
190 public final String toString() {
191 return addToStringAttributes(Objects.toStringHelper(this)).toString();
195 * Add class-specific toString attributes.
197 * @param toStringHelper ToStringHelper instance
198 * @return ToStringHelper instance which was passed in
200 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
201 return toStringHelper.add("id", identifier);
205 private static class SnapshotBackedReadTransaction extends AbstractDOMStoreTransaction implements DOMStoreReadTransaction {
206 private DataAndMetadataSnapshot stableSnapshot;
208 public SnapshotBackedReadTransaction(final Object identifier, final DataAndMetadataSnapshot snapshot) {
210 this.stableSnapshot = Preconditions.checkNotNull(snapshot);
211 LOG.debug("ReadOnly Tx: {} allocated with snapshot {}", identifier, snapshot.getMetadataTree().getSubtreeVersion());
215 public void close() {
216 LOG.debug("Store transaction: {} : Closed", getIdentifier());
217 stableSnapshot = null;
221 public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
222 checkNotNull(path, "Path must not be null.");
223 checkState(stableSnapshot != null, "Transaction is closed");
224 return Futures.immediateFuture(NormalizedNodeUtils.findNode(stableSnapshot.getDataTree(), path));
228 private static class SnaphostBackedWriteTransaction extends AbstractDOMStoreTransaction implements DOMStoreWriteTransaction {
229 private MutableDataTree mutableTree;
230 private InMemoryDOMDataStore store;
231 private boolean ready = false;
233 public SnaphostBackedWriteTransaction(final Object identifier, final DataAndMetadataSnapshot snapshot,
234 final InMemoryDOMDataStore store, final ModificationApplyOperation applyOper) {
236 mutableTree = MutableDataTree.from(snapshot, applyOper);
238 LOG.debug("Write Tx: {} allocated with snapshot {}",identifier,snapshot.getMetadataTree().getSubtreeVersion());
242 public void close() {
243 LOG.debug("Store transaction: {} : Closed", getIdentifier());
244 this.mutableTree = null;
249 public void write(final InstanceIdentifier path, final NormalizedNode<?, ?> data) {
251 mutableTree.write(path, data);
255 public void delete(final InstanceIdentifier path) {
257 mutableTree.delete(path);
260 protected final boolean isReady() {
264 protected final void checkNotReady() {
265 checkState(!ready, "Transaction %s is ready. No further modifications allowed.", getIdentifier());
269 public synchronized DOMStoreThreePhaseCommitCohort ready() {
270 checkState(!ready, "Transaction %s is already ready.", getIdentifier());
273 LOG.debug("Store transaction: {} : Ready", getIdentifier());
275 return store.submit(this);
278 protected MutableDataTree getMutatedView() {
283 protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
284 return toStringHelper.add("ready", isReady());
288 private static class SnapshotBackedReadWriteTransaction extends SnaphostBackedWriteTransaction implements
289 DOMStoreReadWriteTransaction {
291 protected SnapshotBackedReadWriteTransaction(final Object identifier, final DataAndMetadataSnapshot snapshot,
292 final InMemoryDOMDataStore store, final ModificationApplyOperation applyOper) {
293 super(identifier, snapshot, store, applyOper);
297 public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
298 return Futures.immediateFuture(getMutatedView().read(path));
302 private class ThreePhaseCommitImpl implements DOMStoreThreePhaseCommitCohort {
304 private final SnaphostBackedWriteTransaction transaction;
305 private final NodeModification modification;
307 private DataAndMetadataSnapshot storeSnapshot;
308 private Optional<StoreMetadataNode> proposedSubtree;
309 private ResolveDataChangeEventsTask listenerResolver;
311 public ThreePhaseCommitImpl(final SnaphostBackedWriteTransaction writeTransaction) {
312 this.transaction = writeTransaction;
313 this.modification = transaction.getMutatedView().getRootModification();
317 public ListenableFuture<Boolean> canCommit() {
318 final DataAndMetadataSnapshot snapshotCapture = snapshot.get();
319 final ModificationApplyOperation snapshotOperation = operationTree;
321 return executor.submit(new Callable<Boolean>() {
324 public Boolean call() throws Exception {
325 boolean applicable = snapshotOperation.isApplicable(modification,
326 Optional.of(snapshotCapture.getMetadataTree()));
327 LOG.debug("Store Transcation: {} : canCommit : {}", transaction.getIdentifier(), applicable);
334 public ListenableFuture<Void> preCommit() {
335 storeSnapshot = snapshot.get();
336 if(modification.getModificationType() == ModificationType.UNMODIFIED) {
337 return Futures.immediateFuture(null);
339 return executor.submit(new Callable<Void>() {
344 public Void call() throws Exception {
345 StoreMetadataNode metadataTree = storeSnapshot.getMetadataTree();
347 proposedSubtree = operationTree.apply(modification, Optional.of(metadataTree),
348 increase(metadataTree.getSubtreeVersion()));
350 listenerResolver = ResolveDataChangeEventsTask.create() //
351 .setRootPath(PUBLIC_ROOT_PATH) //
352 .setBeforeRoot(Optional.of(metadataTree)) //
353 .setAfterRoot(proposedSubtree) //
354 .setModificationRoot(modification) //
355 .setListenerRoot(listenerTree);
363 public ListenableFuture<Void> abort() {
364 storeSnapshot = null;
365 proposedSubtree = null;
366 return Futures.<Void> immediateFuture(null);
370 public ListenableFuture<Void> commit() {
371 if(modification.getModificationType() == ModificationType.UNMODIFIED) {
372 return Futures.immediateFuture(null);
375 checkState(proposedSubtree != null,"Proposed subtree must be computed");
376 checkState(storeSnapshot != null,"Proposed subtree must be computed");
377 // return ImmediateFuture<>;
378 InMemoryDOMDataStore.this.commit(storeSnapshot, proposedSubtree.get(),listenerResolver);
379 return Futures.<Void> immediateFuture(null);
384 private static final class AlwaysFailOperation implements ModificationApplyOperation {
387 public Optional<StoreMetadataNode> apply(final NodeModification modification,
388 final Optional<StoreMetadataNode> storeMeta, final UnsignedLong subtreeVersion) {
389 throw new IllegalStateException("Schema Context is not available.");
393 public boolean isApplicable(final NodeModification modification, final Optional<StoreMetadataNode> storeMetadata) {
394 throw new IllegalStateException("Schema Context is not available.");
398 public Optional<ModificationApplyOperation> getChild(final PathArgument child) {
399 throw new IllegalStateException("Schema Context is not available.");
403 public void verifyStructure(final NodeModification modification) throws IllegalArgumentException {
404 throw new IllegalStateException("Schema Context is not available.");