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

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