Adjust to yangtools-2.0.0 changes
[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
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.controller.sal.core.spi.data.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 (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 (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 (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 : Optional.fromJavaUtil(mutableTree.readNode(path));
124     }
125
126     private final void checkNotReady() {
127         checkState(readyImpl != null, "Transaction %s is no longer open. No further modifications allowed.",
128                 getIdentifier());
129     }
130
131     @Override
132     public DOMStoreThreePhaseCommitCohort ready() {
133         @SuppressWarnings("unchecked")
134         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
135         checkState(wasReady != null, "Transaction %s is no longer open", getIdentifier());
136
137         LOG.debug("Store transaction: {} : Ready", getIdentifier());
138
139         final DataTreeModification tree = mutableTree;
140         TREE_UPDATER.lazySet(this, null);
141         tree.ready();
142         return wasReady.transactionReady(this, tree);
143     }
144
145     @Override
146     public void close() {
147         @SuppressWarnings("unchecked")
148         final TransactionReadyPrototype<T> wasReady = READY_UPDATER.getAndSet(this, null);
149         if (wasReady != null) {
150             LOG.debug("Store transaction: {} : Closed", getIdentifier());
151             TREE_UPDATER.lazySet(this, null);
152             wasReady.transactionAborted(this);
153         } else {
154             LOG.debug("Store transaction: {} : Closed after submit", getIdentifier());
155         }
156     }
157
158     @Override
159     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
160         return toStringHelper.add("ready", readyImpl == null);
161     }
162
163     /**
164      * This class is intended to be implemented by Transaction factories
165      * responsible for allocation of {@link org.opendaylight.controller.sal.core.spi.data.SnapshotBackedWriteTransaction} and
166      * providing underlying logic for applying implementation.
167      *
168      * @param <T> identifier type
169      */
170     public abstract static class TransactionReadyPrototype<T> {
171         /**
172          * Called when a transaction is closed without being readied. This is not invoked for
173          * transactions which are ready.
174          *
175          * @param tx Transaction which got aborted.
176          */
177         protected abstract void transactionAborted(final SnapshotBackedWriteTransaction<T> tx);
178
179         /**
180          * Returns a commit coordinator associated with supplied transactions.
181          *
182          * This call must not fail.
183          *
184          * @param tx
185          *            Transaction on which ready was invoked.
186          * @param tree
187          *            Modified data tree which has been constructed.
188          * @return DOMStoreThreePhaseCommitCohort associated with transaction
189          */
190         protected abstract DOMStoreThreePhaseCommitCohort transactionReady(SnapshotBackedWriteTransaction<T> tx, DataTreeModification tree);
191     }
192 }

©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.