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