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