9dcc71fb03244255be07ef227df5c877987f3020
[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.MoreObjects.ToStringHelper;
12 import com.google.common.base.Preconditions;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.Futures;
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.mdsal.common.api.LogicalDatastoreType;
21 import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
22 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
23 import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
24 import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
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 = Preconditions.checkNotNull(commitImpl, "commitImpl must not be null.");
71     }
72
73     @Override
74     public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
75             final NormalizedNode<?, ?> data) {
76         checkRunning(commitImpl);
77         checkInstanceIdentifierReferencesData(path,data);
78         getSubtransaction(store).write(path, data);
79     }
80
81     private static void checkInstanceIdentifierReferencesData(final YangInstanceIdentifier path,
82             final NormalizedNode<?, ?> data) {
83         Preconditions.checkArgument(data != null, "Attempted to store null data at %s", path);
84         final PathArgument lastArg = path.getLastPathArgument();
85         Preconditions.checkArgument(
86                 lastArg == data.getIdentifier() || lastArg != null && lastArg.equals(data.getIdentifier()),
87                 "Instance identifier references %s but data identifier is %s", lastArg, data);
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,
98             final NormalizedNode<?, ?> data) {
99         checkRunning(commitImpl);
100         checkInstanceIdentifierReferencesData(path, data);
101         getSubtransaction(store).merge(path, data);
102     }
103
104     @Override
105     public boolean cancel() {
106         final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
107         if (impl != null) {
108             LOG.trace("Transaction {} cancelled before submit", getIdentifier());
109             FUTURE_UPDATER.lazySet(this, CANCELLED_FUTURE);
110             closeSubtransactions();
111             return true;
112         }
113
114         // The transaction is in process of being submitted or cancelled. Busy-wait
115         // for the corresponding future.
116         Future<?> future;
117         do {
118             future = commitFuture;
119         }
120         while (future == null);
121
122         return future.cancel(false);
123     }
124
125     @Override
126     @SuppressWarnings("checkstyle:illegalcatch")
127     public CheckedFuture<Void, TransactionCommitFailedException> submit() {
128         final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
129         checkRunning(impl);
130
131         final Collection<T> txns = getSubtransactions();
132         final Collection<DOMStoreThreePhaseCommitCohort> cohorts = new ArrayList<>(txns.size());
133
134         CheckedFuture<Void, TransactionCommitFailedException> ret;
135         try {
136             for (final T txn : txns) {
137                 cohorts.add(txn.ready());
138             }
139
140             ret = impl.submit(this, cohorts);
141         } catch (RuntimeException e) {
142             ret = Futures.immediateFailedCheckedFuture(
143                     TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e));
144         }
145         FUTURE_UPDATER.lazySet(this, ret);
146         return ret;
147     }
148
149     private void checkRunning(final AbstractDOMTransactionFactory<?> impl) {
150         Preconditions.checkState(impl != null, "Transaction %s is no longer running", getIdentifier());
151     }
152
153     @Override
154     protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
155         return super.addToStringAttributes(toStringHelper).add("running", commitImpl == null);
156     }
157 }