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