Bump to odlparent-6.0.1/yangtools-4.0.2/mdsal-5.0.4
[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 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.Optional;
16 import com.google.common.base.Throwables;
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
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  * @deprecated Use {@link org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction} instead.
33  */
34 @Deprecated(forRemoval = true)
35 @Beta
36 public class SnapshotBackedWriteTransaction<T> extends AbstractDOMStoreTransaction<T>
37         implements DOMStoreWriteTransaction {
38     private static final Logger LOG = LoggerFactory.getLogger(SnapshotBackedWriteTransaction.class);
39     @SuppressWarnings("rawtypes")
40     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, TransactionReadyPrototype>
41         READY_UPDATER = AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class,
42                 TransactionReadyPrototype.class, "readyImpl");
43     @SuppressWarnings("rawtypes")
44     private static final AtomicReferenceFieldUpdater<SnapshotBackedWriteTransaction, DataTreeModification>
45         TREE_UPDATER = AtomicReferenceFieldUpdater.newUpdater(SnapshotBackedWriteTransaction.class,
46                 DataTreeModification.class, "mutableTree");
47
48     // non-null when not ready
49     private volatile TransactionReadyPrototype<T> readyImpl;
50     // non-null when not committed/closed
51     private volatile DataTreeModification mutableTree;
52
53     SnapshotBackedWriteTransaction(final T identifier, final boolean debug,
54             final DataTreeSnapshot snapshot, final TransactionReadyPrototype<T> readyImpl) {
55         super(identifier, debug);
56         this.readyImpl = requireNonNull(readyImpl, "readyImpl must not be null.");
57         mutableTree = snapshot.newModification();
58         LOG.debug("Write Tx: {} allocated with snapshot {}", identifier, snapshot);
59     }
60
61     @Override
62     @SuppressWarnings("checkstyle:IllegalCatch")
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 (RuntimeException 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     @SuppressWarnings("checkstyle:IllegalCatch")
84     public void merge(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
85         checkNotReady();
86
87         final DataTreeModification tree = mutableTree;
88         LOG.debug("Tx: {} Merge: {}:{}", getIdentifier(), path, data);
89
90         try {
91             tree.merge(path, data);
92             // FIXME: Add checked exception
93         } catch (RuntimeException e) {
94             LOG.error("Tx: {}, failed to write {}:{} in {}", getIdentifier(), path, data, tree, e);
95             // Rethrow original ones if they are subclasses of RuntimeException
96             // or Error
97             Throwables.propagateIfPossible(e);
98             // FIXME: Introduce proper checked exception
99             throw new IllegalArgumentException("Illegal input data.", e);
100         }
101     }
102
103     @Override
104     @SuppressWarnings("checkstyle:IllegalCatch")
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 (RuntimeException e) {
115             LOG.error("Tx: {}, failed to delete {} in {}", getIdentifier(), path, tree, e);
116             // Rethrow original ones if they are subclasses of RuntimeException
117             // or Error
118             Throwables.propagateIfPossible(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 : Optional.fromJavaUtil(mutableTree.readNode(path));
133     }
134
135     private void checkNotReady() {
136         checkState(readyImpl != null, "Transaction %s is no longer open. No further modifications allowed.",
137                 getIdentifier());
138     }
139
140     @Override
141     @SuppressWarnings("checkstyle:IllegalCatch")
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      * This class is intended to be implemented by Transaction factories responsible for allocation of
180      * {@link org.opendaylight.controller.sal.core.spi.data.SnapshotBackedWriteTransaction} and
181      * providing underlying logic for applying implementation.
182      *
183      * @param <T> identifier type
184      */
185     @Deprecated
186     public abstract static class TransactionReadyPrototype<T> {
187         /**
188          * Called when a transaction is closed without being readied. This is not invoked for
189          * transactions which are ready.
190          *
191          * @param tx Transaction which got aborted.
192          */
193         protected abstract void transactionAborted(SnapshotBackedWriteTransaction<T> tx);
194
195         /**
196          * Returns a commit coordinator associated with supplied transactions.
197          *
198          * <p>
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 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.