eaabb3a21fbb802e82e90fcd70a2ef1e41c46e39
[controller.git] / opendaylight / md-sal / sal-dom-spi / src / main / java / org / opendaylight / controller / sal / core / spi / data / 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.sal.core.spi.data;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import com.google.common.annotations.Beta;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.Optional;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Throwables;
17 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
18 import javax.annotation.Nullable;
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.sal.core.spi.data.SnapshotBackedWriteTransaction.TransactionReadyPrototype}.
30  *
31  * @param <T> Identifier type
32  */
33 @Beta
34 public class SnapshotBackedWriteTransaction<T> extends AbstractDOMStoreTransaction<T> implements DOMStoreWriteTransaction {
35     private static final Logger LOG = LoggerFactory.getLogger(SnapshotBackedWriteTransaction.class);
36     @SuppressWarnings("rawtypes")
37     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, TransactionReadyPrototype> READY_UPDATER =
38             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, TransactionReadyPrototype.class, "readyImpl");
39     @SuppressWarnings("rawtypes")
40     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, DataTreeModification> TREE_UPDATER =
41             AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class, DataTreeModification.class, "mutableTree");
42
43     // non-null when not ready
44     private volatile TransactionReadyPrototype<T> readyImpl;
45     // non-null when not committed/closed
46     private volatile DataTreeModification mutableTree;
47
48     SnapshotBackedWriteTransaction(final T identifier, final boolean debug,
49             final DataTreeSnapshot snapshot, final TransactionReadyPrototype<T> readyImpl) {
50         super(identifier, debug);
51         this.readyImpl = Preconditions.checkNotNull(readyImpl, "readyImpl must not be null.");
52         mutableTree = snapshot.newModification();
53         LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
54     }
55
56     @Override
57     public void write(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
58         checkNotReady();
59
60         final DataTreeModification tree = mutableTree;
61         LOG.debug("Tx: {} Write: {}:{}", getIdentifier(), path, data);
62
63         try {
64             tree.write(path, data);
65             // FIXME: Add checked exception
66         } catch (Exception e) {
67             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
68             // Rethrow original ones if they are subclasses of RuntimeException
69             // or Error
70             Throwables.propagateIfPossible(e);
71             // FIXME: Introduce proper checked exception
72             throw new IllegalArgumentException("Illegal input data.", e);
73         }
74     }
75
76     @Override
77     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
78         checkNotReady();
79
80         final DataTreeModification tree = mutableTree;
81         LOG.debug("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
82
83         try {
84             tree.merge(path, data);
85             // FIXME: Add checked exception
86         } catch (Exception e) {
87             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
88             // Rethrow original ones if they are subclasses of RuntimeException
89             // or Error
90             Throwables.propagateIfPossible(e);
91             // FIXME: Introduce proper checked exception
92             throw new IllegalArgumentException("Illegal input data.", e);
93         }
94     }
95
96     @Override
97     public void delete(final YangInstanceIdentifier path) {
98         checkNotReady();
99
100         final DataTreeModification tree = mutableTree;
101         LOG.debug("Tx: {} Delete: {}", getIdentifier(), path);
102
103         try {
104             tree.delete(path);
105             // FIXME: Add checked exception
106         } catch (Exception e) {
107             LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, tree, e);
108             // Rethrow original ones if they are subclasses of RuntimeException
109             // or Error
110             Throwables.propagateIfPossible(e);
111             // FIXME: Introduce proper checked exception
112             throw new IllegalArgumentException("Illegal path to delete.", e);
113         }
114     }
115
116     /**
117      * Exposed for {@link SnapshotBackedReadWriteTransaction}'s sake only. The contract does
118      * not allow data access after the transaction has been closed or readied.
119      *
120      * @param path Path to read
121      * @return null if the the transaction has been closed;
122      */
123     final Optional<NormalizedNode<?, ?>> readSnapshotNode(final YangInstanceIdentifier path) {
124         return readyImpl == null ? null : Optional.fromJavaUtil(mutableTree.readNode(path));
125     }
126
127     private final void checkNotReady() {
128         checkState(readyImpl != null, "Transaction %s is no longer open. No further modifications allowed.",
129                 getIdentifier());
130     }
131
132     @Override
133     public DOMStoreThreePhaseCommitCohort ready() {
134         @SuppressWarnings("unchecked")
135         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
136         checkState(wasReady != null, "Transaction %s is no longer open", getIdentifier());
137
138         LOG.debug("Store transaction: {} : Ready", getIdentifier());
139
140         final DataTreeModification tree = mutableTree;
141         TREE_UPDATER.lazySet(this, null);
142         try {
143             tree.ready();
144             return wasReady.transactionReady(this, tree, null);
145         } catch (RuntimeException e) {
146             LOG.debug("Store transaction: {}: unexpected failure when readying", getIdentifier(), e);
147             return wasReady.transactionReady(this, tree, e);
148         }
149     }
150
151     @Override
152     public void close() {
153         @SuppressWarnings("unchecked")
154         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
155         if (wasReady != null) {
156             LOG.debug("Store transaction: {} : Closed", getIdentifier());
157             TREE_UPDATER.lazySet(this, null);
158             wasReady.transactionAborted(this);
159         } else {
160             LOG.debug("Store transaction: {} : Closed after submit", getIdentifier());
161         }
162     }
163
164     @Override
165     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
166         return toStringHelper.add("ready", readyImpl == null);
167     }
168
169     /**
170      * This class is intended to be implemented by Transaction factories
171      * responsible for allocation of {@link org.opendaylight.controller.sal.core.spi.data.SnapshotBackedWriteTransaction} and
172      * providing underlying logic for applying implementation.
173      *
174      * @param <T> identifier type
175      */
176     public abstract static class TransactionReadyPrototype<T> {
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<T> 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          * @param readyError
195          *            Any error that has already happened when readying.
196          * @return DOMStoreThreePhaseCommitCohort associated with transaction
197          */
198         protected abstract DOMStoreThreePhaseCommitCohort transactionReady(SnapshotBackedWriteTransaction<T> tx,
199                                                                            DataTreeModification tree,
200                                                                            @Nullable Exception readyError);
201     }
202 }