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