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