10e3a7df10de5f41ee888b392e753479f5f186a9
[controller.git] / opendaylight / md-sal / sal-inmemory-datastore / src / main / java / org / opendaylight / controller / md / sal / dom / store / impl / SnapshotBackedWriteTransaction.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 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Throwables;
15 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
16 import org.opendaylight.controller.sal.core.spi.data.AbstractDOMStoreTransaction;
17 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
18 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
21 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
22 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeSnapshot;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 /**
27  * Implementation of Write transaction which is backed by
28  * {@link DataTreeSnapshot} and executed according to
29  * {@link org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction.TransactionReadyPrototype}.
30  *
31  */
32 class SnapshotBackedWriteTransaction extends AbstractDOMStoreTransaction<Object> implements DOMStoreWriteTransaction {
33     private static final Logger LOG = LoggerFactory.getLogger(SnapshotBackedWriteTransaction.class);
34     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, TransactionReadyPrototype> READY_UPDATER =
35             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, TransactionReadyPrototype.class, "readyImpl");
36     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, DataTreeModification> TREE_UPDATER =
37             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, DataTreeModification.class, "mutableTree");
38
39     // non-null when not ready
40     private volatile TransactionReadyPrototype readyImpl;
41     // non-null when not committed/closed
42     private volatile DataTreeModification mutableTree;
43
44     /**
45      * Creates new write-only transaction.
46      *
47      * @param identifier
48      *            transaction Identifier
49      * @param snapshot
50      *            Snapshot which will be modified.
51      * @param readyImpl
52      *            Implementation of ready method.
53      */
54     public SnapshotBackedWriteTransaction(final Object identifier, final boolean debug,
55             final DataTreeSnapshot snapshot, final TransactionReadyPrototype readyImpl) {
56         super(identifier, debug);
57         this.readyImpl = Preconditions.checkNotNull(readyImpl, "readyImpl must not be null.");
58         mutableTree = snapshot.newModification();
59         LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
60     }
61
62     @Override
63     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
64         checkNotReady();
65
66         final DataTreeModification tree = mutableTree;
67         LOG.debug("Tx: {} Write: {}:{}", getIdentifier(), path, data);
68
69         try {
70             tree.write(path, data);
71             // FIXME: Add checked exception
72         } catch (Exception e) {
73             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
74             // Rethrow original ones if they are subclasses of RuntimeException
75             // or Error
76             Throwables.propagateIfPossible(e);
77             // FIXME: Introduce proper checked exception
78             throw new IllegalArgumentException("Illegal input data.", e);
79         }
80     }
81
82     @Override
83     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
84         checkNotReady();
85
86         final DataTreeModification tree = mutableTree;
87         LOG.debug("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
88
89         try {
90             tree.merge(path, data);
91             // FIXME: Add checked exception
92         } catch (Exception e) {
93             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
94             // Rethrow original ones if they are subclasses of RuntimeException
95             // or Error
96             Throwables.propagateIfPossible(e);
97             // FIXME: Introduce proper checked exception
98             throw new IllegalArgumentException("Illegal input data.", e);
99         }
100     }
101
102     @Override
103     public void delete(final YangInstanceIdentifier path) {
104         checkNotReady();
105
106         final DataTreeModification tree = mutableTree;
107         LOG.debug("Tx: {} Delete: {}", getIdentifier(), path);
108
109         try {
110             tree.delete(path);
111             // FIXME: Add checked exception
112         } catch (Exception e) {
113             LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, tree, e);
114             // Rethrow original ones if they are subclasses of RuntimeException
115             // or Error
116             Throwables.propagateIfPossible(e);
117             // FIXME: Introduce proper checked exception
118             throw new IllegalArgumentException("Illegal path to delete.", e);
119         }
120     }
121
122     /**
123      * Exposed for {@link SnapshotBackedReadWriteTransaction}'s sake only. The contract does
124      * not allow data access after the transaction has been closed or readied.
125      *
126      * @param path Path to read
127      * @return null if the the transaction has been closed;
128      */
129     protected final Optional<NormalizedNode<?, ?>> readSnapshotNode(final YangInstanceIdentifier path) {
130         return readyImpl == null ? null : mutableTree.readNode(path);
131     }
132
133     private final void checkNotReady() {
134         checkState(readyImpl != null, "Transaction %s is no longer open. No further modifications allowed.", getIdentifier());
135     }
136
137     @Override
138     public DOMStoreThreePhaseCommitCohort ready() {
139         final TransactionReadyPrototype wasReady = READY_UPDATER.getAndSet(this, null);
140         checkState(wasReady != null, "Transaction %s is no longer open", getIdentifier());
141
142         LOG.debug("Store transaction: {} : Ready", getIdentifier());
143
144         final DataTreeModification tree = mutableTree;
145         TREE_UPDATER.lazySet(this, null);
146         tree.ready();
147         return wasReady.transactionReady(this, tree);
148     }
149
150     @Override
151     public void close() {
152         final TransactionReadyPrototype wasReady = READY_UPDATER.getAndSet(this, null);
153         if (wasReady != null) {
154             LOG.debug("Store transaction: {} : Closed", getIdentifier());
155             TREE_UPDATER.lazySet(this, null);
156             wasReady.transactionAborted(this);
157         } else {
158             LOG.debug("Store transaction: {} : Closed after submit", getIdentifier());
159         }
160     }
161
162     @Override
163     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
164         return toStringHelper.add("ready", readyImpl == null);
165     }
166
167     /**
168      * Prototype implementation of
169      * {@link #ready(org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction)}
170      *
171      * This class is intended to be implemented by Transaction factories
172      * responsible for allocation of {@link org.opendaylight.controller.md.sal.dom.store.impl.SnapshotBackedWriteTransaction} and
173      * providing underlying logic for applying implementation.
174      *
175      */
176     abstract static class TransactionReadyPrototype {
177         /**
178          * Called when a transaction is closed without being readied. This is not invoked for
179          * transactions which are ready.
180          *
181          * @param tx Transaction which got aborted.
182          */
183         protected abstract void transactionAborted(final SnapshotBackedWriteTransaction tx);
184
185         /**
186          * Returns a commit coordinator associated with supplied transactions.
187          *
188          * This call must not fail.
189          *
190          * @param tx
191          *            Transaction on which ready was invoked.
192          * @param tree
193          *            Modified data tree which has been constructed.
194          * @return DOMStoreThreePhaseCommitCohort associated with transaction
195          */
196         protected abstract DOMStoreThreePhaseCommitCohort transactionReady(SnapshotBackedWriteTransaction tx, DataTreeModification tree);
197     }
198 }