5c312cc92d0d174792fac5ad92975045b0bed90e
[controller.git] / opendaylight / md-sal / sal-dom-broker / src / main / java / org / opendaylight / controller / md / sal / dom / broker / impl / DOMForwardedWriteTransaction.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.md.sal.dom.broker.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Supplier;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import com.google.common.util.concurrent.FluentFuture;
14 import com.google.common.util.concurrent.Futures;
15 import com.google.common.util.concurrent.ListenableFuture;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Map;
19 import java.util.concurrent.Future;
20 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
23 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
24 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
25 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
26 import org.opendaylight.mdsal.common.api.CommitInfo;
27 import org.opendaylight.mdsal.common.api.MappingCheckedFuture;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /**
34  * Read-Write Transaction, which is composed of several
35  * {@link DOMStoreWriteTransaction} transactions. A sub-transaction is selected by
36  * {@link LogicalDatastoreType} type parameter in:
37  *
38  * <p>
39  * <ul>
40  * <li>{@link #put(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
41  * <li>{@link #delete(LogicalDatastoreType, YangInstanceIdentifier)}
42  * <li>{@link #merge(LogicalDatastoreType, YangInstanceIdentifier, NormalizedNode)}
43  * </ul>
44  *
45  * <p>
46  * {@link #commit()} will result in invocation of
47  * {@link DOMDataCommitImplementation#submit(org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction,
48  * Iterable)} invocation with all {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort}
49  * for underlying transactions.
50  *
51  * @param <T> Subtype of {@link DOMStoreWriteTransaction} which is used as
52  *            subtransaction.
53  */
54 class DOMForwardedWriteTransaction<T extends DOMStoreWriteTransaction> extends
55         AbstractDOMForwardedCompositeTransaction<LogicalDatastoreType, T> implements DOMDataWriteTransaction {
56     @SuppressWarnings("rawtypes")
57     private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction,
58             AbstractDOMForwardedTransactionFactory>
59             IMPL_UPDATER = AtomicReferenceFieldUpdater
60             .newUpdater(DOMForwardedWriteTransaction.class, AbstractDOMForwardedTransactionFactory.class, "commitImpl");
61     @SuppressWarnings("rawtypes")
62     private static final AtomicReferenceFieldUpdater<DOMForwardedWriteTransaction, Future> FUTURE_UPDATER
63             = AtomicReferenceFieldUpdater.newUpdater(DOMForwardedWriteTransaction.class, Future.class, "commitFuture");
64     private static final Logger LOG = LoggerFactory.getLogger(DOMForwardedWriteTransaction.class);
65     private static final Future<?> CANCELLED_FUTURE = Futures.immediateCancelledFuture();
66
67     /**
68      * Implementation of real commit. It also acts as an indication that
69      * the transaction is running -- which we flip atomically using
70      * {@link #IMPL_UPDATER}.
71      */
72     private volatile AbstractDOMForwardedTransactionFactory<?> commitImpl;
73
74     /**
75      * Future task of transaction commit. It starts off as null, but is
76      * set appropriately on {@link #commit()} and {@link #cancel()} via
77      * {@link AtomicReferenceFieldUpdater#lazySet(Object, Object)}.
78      *
79      * <p>
80      * Lazy set is safe for use because it is only referenced to in the
81      * {@link #cancel()} slow path, where we will busy-wait for it. The
82      * fast path gets the benefit of a store-store barrier instead of the
83      * usual store-load barrier.
84      */
85     private volatile Future<?> commitFuture;
86
87     protected DOMForwardedWriteTransaction(final Object identifier, final Map<LogicalDatastoreType, T> backingTxs,
88                                            final AbstractDOMForwardedTransactionFactory<?> commitImpl) {
89         super(identifier, backingTxs);
90         this.commitImpl = Preconditions.checkNotNull(commitImpl, "commitImpl must not be null.");
91     }
92
93     @Override
94     public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
95                     final NormalizedNode<?, ?> data) {
96         checkRunning(commitImpl);
97         getSubtransaction(store).write(path, data);
98     }
99
100     @Override
101     public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
102         checkRunning(commitImpl);
103         getSubtransaction(store).delete(path);
104     }
105
106     @Override
107     public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
108                       final NormalizedNode<?, ?> data) {
109         checkRunning(commitImpl);
110         getSubtransaction(store).merge(path, data);
111     }
112
113     @Override
114     public boolean cancel() {
115         final AbstractDOMForwardedTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
116         if (impl != null) {
117             LOG.trace("Transaction {} cancelled before submit", getIdentifier());
118             FUTURE_UPDATER.lazySet(this, CANCELLED_FUTURE);
119             closeSubtransactions();
120             return true;
121         }
122
123         // The transaction is in process of being submitted or cancelled. Busy-wait
124         // for the corresponding future.
125         Future<?> future;
126         do {
127             future = commitFuture;
128         } while (future == null);
129
130         return future.cancel(false);
131     }
132
133     @Override
134     public CheckedFuture<Void, TransactionCommitFailedException> submit() {
135         return MappingCheckedFuture.create(doCommit(() -> null),
136                 TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER);
137     }
138
139     @Override
140     public FluentFuture<? extends CommitInfo> commit() {
141         return FluentFuture.from(doCommit(CommitInfo::empty));
142     }
143
144     @SuppressWarnings("checkstyle:IllegalCatch")
145     private <V> ListenableFuture<V> doCommit(Supplier<V> futureValueSupplier) {
146         final AbstractDOMForwardedTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
147         checkRunning(impl);
148
149         final Collection<T> txns = getSubtransactions();
150         final Collection<DOMStoreThreePhaseCommitCohort> cohorts = new ArrayList<>(txns.size());
151
152         ListenableFuture<V> ret;
153         try {
154             for (DOMStoreWriteTransaction txn : txns) {
155                 cohorts.add(txn.ready());
156             }
157
158             ret = impl.commit(this, cohorts, futureValueSupplier);
159         } catch (RuntimeException e) {
160             ret = FluentFuture.from(Futures.immediateFailedFuture(
161                     TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e)));
162         }
163         FUTURE_UPDATER.lazySet(this, ret);
164         return ret;
165     }
166
167     private void checkRunning(final AbstractDOMForwardedTransactionFactory<?> impl) {
168         Preconditions.checkState(impl != null, "Transaction %s is no longer running", getIdentifier());
169     }
170 }