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