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

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