Do not allow multi-datastore transactions
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / databroker / AbstractDOMBrokerWriteTransaction.java
1 /*
2  * Copyright (c) 2015 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.cluster.databroker;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
14
15 import com.google.common.base.MoreObjects.ToStringHelper;
16 import com.google.common.util.concurrent.FluentFuture;
17 import com.google.common.util.concurrent.Futures;
18 import java.util.Map;
19 import java.util.concurrent.Future;
20 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
21 import org.opendaylight.mdsal.common.api.CommitInfo;
22 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
23 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
24 import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
25 import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
26 import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 public abstract class AbstractDOMBrokerWriteTransaction<T extends DOMStoreWriteTransaction>
34         extends AbstractDOMBrokerTransaction<T> implements DOMDataTreeWriteTransaction {
35
36     @SuppressWarnings("rawtypes")
37     private static final AtomicReferenceFieldUpdater<AbstractDOMBrokerWriteTransaction, AbstractDOMTransactionFactory>
38             IMPL_UPDATER = AtomicReferenceFieldUpdater.newUpdater(AbstractDOMBrokerWriteTransaction.class,
39                     AbstractDOMTransactionFactory.class, "commitImpl");
40     @SuppressWarnings("rawtypes")
41     private static final AtomicReferenceFieldUpdater<AbstractDOMBrokerWriteTransaction, Future> FUTURE_UPDATER =
42             AtomicReferenceFieldUpdater.newUpdater(AbstractDOMBrokerWriteTransaction.class, Future.class,
43                     "commitFuture");
44     private static final Logger LOG = LoggerFactory.getLogger(AbstractDOMBrokerWriteTransaction.class);
45     private static final Future<?> CANCELLED_FUTURE = Futures.immediateCancelledFuture();
46
47     /**
48      * Implementation of real commit. It also acts as an indication that
49      * the transaction is running -- which we flip atomically using
50      * {@link #IMPL_UPDATER}.
51      */
52     private volatile AbstractDOMTransactionFactory<?> commitImpl;
53
54     /**
55      * Future task of transaction commit. It starts off as null, but is
56      * set appropriately on {@link #submit()} and {@link #cancel()} via
57      * {@link AtomicReferenceFieldUpdater#lazySet(Object, Object)}.
58      * <p/>
59      * Lazy set is safe for use because it is only referenced to in the
60      * {@link #cancel()} slow path, where we will busy-wait for it. The
61      * fast path gets the benefit of a store-store barrier instead of the
62      * usual store-load barrier.
63      */
64     private volatile Future<?> commitFuture;
65
66     protected AbstractDOMBrokerWriteTransaction(final Object identifier,
67             final Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories,
68             final AbstractDOMTransactionFactory<?> commitImpl) {
69         super(identifier, storeTxFactories);
70         this.commitImpl = requireNonNull(commitImpl, "commitImpl must not be null.");
71     }
72
73     @Override
74     public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) {
75         checkRunning(commitImpl);
76         checkInstanceIdentifierReferencesData(path,data);
77         getSubtransaction(store).write(path, data);
78     }
79
80     private static void checkInstanceIdentifierReferencesData(final YangInstanceIdentifier path,
81             final NormalizedNode data) {
82         checkArgument(data != null, "Attempted to store null data at %s", path);
83         final PathArgument lastArg = path.getLastPathArgument();
84         if (lastArg != null) {
85             checkArgument(lastArg.equals(data.getIdentifier()),
86                 "Instance identifier references %s but data identifier is %s", lastArg, data);
87         }
88     }
89
90     @Override
91     public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
92         checkRunning(commitImpl);
93         getSubtransaction(store).delete(path);
94     }
95
96     @Override
97     public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) {
98         checkRunning(commitImpl);
99         checkInstanceIdentifierReferencesData(path, data);
100         getSubtransaction(store).merge(path, data);
101     }
102
103     @Override
104     public boolean cancel() {
105         final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
106         if (impl != null) {
107             LOG.trace("Transaction {} cancelled before submit", getIdentifier());
108             FUTURE_UPDATER.lazySet(this, CANCELLED_FUTURE);
109             closeSubtransaction();
110             return true;
111         }
112
113         // The transaction is in process of being submitted or cancelled. Busy-wait
114         // for the corresponding future.
115         Future<?> future;
116         do {
117             future = commitFuture;
118         }
119         while (future == null);
120
121         return future.cancel(false);
122     }
123
124     @Override
125     @SuppressWarnings("checkstyle:IllegalCatch")
126     public FluentFuture<? extends CommitInfo> commit() {
127         final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
128         checkRunning(impl);
129
130         FluentFuture<? extends CommitInfo> ret;
131         final var tx = getSubtransaction();
132         if (tx == null) {
133             ret = CommitInfo.emptyFluentFuture();
134         } else {
135             try {
136                 ret = impl.commit(this, tx.ready());
137             } catch (RuntimeException e) {
138                 ret = immediateFailedFluentFuture(TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e));
139             }
140         }
141
142         FUTURE_UPDATER.lazySet(this, ret);
143         return ret;
144     }
145
146     private void checkRunning(final AbstractDOMTransactionFactory<?> impl) {
147         checkState(impl != null, "Transaction %s is no longer running", getIdentifier());
148     }
149
150     @Override
151     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
152         return super.addToStringAttributes(toStringHelper).add("running", commitImpl == null);
153     }
154 }